需求
连接低功耗蓝牙设备,打印已有的记录内容
思路
Part1:通过uniapp自带的API连接上蓝牙设备,获取到设备的各种信息。
Part2:通过uniapp的API写入字符串与指令
Part1
蓝牙连接代码参考
data() {
return {
//* 设备数组
deviceList: [],
//* 定义一个对象存储设备信息
deviceInfo: {},
//* 默认蓝牙连接状态
blueConnFlag: false,
}
}
//* 蓝牙连接方法
//* 蓝牙初始化
onBlue() {
uni.openBluetoothAdapter({
success: (res) => {
//监听寻找到新设备的事件
this.findDevice();
//监听本机蓝牙适配器状态变化事件
this.onStatus();
},
fail: (err) => {
uni.$u.toast("蓝牙开启失败");
},
});
},
//* 找寻蓝牙设备
findDevice() {
console.log("监听寻找到新设备的事件---------------");
//监听寻找到新设备的事件
uni.onBluetoothDeviceFound((devices) => {
const { name, deviceId } = devices.devices[0];
if (name == "") return;
this.deviceList.push({
name,
deviceId,
services: [],
});
//* 去重
this.deviceList = this.deviceList.filter((item) => item);
});
},
//* 监听蓝牙状态
onStatus() {
uni.getBluetoothAdapterState({
success: function (res) {
console.log(res, "蓝牙搜索状态为");
//本机蓝牙开启时
if (res.available) {
//如在正在搜索设备,则停止搜索
if (res.discovering) {
uni.stopBluetoothDevicesDiscovery();
}
//搜索蓝牙
//开始搜寻附近的蓝牙外围设备
uni.startBluetoothDevicesDiscovery();
} else {
console.log("本机蓝牙不可用");
}
},
});
},
//* 连接蓝牙
onLink(item) {
if (this.deviceInfo.name && this.deviceInfo.deviceId) {
const { deviceId } = item;
console.log("连接蓝牙---------------" + deviceId);
//连接低功耗蓝牙设备。
uni.createBLEConnection({
deviceId: deviceId,
complete: (res) => {
console.log("创建连接的回调", res);
if (res.errMsg != "createBLEConnection:ok") return;
//连接设备时,需断开本机连接设备
// uni.closeBLEConnection({
// deviceId,
// });
// this.connId = deviceId;
// this.currDev = item;
setTimeout(() => {
//获取蓝牙设备所有服务(service)
this.getBLEServices(deviceId);
}, 2000);
},
});
//连接成功 关闭搜索
uni.stopBluetoothDevicesDiscovery();
setTimeout(() => {
this.blueConnFlag = true;
}, 1000);
} else {
uni.$u.toast("请选择蓝牙设备进行连接!");
}
},
//* 断开蓝牙
outLink(item) {
const { deviceId } = item;
uni.closeBLEConnection({
deviceId,
success: (res) => {
uni.$u.toast("蓝牙设备已关闭!");
this.deviceInfo = {};
this.blueConnFlag = false;
},
fail: (err) => {
uni.$u.toast("关闭设备失败,请重新尝试!");
},
});
},
//* 连接设备
getBLEServices(deviceId) {
uni.getBLEDeviceServices({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
complete: (res) => {
// console.log(res, "连接设备获取到的res");
const { services } = res;
if (services) {
services.forEach((item) => {
const { uuid } = item;
uni.getBLEDeviceCharacteristics({
// 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
deviceId: deviceId,
// 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
serviceId: uuid,
success: (res) => {
// console.log("获取的特征值为:", res);
const { characteristics } = res;
for (let block of characteristics) {
if (!block.properties.write) return;
for (let i = 0; i < this.deviceList.length; i++) {
if (
this.deviceList[i].deviceId === this.deviceInfo.deviceId
) {
this.deviceList[i].services.push({
serviceId: uuid,
characteristicId: block.uuid,
});
break;
}
}
}
//* 更新deviceInfo数据
this.deviceInfo = this.deviceList.find(
(item) => item.deviceId === this.deviceInfo.deviceId
);
uni.setStorage({
key: "currDev",
data: this.devicesList,
});
},
});
});
} else {
setTimeout(() => {
this.getBLEServices(deviceId);
}, 2000);
}
},
});
},
Part2 -——由于不同类型打印机的命令不同,我这边大致说一下我的思路,我将发送的的命令与字符串合并成一个二维数组,循环将数组传入,但是需要注意打印的字节数不能超过20字节,如果超过20字节需要分包发送。我这边大致写了一个方法,但是最近打印机故障了还未测试。可自行修改代码适配。||2023.12.21 经测试拆分字节会出现乱码 请使用以下代码,通过拆分数组循环将每个字节数组再进行拆分发送。代码已测 可以使用 , 使用是 直接将二维数组传入send方法就行
蓝牙打印代码参考
async Send(buff) {
let that = this;
//* 循环遍历写入
for (let buffSlice of buff) {
let buffLen = buffSlice.length;
let arrSize = 21;
while (buffLen > 0) {
if (buffLen > arrSize) {
let writeBuf = buffSlice.slice(0, arrSize);
await that.writItByArr(writeBuf);
buffSlice = buffSlice.slice(arrSize);
buffLen = buffSlice.length;
} else {
await that.writItByArr(buffSlice);
break;
}
}
}
},
writItByArr(buff) {
let that = this;
let buf = new ArrayBuffer(buff.length);
let dataView = new DataView(buf);
for (var i = 0; i < buff.length; ++i) {
dataView.setUint8(i, buff[i]);
}
// console.log(this.deviceInfo.deviceId);
return new Promise((resolve, reject) => {
setTimeout(() => {
uni.writeBLECharacteristicValue({
deviceId: that.deviceInfo.deviceId,
serviceId: that.deviceInfo.services[0].serviceId,
characteristicId: that.deviceInfo.services[0].characteristicId,
value: buf,
success: function (res) {
console.log("写入成功", res);
resolve(true);
// uni.$u.toast("打印成功");
},
fail: function (e) {
console.log("写入失败", e);
that.writItByArr(buff);
},
complete: function (res) {
// console.log("发送数", res);
},
});
}, 100);
});
},