天梦星官网 (tmxkj.top)https://tmxkj.top/#/ 编程资源
直接上代码:
ly_text:"点击搜索",
connected_ly:false,//蓝牙按钮是否显示
blue_list_ly:false,//蓝牙连接列表显示
discoveryStarted: false,
devices: [],//设备列表
name: '',
deviceId: '',
chs: [],
canWrite: false,
/**
* 第一步
* @param {打开蓝牙}
* @param {搜索}
*/
openBluetoothAdapter() {
if (!wx.openBluetoothAdapter) {
wx.showModal({
title: '提示',
content: '当前微信版本过低,无法使用该功能,请升级到最新微信版本后重试。'
})
return
}
/**
* 初始化蓝牙模块
*/
this.openBluetoothAdapters()
},
/**
* 第二步
* @param {初始化蓝牙模块}
* @param {请求打开蓝牙}
*/
openBluetoothAdapters() {
this.ly_text="搜索设备中"
uni.openBluetoothAdapter({//请求打开蓝牙情况
success: (res) => {
this.startBluetoothDevicesDiscovery();//打开蓝牙后 开始搜索
},
fail: (err) => {
if (err.errCode === 10001) {
uni.showModal({
title: '错误',
content: '未找到蓝牙设备,请打开蓝牙重试!',
showCancel: false
});
uni.onBluetoothAdapterStateChange(res => {
console.log('请求打开蓝牙失败再次请求', res);
if (res.available) {
uni.onBluetoothAdapterStateChange(() => {});
this.startBluetoothDevicesDiscovery();
}
})
}
}
});
},
/**
* 第三步
* @param {开始搜寻附近的蓝牙外围设备}
*/
startBluetoothDevicesDiscovery() {
this.discoveryStarted = true
uni.startBluetoothDevicesDiscovery({
success: (res) => {
this.onBluetoothDeviceFound();//蓝牙搜索成功后监听搜索
},
fail: (res) => {
console.log('搜索蓝牙失败', res)
}
})
},
/**
* 第四步
* @param {监听寻找到新设备的事件}
* @param {最终得到最后的蓝牙连接列表}
* @param {搜素事件到此结束}
*/
onBluetoothDeviceFound() {
uni.onBluetoothDeviceFound(res => {
//res:发现的设备列表
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return
}
let foundDevices = this.devices;
let idx = this.inArray(foundDevices, 'deviceId', device.deviceId);
let data = {};
if (idx === -1) {
this.devices.push(device);
} else {
this.devices[index] = device;
}
})
if(this.devices.length>=1){
this.blue_list_ly=true;
this.ly_text="发现设备"
}else{
// uni.showToast({
// title:'暂无搜索内容',
// icon:'error'
// })
this.ly_text="未发现设备"
}
console.log('发现的设备列表:', this.devices);
})
},
/**
* 第五步
* @param {手动点击连接蓝牙事件}
* @param {创建连接蓝牙}
* @param {如果已经连接过可直接连接}
*/
_createBLEConnection(e) {
uni.createBLEConnection({
deviceId:e.deviceId,
success: (res) => {
this.blue_list_ly=false;
this.connected_ly=true;
this.ly_text="已连接";
this.name = e.name;
this.deviceId =e.deviceId;
//获取蓝牙
this.getBLEDeviceServices(e.deviceId);
uni.setStorage({
key: LAST_CONNECTED_DEVICE,
data: {
name:e.name,
deviceId:e.deviceId
}
})
},
fail: (err) => {
this.connected_ly =false;
this.ly_text="连接失败";
}
})
this.stopBluetoothDevicesDiscovery();
},
/**
* 第六步
* @param {蓝牙连接成功关闭监听搜索}
* @param {蓝牙搜索比较消耗资源}
*/
stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery({
complete: () => {
console.log('停')
this.discoveryStarted = false
}
})
},
/**
* 第七步
* @param {蓝牙连接成功关闭搜索}
* @param {功能}
*/
closeBLEConnection(e) {
uni.closeBLEConnection({
deviceId: e.deviceId
})
this.connected_ly=false;
},
/**
* 第八步
* @param {蓝牙功能查询}
* @param {蓝牙连接成功后}
* @param {找到主要服务功能}
*/
getBLEDeviceServices(deviceId) {
uni.getBLEDeviceServices({
deviceId,
success: (res) => {
for (let i = 0; i < res.services?.length; i++) {
if (res.services[i].isPrimary) {
this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid);
return
}
}
}
})
},
/**
* 第九步
* @param {蓝牙功能特征查询}
* @param {主要功能的特性}
* @param {找到主要服务功能的特征}
* @param {到此步骤连接结束}
*/
getBLEDeviceCharacteristics(deviceId, serviceId) {
uni.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
for (let i = 0; i < res.characteristics?.length; i++) {
const item = res.characteristics[i]
if (item.properties.write) {
this.canWrite = true;
this._deviceId = deviceId
this._serviceId = serviceId
this._characteristicId = item.uuid
uni.setStorage({
key: "BlueKey",
data: {
_close:true,
_name:this.name,
_deviceId : deviceId,
_serviceId : serviceId,
_characteristicId : item.uuid,
}
})
break;
}
}
setTimeout(()=>{
if (this.canWrite) {
this.connected_ly=true;
this.ly_text="已连接"
} else {
uni.showToast({
icon: 'error',
title: '您当前选择的设备不支持打印功能,请重新选择!',
duration: 3000
})
}
},1000)
},
fail: (res) => {
console.error('获取蓝牙特征失败', res)
}
})
},
/**
* 第十步
* @param {编写蓝牙需要打印的内容}
* @param {打印按钮的事件}
* @param {打印功能前准备}
*/
writeBLECharacteristicValue() {
var that=this
setTimeout(() => {
let printerJobs = new PrinterJobs();
let dayun1 = '当事人 (单位):' + this.listObj?.contactinfo?.client + '\r\n' +
'被处罚人姓名:' + this.listObj?.contactinfo?.name + '\r\n' +
'被处罚人性别:' + this.listObj?.contactinfo?.sex + '\r\n' +
'被处罚人联系方式:' + this.listObj?.contactinfo?.iPhone + '\r\n' +
'被处罚人身份证号码:' + this.listObj?.contactinfo?.idcard + '\r\n'
printerJobs
.setSize(2, 2)
.setAlign('CT')
.print('! 0 100 203 100 1\r\n法决定书\r\nPRINT\r\n')
.setSize(1, 1).setAlign('LT')
.print(dayun1)
let buffer = printerJobs.buffer();
// console.log('ArrayBuffer', 'length: ' + buffer.byteLength, ' hex: ' + this.ab2hex(
// buffer));
// 1.并行调用多次会存在写失败的可能性
// 2.建议每次写入不超过20字节
// 分包处理,延时调用
const maxChunk = 20;
const delay = 20;
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);
setTimeout(this._writeBLECharacteristicValue, j * delay, subPackage);
}
this.lanyardShow = false;
this.$refs.uUpload.clear();
this.clearFormData();
uni.showToast({
title: '打印成功',
icon: 'success'
})
}, 5000)
},
/**
* 第十一步
* @param {最终的打印}
* @param {由第十步骤调用}
* @param {轮询打印}
* @param {打印机输出}
* @param {打印结束}
*/
_writeBLECharacteristicValue(buffer) {
wx.writeBLECharacteristicValue({
deviceId: this._deviceId,
serviceId: this._serviceId,
characteristicId: this._characteristicId,
value: buffer,
success(res) {
console.log('最后执行打印了===========', res)
},
fail(res) {
console.log('打印失败', res)
}
})
},
/**
* 第十二步
* @param {蓝牙相关事件}
* @param {和以上打印不衔接}
* @param {关闭蓝牙}
*/
closeBluetoothAdapter() {
wx.closeBluetoothAdapter()
this.discoveryStarted = false
},
/**
* 第十三步
* @param {判断蓝牙是否已经连接}
* @param {只支持wx. 不支持uni.}
* @param {只支持安卓, 不支持苹果}
*/
isBluetoothDevicePaired(){
var that =this
wx.isBluetoothDevicePaired({
deviceId:uni.getStorageSync("BlueKey")?._deviceId,
success(res){
console.log(res,"判断连接成功")
that.connected_ly=true;
that.ly_text="连接成功"
},fail(err){
console.log(err,"判断连接失败");
that.ly_text="点击搜索"
}
})
},
/**
* 第十四步
* @param {蓝牙相关资源事件}
* @param {搜索 资源 打印}
* @param {转换}
*/
inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i
}
}
return -1
},
ab2hex(buffer) { // ArrayBuffer转16进度字符串示例
const hexArr = Array.prototype.map.call(
new Uint8Array(buffer),
function(bit) {
return ('00' + bit.toString(16)).slice(-2)
}
)
return hexArr.join(',')
},
str2ab(str) {
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;
},
/**
* 第十五步
* @param {进入页面就自动连接}
* @param {该方法存在BUG}
* @param {目前该方法先不投放使用}
*/
createBLEConnectionWithDeviceId(e) {
//创建蓝牙链接
uni.openBluetoothAdapter({
success: (res) => {
let ly_data={
name:uni.getStorageSync("BlueKey")?._deviceId,
deviceId:uni.getStorageSync("BlueKey")?._name
}
this._createBLEConnection(ly_data);
},
fail: (res) => {
if (res.errCode === 10001) {
uni.showModal({
title: '错误',
content: '未找到蓝牙设备, 请打开蓝牙后重试。',
showCancel: false
});
this.connected_ly=false
} else if (res.errCode === -1 || res.errCode === 10010) { //已连接
this.connected_ly = true;
}
}
})
},
/**
* 第十六步
* @param {获取蓝牙适配状态}
* @param {在蓝牙连接成功后调用查看}
* @param {判断连接用}
*/
getBluetoothAdapterState() {
wx.getBluetoothAdapterState({
success: (res) => {
console.log(res)
if(res.available){
this.connected_ly=true
this.ly_text="已连接"
console.log("蓝牙已经连接",res)
}else{
this.connected_ly=false;
this.ly_text="点击连接"
console.log("蓝牙已经断开")
}
}
})
},
html
{{ly_text}}
搜索到的设备
{{item.name ? item.name : item.localName}}
连接
css
.ly-cass-box{
width: 150rpx;
height: auto;
display: flex;
align-items: center;
justify-content: center;
flex-direction: column;
position: fixed;
bottom:70rpx;
right: 50rpx;
z-index: 500;
}
.ly-cass{
width: 120rpx;
height: 120rpx;
background-color: #f4f4f5;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
}
.ly-text{
margin-top: 20rpx;
background-color: #eee;
padding: 2rpx 8rpx 2rpx 8rpx;
border-radius: 6rpx;
font-size: 25rpx;
}
.no-open-gps-tip {
width: 100%;
display: flex;
flex-direction: row;
align-items: center;
color: #fa3534;
font-weight: 400;
font-size: 30rpx;
background: rgba(235, 207, 48, 0.8);
padding: 30rpx;
}
.devices-item {
width: 100%;
display: flex;
justify-content: space-between;
margin-top: 20rpx;
align-items: flex-end;
padding-bottom: 5rpx;
border-bottom: 1px solid #f4f4f5;
}
.devices-list {
width: 100%;
padding: 0 20rpx;
display: flex;
flex-direction: column;
}
.tip-search {
width: 100%;
margin: 20rpx 0;
text-align: left;
font-size: 16px;
color: #2979ff;
}
.has-devices-list-container {
width: 100%;
display: flex;
flex-direction: column;
margin: 30rpx 0;
}
const PrinterJobs = require('./common/printer/printerjobs');//根据自己放的路径调用
const printerUtil = require('./common/printer/printerutil');//根据自己放的路径调用
目录结构
核心代码代码下载
备注:核心代码在头顶上的zip当中
使用逻辑:
1.用户第一次进来点击连接,只用连接一次,只要用户不关闭程序就不会断开,可接着打印,
2.如果已经连接需要在主动加载函数里面调用判断是否已经连接