printer.js
var printerData = {
connected:false,
connectedName:'weihuang',
deviceInfo:{},
deviceId:'EC:11:27:88:F3:D8',
deviceName:'weihuang',
serviceId:'000018F0-0000-1000-8000-00805F9B34FB',
characteristId:'00002AF1-0000-1000-8000-00805F9B34FB',
}
var trying = false;
function openBluetoothAdapter()
{
// device.checkOpenGPSService();
uni.openBluetoothAdapter({
success: (res) => {
console.log('openBluetoothAdapter success', res);
createBLEConnection();
// this.startBluetoothDevicesDiscovery()
},
fail: (res) => {
// if (res.errCode === 10001) {
// uni.onBluetoothAdapterStateChange(function (res) {
// console.log('onBluetoothAdapterStateChange', res)
// if (res.available) {
// this.startBluetoothDevicesDiscovery()
// }
// })
// }
console.log('openBluetoothAdapter fail', res);
}
})
}
function onBLEConnectionStateChange()
{
console.log('onBLEConnectionStateChange');
uni.onBLEConnectionStateChange(res => {
// 该方法回调中可以用于处理连接意外断开等异常情况
console.log(`蓝牙连接状态 -------------------------->`);
console.log(JSON.stringify(res));
if (res.deviceId==='EC:11:27:88:F3:D8'&&!res.connected) {
// if (this.isStop) return;
// console.log('断开低功耗蓝牙成功:');
if(trying)
{
return;
}
printerData.connected=false;
uni.showToast({
icon: "none",
title: "蓝牙已经断开!",
mask: false,
duration: 3000
});
closeBLEConnection();
setTimeout(function(){
trying = true;
return createBLEConnection()
},1000)
// createBLEConnection();
// 要用闭包,不然会有空指针错误
// setTimeout(createBLEConnection,1000);
// setTimeout(function(){
// return createBLEConnection()
// },3000)
//在这里尝试重连
// createBLEConnection(callback,buffer);
//关闭连接
// this.closeBluetoothAdapter();
}
});
// setInterval(onBLEConnectionStateChange,1000);
}
function closeBLEConnection(){
uni.closeBLEConnection({
deviceId:printerData.deviceId,
success:res=> {
// this.isLink.splice(index,1,4)
console.log('closeBLEConnection',res)
}
})
}
function closeBluetoothAdapter(){
uni.closeBluetoothAdapter({
success: res => {
// this.appendMSG("closeBluetoothAdapter success",res);
console.log('关闭蓝牙适配器');
}
});
}
// 可以不用发现直接连接
function startBluetoothDevicesDiscovery() { //开始扫描
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: (res) => {
console.log('startBluetoothDevicesDiscovery success', res)
// this.onBluetoothDeviceFound()
},
})
}
function createBLEConnection(){
console.log("createBLEConnection")
uni.createBLEConnection({
deviceId:printerData.deviceId,
timeout: 4000,
success: (res) => {
uni.showToast({
title: '连接蓝牙打印机成功!',
icon: 'success',
duration: 1000,
mask: true
})
printerData.connected=true;
console.log("createBLEConnection success",JSON.stringify(res))
trying = false;
},
fail(err) {
console.log("连接失败,错误=", err)
// 要用闭包,不然会有空指针错误
// setTimeout(createBLEConnection,1000);
setTimeout(function(){
return createBLEConnection()
},1000)
},
})
}
function notifyBLECharacteristicValueChange()
{
let deviceId = printerData.deviceId;
let serviceId = printerData.serviceId;
let characteristicId = printerData.characteristId;
uni.notifyBLECharacteristicValueChange({
state: true, // 启用 notify 功能
deviceId,
serviceId,
characteristicId,
success: res => {
uni.onBLECharacteristicValueChange((res) => {
console.log('特征值变化:', res)
});
},
fail: res => {
console.log('notifyBLECharacteristicValueChange 失败:' + res.errMsg);
}
});
}
function SendArray(buffer){
console.log('sendarray',buffer.byteLength);
if (printerData.connected == false) {
uni.showToast({
title: '蓝牙未连接,取消操作',
duration: 1000,
mask: true
})
console.log("SendArray connected 的值为false,取消发送")
return
}
// 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(writeData, j * delay, subPackage);
}
}
function writeData(tmpBuffer) { //发送数据,蓝牙设备特征值对应的二进制值
// console.log('writeData',tmpBuffer);
uni.writeBLECharacteristicValue({
deviceId: printerData.deviceId,
serviceId: printerData.serviceId,
characteristicId: printerData.characteristId,
value: tmpBuffer,
success: (res) => {
// console.log("发送成功:"+charjs.buffer2String(tmpBuffer),tmpBuffer.byteLength)
},
fail: (res) => {
console.log("发送失败:",res)
uni.showToast({
title: "发送失败" + res.errMsg,
icon: '../icon/fail',
duration: 1000
})
},
})
}
module.exports = {
openBluetoothAdapter: openBluetoothAdapter,
closeBluetoothAdapter:closeBluetoothAdapter,
onBLEConnectionStateChange:onBLEConnectionStateChange,
}
App.vue
<script>
import printer from 'common/printer.js'
export default {
onLaunch: function() {
console.log('App Launch')
},
onShow: function() {
console.log('App Show')
printer.openBluetoothAdapter();
printer.onBLEConnectionStateChange();
},
onHide: function() {
console.log('App Hide')
}
}
</script>
<style>
/*每个页面公共css */
</style>