<template>
<view class="container">
<button @click="initializeBluetoothProcess">搜索蓝牙设备</button>
<view class="device-list">
<view v-for="device in filteredDevices" :key="device.deviceId" class="device-card">
<view class="device-info" @click="connectDevice(device)">
<view class="device-name">{{ device.name }}</view>
<view class="device-id">ID: {{ device.deviceId }}</view>
<view class="device-rssi">信号强度: {{ device.RSSI }} dBm</view>
<view class="device-status">
{{ getDeviceStatus(device) }}
</view>
</view>
<button class="disconnect-button" @click="disconnectDevice(device)"
v-if="device.deviceId === deviceId && isConnected">
断开连接
</button>
</view>
</view>
<button @click="sendPrintCommand" :disabled="!isConnected">打印测试</button>
</view>
</template>
<script>
export default {
data() {
return {
isBluetoothAvailable: false,
isConnected: false,
isConnecting: false,
deviceId: '',
serviceId: '',
characteristicId: '',
devices: [], // 用于存储发现的蓝牙设备
}
},
computed: {
filteredDevices() {
return this.devices.filter(device =>
device.name && device.name.trim() !== '' && device.RSSI > -80
);
}
},
methods: {
// 检查并初始化蓝牙
async checkAndInitBluetooth() {
try {
await this.openBluetoothAdapter()
const isBluetoothEnabled = await this.checkBluetoothEnabled()
if (!isBluetoothEnabled) {
throw new Error('蓝牙未启用')
}
this.isBluetoothAvailable = true
console.log('蓝牙已准备就绪')
} catch (error) {
console.error('蓝牙初始化失败:', error)
uni.showToast({
title: '蓝牙初始化失败: ' + error.message,
icon: 'none'
})
}
},
// 打开蓝牙适配器
openBluetoothAdapter() {
return new Promise((resolve, reject) => {
uni.openBluetoothAdapter({
success: () => {
console.log('蓝牙适配器已打开')
resolve()
},
fail: (err) => {
console.error('无法打开蓝牙适配器:', err)
reject(new Error('无法打开蓝牙适配器'))
}
})
})
},
// 检查蓝牙是否已启用
checkBluetoothEnabled() {
return new Promise((resolve) => {
uni.getBluetoothAdapterState({
success: (res) => {
resolve(res.available)
},
fail: () => {
resolve(false)
}
})
})
},
// 开始搜索蓝牙设备
startBluetoothDevicesDiscovery() {
uni.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: (res) => {
console.log('开始搜索蓝牙设备')
this.onBluetoothDeviceFound()
},
fail: (err) => {
console.error('搜索蓝牙设备失败', err)
}
})
},
// 监听新设备的发现
onBluetoothDeviceFound() {
uni.onBluetoothDeviceFound((res) => {
res.devices.forEach((device) => {
if (device.name && device.name.trim() !== '' && device.RSSI > -80) {
const existingDeviceIndex = this.devices.findIndex(d => d.deviceId === device
.deviceId)
if (existingDeviceIndex !== -1) {
this.$set(this.devices, existingDeviceIndex, device)
} else {
this.devices.push(device)
}
}
})
})
},
// 连接到选中的蓝牙设备
async connectDevice(device) {
if (this.isConnecting) {
uni.showToast({
title: '正在连接中,请稍候',
icon: 'none'
})
return
}
if (this.isConnected) {
await this.disconnectDevice({
deviceId: this.deviceId
})
}
this.isConnecting = true
this.deviceId = device.deviceId
uni.createBLEConnection({
deviceId: this.deviceId,
success: (res) => {
console.log('连接成功')
this.isConnected = true
this.isConnecting = false
this.getBLEDeviceServices()
},
fail: (err) => {
console.error('连接失败', err)
this.isConnecting = false
uni.showToast({
title: '连接失败',
icon: 'none'
})
}
})
},
// 断开蓝牙连接
disconnectDevice(device) {
return new Promise((resolve) => {
if (device.deviceId === this.deviceId && this.isConnected) {
uni.closeBLEConnection({
deviceId: this.deviceId,
success: () => {
this.isConnected = false
this.deviceId = ''
this.serviceId = ''
this.characteristicId = ''
console.log('蓝牙连接已断开')
resolve()
},
fail: (err) => {
console.error('断开连接失败', err)
resolve()
}
})
} else {
resolve()
}
})
},
// 获取蓝牙设备的服务
getBLEDeviceServices() {
uni.getBLEDeviceServices({
deviceId: this.deviceId,
success: (res) => {
for (let i = 0; i < res.services.length; i++) {
if (res.services[i].isPrimary) {
this.serviceId = res.services[i].uuid
this.getBLEDeviceCharacteristics()
return
}
}
},
fail: (err) => {
console.error('获取服务失败', err)
}
})
},
// 获取蓝牙设备的特征值
getBLEDeviceCharacteristics() {
uni.getBLEDeviceCharacteristics({
deviceId: this.deviceId,
serviceId: this.serviceId,
success: (res) => {
for (let i = 0; i < res.characteristics.length; i++) {
if (res.characteristics[i].properties.write) {
this.characteristicId = res.characteristics[i].uuid
return
}
}
},
fail: (err) => {
console.error('获取特征值失败', err)
}
})
},
// 发送打印指令
sendPrintCommand() {
if (!this.isConnected) {
uni.showToast({
title: '请先连接打印机',
icon: 'none'
})
return
}
// 这里的打印指令需要根据你的打印机型号和要求来定
//数据发送需要拆包,安卓有字节限制
const command = new Uint8Array([0x1B, 0x40, 0x1B, 0x21, 0x00, 0x1B, 0x61, 0x01, 0x48, 0x65, 0x6C, 0x6C,
0x6F, 0x20, 0x57, 0x6F, 0x72, 0x6C, 0x64, 0x0A, 0x1D, 0x56, 0x00
])
uni.writeBLECharacteristicValue({
deviceId: this.deviceId,
serviceId: this.serviceId,
characteristicId: this.characteristicId,
value: command.buffer,
success: (res) => {
console.log('打印指令发送成功')
uni.showToast({
title: '打印指令已发送',
icon: 'success'
})
},
fail: (err) => {
console.error('打印指令发送失败', err)
uni.showToast({
title: '打印指令发送失败',
icon: 'none'
})
}
})
},
// 主函数:初始化并连接打印机
async initializeBluetoothProcess() {
try {
await this.checkAndInitBluetooth()
if (this.isBluetoothAvailable) {
this.devices = [] // 清空之前的设备列表
this.startBluetoothDevicesDiscovery()
}
} catch (error) {
uni.showToast({
title: '蓝牙初始化失败',
icon: 'none'
})
}
},
// 停止搜索蓝牙设备
stopBluetoothDevicesDiscovery() {
uni.stopBluetoothDevicesDiscovery()
},
// 关闭蓝牙模块
closeBluetoothAdapter() {
uni.closeBluetoothAdapter()
this.isBluetoothAvailable = false
},
// 获取设备状态
getDeviceStatus(device) {
if (device.deviceId === this.deviceId) {
if (this.isConnecting) {
return '连接中...'
} else if (this.isConnected) {
return '已连接'
}
}
return '未连接'
}
},
onUnload() {
// 页面卸载时清理蓝牙连接
this.disconnectDevice({
deviceId: this.deviceId
})
this.stopBluetoothDevicesDiscovery()
this.closeBluetoothAdapter()
}
}
</script>
<style>
.container {
padding: 20px;
}
button {
margin: 10px 0;
}
.device-list {
margin-top: 20px;
}
.device-card {
background-color: #f0f0f0;
border-radius: 10px;
padding: 15px;
margin-bottom: 10px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.device-info {
flex: 1;
}
.device-name {
font-size: 18px;
font-weight: bold;
margin-bottom: 5px;
}
.device-id,
.device-rssi,
.device-status {
font-size: 14px;
color: #666;
}
.device-status {
margin-top: 5px;
font-weight: bold;
}
.disconnect-button {
background-color: #ff4d4f;
color: white;
border: none;
padding: 5px 10px;
border-radius: 5px;
}
</style>
uniapp 蓝牙连接
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 一. 蓝牙基础知识介绍 1.1 蓝牙设备 蓝牙设备是一种无线通信技术,用于在短距离范围内传输数据。它可以连接多种电...