<template>
|
<view>
|
<!-- 蓝牙连接状态 MAC地址 -->
|
<view class="connection-status">
|
<view style="display: flex; flex-direction: row; gap: 20rpx;padding: 20rpx;">
|
<view style="width: 5rem;">连接设备: </view>
|
<view v-if="$printer.isConnected() === false">无</view>
|
<view v-else="$printer.isConnected() === true"
|
style="flex: 1;display: inline-flex;flex-direction: row;justify-content: space-between;">
|
<view>{{ $printer.connectedDevice().name }}</view>
|
<view>{{ $printer.connectedDevice().address }}</view>
|
</view>
|
</view>
|
</view>
|
<!-- 操作区 -->
|
<view class="buttons">
|
<button class="btn-c" @click="searchLabelPrinter()">搜索打印机</button>
|
<button class="btn-d" @click="closeBluetooth()">断开连接</button>
|
</view>
|
<!-- 设备列表 -->
|
<scroll-view scroll-y="true" style="height: calc(80vh - 8rem);">
|
<view v-for="(device, index) in discoveredDevices" :key="device.address">
|
<uni-card :title="device.name" :extra="connectedDeviceId === device.address?'已连接':'未连接'"
|
style="margin: 10px;">
|
<view class="operation-zone">
|
<button class="op1" size="mini" plain @click="connectBT(device)">连接设备</button>
|
</view>
|
</uni-card>
|
</view>
|
</scroll-view>
|
</view>
|
</template>
|
|
<script>
|
import printerMeta from "../../static/json/printerMeta.json";
|
import {
|
CommonUtils
|
} from '../../utils/common';
|
import permission from '@/plugins/permission.js'
|
import {
|
InputImage
|
} from '@psdk/frame-imageb';
|
import {
|
ConnectedDevice,
|
Lifecycle,
|
Raw,
|
FakeConnectedDevice,
|
WriteOptions,
|
} from '@psdk/frame-father';
|
import {
|
getAddress
|
} from '../../utils/auth';
|
import blueToothTool from '@/plugins/BluetoothTool.js';
|
import { nextTick } from "vue";
|
export default {
|
name: "blueToothPrinterConnector",
|
data() {
|
return {
|
discoveredDevices: [], // 查询到的设备
|
connectedDeviceId: "",
|
readSuccess: false,
|
clock: null,
|
};
|
},
|
methods: {
|
async checkPermission() { // 授权
|
try {
|
let checkResult = await permission.androidPermissionCheck("bluetooth");
|
console.log("检测信息:", checkResult);
|
if (checkResult.code == 1) {
|
let result = checkResult.data;
|
if (result == 1) {
|
console.log("授权成功!");
|
}
|
if (result == 0) {
|
console.log("授权已拒绝!");
|
}
|
if (result == -1) {
|
console.log("您已永久拒绝权限,请在应用设置中手动打开!");
|
}
|
}
|
} catch (err) {
|
console.log("授权失败:", err);
|
}
|
},
|
async searchLabelPrinter() {
|
// 查找打印机
|
var that = this
|
// 使用openBluetoothAdapter 接口,免去主动申请权限的麻烦
|
uni.openBluetoothAdapter({
|
success: async (res) => {
|
await this.checkPermission();
|
console.log('start discovery devices');
|
this.discoveredDevices = [];
|
console.log(res)
|
blueToothTool.discoveryNewDevice();
|
},
|
fail: async (e) => {
|
console.error(e)
|
if(e.errCode == 10009) {
|
this.showToast('此设备不支持设备搜索功能!');
|
}
|
}
|
})
|
|
},
|
onDevice(device) {
|
console.log("监听寻找到新设备的事件---------------")
|
console.log(device)
|
if (typeof device === 'undefined') return;
|
if (typeof device.name === 'undefined') return;
|
console.log(device.name);
|
if (device.name === '') return;
|
if (device.name === null) return;
|
if (device.name.toUpperCase().endsWith('_BLE') ||
|
device.name.toUpperCase().endsWith('-LE') ||
|
device.name.toUpperCase().endsWith('-BLE')) return;
|
const isDuplicate = this.discoveredDevices.find(item => item.address === device.address);
|
if (isDuplicate) return;
|
this.discoveredDevices.push(device);
|
},
|
connectBT(device) {
|
const vm = this;
|
uni.showLoading({
|
title: '连接中'
|
});
|
blueToothTool.connDevice(device.address, (result) => {
|
console.log("设备MAC地址: ", device.address)
|
console.log("printer:", vm.$printer._connectedDevice)
|
uni.hideLoading()
|
if (result) {
|
// // console.log(result);
|
blueToothTool.cancelDiscovery();
|
// console.log(vm.$printer)
|
vm.$printer.init(new FakeConnectedDevice());
|
vm.connectedDeviceId = device.address;
|
vm.$printer._connectedDevice.address = device.address
|
vm.$printer._connectedDevice.name = device.name
|
console.log("printer:", vm.$printer._connectedDevice)
|
uni.showToast({
|
icon: 'none',
|
title: '连接成功'
|
})
|
|
} else {
|
uni.showToast({
|
icon: 'none',
|
title: '连接失败'
|
})
|
}
|
});
|
},
|
stopSearchBT() {
|
console.log("停止搜寻附近的蓝牙外围设备---------------")
|
blueToothTool.cancelDiscovery();
|
},
|
closeBluetooth() {
|
console.log("停止蓝牙连接")
|
const vm = this;
|
if (vm.connectedDeviceId != '') {
|
blueToothTool.closeBtSocket();
|
vm.connectedDeviceId = "";
|
vm.$printer._connectedDevice = null
|
}
|
|
},
|
showToast(msg, status = "none") {
|
uni.showToast({
|
title: msg,
|
icon: status,
|
duration: 2000
|
});
|
},
|
async checkReadSuccess(count) {
|
// 批量插入时,如果前一次发送成功,则清除前一次的时钟
|
if (this.clock != null) {
|
this.clock.stop();
|
this.clock = null;
|
}
|
let that = this
|
return new Promise((resolve, reject) => {
|
let currentCount = 0;
|
that.clock = new CommonUtils.timeClock(() => {
|
console.log(that.readSuccess)
|
currentCount++;
|
if (that.readSuccess == true) {
|
that.clock.stop();
|
resolve(true);
|
} else if (currentCount >= count) {
|
that.clock.stop();
|
reject(new Error('读取超时'));
|
}
|
}, printerMeta['timeoutPerMillSecond']);
|
|
// 启动时钟
|
that.clock.start();
|
});
|
},
|
async sendMessage(cmd) {
|
cmd = Array.from(this.uint8ArrayToSignedArray(cmd))
|
uni.showLoading({
|
title: "发送中..."
|
})
|
// console.log("msg: " + cmd);
|
let that = this
|
return new Promise((resolve, reject) => {
|
const result = blueToothTool.sendByteData(cmd);
|
if (!result) {
|
this.clock.stop();
|
reject("发送失败,请重试...")
|
}
|
that.checkReadSuccess(printerMeta['timeoutCount'])
|
.then((res) => {
|
if (res === true) {
|
resolve(true)
|
}
|
})
|
.catch((err) => {
|
this.clock.stop();
|
reject('设备异常,请检查设备状态...')
|
})
|
.finally(() => {
|
that.readSuccess = false
|
})
|
})
|
|
},
|
uint8ArrayToSignedArray(uint8Array) {
|
let signedArray = new Array(uint8Array.length);
|
for (let i = 0; i < uint8Array.length; i++) {
|
if (uint8Array[i] >= 128) {
|
signedArray[i] = uint8Array[i] - 256;
|
} else {
|
signedArray[i] = uint8Array[i];
|
}
|
}
|
return signedArray;
|
},
|
},
|
async mounted() {
|
//#ifdef APP-PLUS
|
// 蓝牙
|
console.log("蓝牙初始化")
|
blueToothTool.init({
|
listenBTStatusCallback: (state) => {
|
if (state == 'STATE_ON') {
|
console.log(state);
|
}
|
if (state == 'STATE_OFF') {
|
console.log(state);
|
this.closeBluetooth()
|
}
|
},
|
discoveryDeviceCallback: this.onDevice,
|
discoveryFinishedCallback: function() {
|
console.log("搜索完成");
|
},
|
readDataCallback: (dataByteArr) => {
|
// if(that.receiveDataArr.length >= 200) {
|
// that.receiveDataArr = [];
|
// }
|
// that.receiveDataArr.push.apply(that.receiveDataArr, dataByteArr);
|
this.readSuccess = true
|
console.log("读取完成" + dataByteArr);
|
},
|
connExceptionCallback: function(e) {
|
console.log(e);
|
}
|
});
|
|
if (this.$printer.isConnected()) {
|
this.connectedDeviceId = this.$printer.connectedDevice().address
|
}
|
//#endif
|
},
|
}
|
</script>
|
|
<style lang="scss" scoped>
|
.buttons {
|
width: 100%;
|
display: flex;
|
justify-content: center;
|
margin-top: 20rpx;
|
|
button {
|
border-radius: 50rpx;
|
width: 220rpx;
|
height: 66rpx;
|
line-height: 66rpx;
|
font-size: 28rpx;
|
}
|
|
.btn-a {
|
background-color: #acacac;
|
color: #fff;
|
}
|
|
.btn-b {
|
background-color: #41a863;
|
color: #fff;
|
}
|
|
.btn-c {
|
background-color: #3a78ff;
|
color: #fff;
|
}
|
|
.btn-d {
|
background-color: #da0000;
|
color: #fff;
|
}
|
}
|
|
.operation-zone {
|
display: flex;
|
justify-content: space-around;
|
margin-top: 10rpx;
|
|
.op1 {
|
border: 1px solid #41a863;
|
color: #41a863;
|
}
|
|
.op4 {
|
border: 1px solid #da0000;
|
color: #da0000;
|
}
|
|
}
|
</style>
|