天夢(mèng)星官網(wǎng) (tmxkj.top)https://tmxkj.top/#/? 編程資源
直接上代碼:
ly_text:"點(diǎn)擊搜索",
connected_ly:false,//藍(lán)牙按鈕是否顯示
blue_list_ly:false,//藍(lán)牙連接列表顯示
discoveryStarted: false,
devices: [],//設(shè)備列表
name: '',
deviceId: '',
chs: [],
canWrite: false,
/**
* 第一步
* @param {打開(kāi)藍(lán)牙}
* @param {搜索}
*/
openBluetoothAdapter() {
if (!wx.openBluetoothAdapter) {
wx.showModal({
title: '提示',
content: '當(dāng)前微信版本過(guò)低,無(wú)法使用該功能,請(qǐng)升級(jí)到最新微信版本后重試。'
})
return
}
/**
* 初始化藍(lán)牙模塊
*/
this.openBluetoothAdapters()
},
/**
* 第二步
* @param {初始化藍(lán)牙模塊}
* @param {請(qǐng)求打開(kāi)藍(lán)牙}
*/
openBluetoothAdapters() {
this.ly_text="搜索設(shè)備中"
uni.openBluetoothAdapter({//請(qǐng)求打開(kāi)藍(lán)牙情況
success: (res) => {
this.startBluetoothDevicesDiscovery();//打開(kāi)藍(lán)牙后 開(kāi)始搜索
},
fail: (err) => {
if (err.errCode === 10001) {
uni.showModal({
title: '錯(cuò)誤',
content: '未找到藍(lán)牙設(shè)備,請(qǐng)打開(kāi)藍(lán)牙重試!',
showCancel: false
});
uni.onBluetoothAdapterStateChange(res => {
console.log('請(qǐng)求打開(kāi)藍(lán)牙失敗再次請(qǐng)求', res);
if (res.available) {
uni.onBluetoothAdapterStateChange(() => {});
this.startBluetoothDevicesDiscovery();
}
})
}
}
});
},
/**
* 第三步
* @param {開(kāi)始搜尋附近的藍(lán)牙外圍設(shè)備}
*/
startBluetoothDevicesDiscovery() {
this.discoveryStarted = true
uni.startBluetoothDevicesDiscovery({
success: (res) => {
this.onBluetoothDeviceFound();//藍(lán)牙搜索成功后監(jiān)聽(tīng)搜索
},
fail: (res) => {
console.log('搜索藍(lán)牙失敗', res)
}
})
},
/**
* 第四步
* @param {監(jiān)聽(tīng)尋找到新設(shè)備的事件}
* @param {最終得到最后的藍(lán)牙連接列表}
* @param {搜素事件到此結(jié)束}
*/
onBluetoothDeviceFound() {
uni.onBluetoothDeviceFound(res => {
//res:發(fā)現(xiàn)的設(shè)備列表
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="發(fā)現(xiàn)設(shè)備"
}else{
// uni.showToast({
// title:'暫無(wú)搜索內(nèi)容',
// icon:'error'
// })
this.ly_text="未發(fā)現(xiàn)設(shè)備"
}
console.log('發(fā)現(xiàn)的設(shè)備列表:', this.devices);
})
},
/**
* 第五步
* @param {手動(dòng)點(diǎn)擊連接藍(lán)牙事件}
* @param {創(chuàng)建連接藍(lán)牙}
* @param {如果已經(jīng)連接過(guò)可直接連接}
*/
_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;
//獲取藍(lán)牙
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 {藍(lán)牙連接成功關(guān)閉監(jiān)聽(tīng)搜索}
* @param {藍(lán)牙搜索比較消耗資源}
*/
stopBluetoothDevicesDiscovery() {
wx.stopBluetoothDevicesDiscovery({
complete: () => {
console.log('停')
this.discoveryStarted = false
}
})
},
/**
* 第七步
* @param {藍(lán)牙連接成功關(guān)閉搜索}
* @param {功能}
*/
closeBLEConnection(e) {
uni.closeBLEConnection({
deviceId: e.deviceId
})
this.connected_ly=false;
},
/**
* 第八步
* @param {藍(lán)牙功能查詢}
* @param {藍(lán)牙連接成功后}
* @param {找到主要服務(wù)功能}
*/
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 {藍(lán)牙功能特征查詢}
* @param {主要功能的特性}
* @param {找到主要服務(wù)功能的特征}
* @param {到此步驟連接結(jié)束}
*/
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: '您當(dāng)前選擇的設(shè)備不支持打印功能,請(qǐng)重新選擇!',
duration: 3000
})
}
},1000)
},
fail: (res) => {
console.error('獲取藍(lán)牙特征失敗', res)
}
})
},
/**
* 第十步
* @param {編寫(xiě)藍(lán)牙需要打印的內(nèi)容}
* @param {打印按鈕的事件}
* @param {打印功能前準(zhǔn)備}
*/
writeBLECharacteristicValue() {
var that=this
setTimeout(() => {
let printerJobs = new PrinterJobs();
let dayun1 = '當(dāng)事人 (單位):' + this.listObj?.contactinfo?.client + '\r\n' +
'被處罰人姓名:' + this.listObj?.contactinfo?.name + '\r\n' +
'被處罰人性別:' + this.listObj?.contactinfo?.sex + '\r\n' +
'被處罰人聯(lián)系方式:' + this.listObj?.contactinfo?.iPhone + '\r\n' +
'被處罰人身份證號(hào)碼:' + this.listObj?.contactinfo?.idcard + '\r\n'
printerJobs
.setSize(2, 2)
.setAlign('CT')
.print('! 0 100 203 100 1\r\n法決定書(shū)\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.并行調(diào)用多次會(huì)存在寫(xiě)失敗的可能性
// 2.建議每次寫(xiě)入不超過(guò)20字節(jié)
// 分包處理,延時(shí)調(diào)用
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 {由第十步驟調(diào)用}
* @param {輪詢打印}
* @param {打印機(jī)輸出}
* @param {打印結(jié)束}
*/
_writeBLECharacteristicValue(buffer) {
wx.writeBLECharacteristicValue({
deviceId: this._deviceId,
serviceId: this._serviceId,
characteristicId: this._characteristicId,
value: buffer,
success(res) {
console.log('最后執(zhí)行打印了===========', res)
},
fail(res) {
console.log('打印失敗', res)
}
})
},
/**
* 第十二步
* @param {藍(lán)牙相關(guān)事件}
* @param {和以上打印不銜接}
* @param {關(guān)閉藍(lán)牙}
*/
closeBluetoothAdapter() {
wx.closeBluetoothAdapter()
this.discoveryStarted = false
},
/**
* 第十三步
* @param {判斷藍(lán)牙是否已經(jīng)連接}
* @param {只支持wx. 不支持uni.}
* @param {只支持安卓, 不支持蘋(píng)果}
*/
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="點(diǎn)擊搜索"
}
})
},
/**
* 第十四步
* @param {藍(lán)牙相關(guān)資源事件}
* @param {搜索 資源 打印}
* @param {轉(zhuǎn)換}
*/
inArray(arr, key, val) {
for (let i = 0; i < arr.length; i++) {
if (arr[i][key] === val) {
return i
}
}
return -1
},
ab2hex(buffer) { // ArrayBuffer轉(zhuǎn)16進(jìn)度字符串示例
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 {進(jìn)入頁(yè)面就自動(dòng)連接}
* @param {該方法存在BUG}
* @param {目前該方法先不投放使用}
*/
createBLEConnectionWithDeviceId(e) {
//創(chuàng)建藍(lán)牙鏈接
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: '錯(cuò)誤',
content: '未找到藍(lán)牙設(shè)備, 請(qǐng)打開(kāi)藍(lán)牙后重試。',
showCancel: false
});
this.connected_ly=false
} else if (res.errCode === -1 || res.errCode === 10010) { //已連接
this.connected_ly = true;
}
}
})
},
/**
* 第十六步
* @param {獲取藍(lán)牙適配狀態(tài)}
* @param {在藍(lán)牙連接成功后調(diào)用查看}
* @param {判斷連接用}
*/
getBluetoothAdapterState() {
wx.getBluetoothAdapterState({
success: (res) => {
console.log(res)
if(res.available){
this.connected_ly=true
this.ly_text="已連接"
console.log("藍(lán)牙已經(jīng)連接",res)
}else{
this.connected_ly=false;
this.ly_text="點(diǎn)擊連接"
console.log("藍(lán)牙已經(jīng)斷開(kāi)")
}
}
})
},
html
<view class="ly-cass-box">
<view class="ly-cass" @click="openBluetoothAdapter()">
<image src="../../static/bluetooth.png" style="width: 70rpx;height: 70rpx;" />
</view>
<text class="ly-text">{{ly_text}}</text>
</view>
<u-popup v-model="blue_list_ly" mode="center" border-radius="14" mask-close-able=false closeable=true
width=85%>
<view style="margin: 80rpx 20rpx 30rpx 20rpx;">
<view class="has-devices-list-container">
<view class="tip-search">搜索到的設(shè)備</view>
<view class="devices-list">
<view v-for="(item,index) in devices" :key="index" class="devices-item">
<view>{{item.name ? item.name : item.localName}}</view>
<u-button size="mini" type="warning" @click="_createBLEConnection(item)">
連接
</u-button>
</view>
</view>
</view>
</view>
</u-popup>
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;
}
打印執(zhí)行的方法(這個(gè)方法已經(jīng)封裝好調(diào)用即可)
const PrinterJobs = require('./common/printer/printerjobs');//根據(jù)自己放的路徑調(diào)用
const printerUtil = require('./common/printer/printerutil');//根據(jù)自己放的路徑調(diào)用
目錄結(jié)構(gòu)
?核心代碼代碼下載
備注:核心代碼在頭頂上的zip當(dāng)中
使用邏輯:
1.用戶第一次進(jìn)來(lái)點(diǎn)擊連接,只用連接一次,只要用戶不關(guān)閉程序就不會(huì)斷開(kāi),可接著打印,文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-610380.html
2.如果已經(jīng)連接需要在主動(dòng)加載函數(shù)里面調(diào)用判斷是否已經(jīng)連接文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-610380.html
到了這里,關(guān)于uniapp 微信小程序小票打印機(jī)打印教程(超詳細(xì)講解) 完整代碼,下載后可直接使用的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!