写一个微信小程序实习蓝牙连接和数据传输
时间: 2024-02-12 21:02:37 浏览: 141
微信小程序连接蓝牙设备
首先,需要在微信开发者工具中新建一个小程序项目。然后,按照以下步骤实现蓝牙连接和数据传输:
1. 在 app.json 文件中添加以下代码:
```
"permission": {
"scope.userLocation": {
"desc": "你的位置信息将用于蓝牙设备连接"
},
"scope.bluetooth": {
"desc": "你的蓝牙信息将用于连接蓝牙设备"
}
}
```
这样可以获取用户的位置和蓝牙权限。
2. 在 index.wxml 文件中添加以下代码:
```
<view class='container'>
<view class='devices'>
<view class='device' wx:for="{{devices}}" wx:key="{{index}}" bindtap='connect'>
<text>{{item.name}}</text>
<text>{{item.deviceId}}</text>
</view>
</view>
<view class='data'>
<form bindsubmit='sendData'>
<input type='text' placeholder='请输入发送内容' bindinput='inputData' value='{{inputValue}}' />
<button type='submit'>发送</button>
</form>
</view>
</view>
```
这个代码主要是用来显示蓝牙设备和发送数据。
3. 在 index.js 文件中添加以下代码:
```
const app = getApp()
Page({
data: {
devices: [],
connectedDeviceId: '',
inputValue: '',
characteristics: [],
connected: false
},
onReady() {
wx.onBluetoothAdapterStateChange(function (res) {
console.log('蓝牙适配器状态变化', res)
})
wx.onBluetoothDeviceFound((devices) => {
devices.forEach(device => {
if (!device.name && !device.localName) {
return
}
const foundDevices = this.data.devices
const idx = app.globalData.devices.findIndex(item => item.deviceId === device.deviceId)
if (idx === -1) {
foundDevices.push(device)
} else {
foundDevices[idx] = device
}
this.setData({
devices: foundDevices
})
})
})
wx.onBLEConnectionStateChange((res) => {
console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
this.setData({
connected: res.connected
})
})
},
openBluetoothAdapter() {
wx.openBluetoothAdapter({
success: (res) => {
console.log('初始化蓝牙适配器成功', res)
this.startBluetoothDevicesDiscovery()
},
fail: (res) => {
wx.showToast({
title: '请开启蓝牙',
icon: 'none'
})
}
})
},
startBluetoothDevicesDiscovery() {
if (this._discoveryStarted) {
return
}
this._discoveryStarted = true
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: false,
success: (res) => {
console.log('开始搜索附近的蓝牙设备', res)
},
fail: (res) => {
console.log('搜索附近的蓝牙设备失败', res)
this._discoveryStarted = false
}
})
},
connect(e) {
const deviceId = e.currentTarget.dataset.deviceId
wx.createBLEConnection({
deviceId,
success: (res) => {
console.log('连接成功', res)
this.setData({
connectedDeviceId: deviceId,
connected: true
})
this.getBLEDeviceServices(deviceId)
},
fail: (res) => {
console.log('连接失败', res)
}
})
},
getBLEDeviceServices(deviceId) {
wx.getBLEDeviceServices({
deviceId,
success: (res) => {
console.log('获取服务成功', res)
this.getBLEDeviceCharacteristics(deviceId, res.services[0].uuid)
}
})
},
getBLEDeviceCharacteristics(deviceId, serviceId) {
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
console.log('获取特征值成功', res)
this.setData({
characteristics: res.characteristics
})
this.notifyBLECharacteristicValueChange(deviceId, res.characteristics[0].uuid)
}
})
},
notifyBLECharacteristicValueChange(deviceId, characteristicId) {
wx.notifyBLECharacteristicValueChange({
state: true,
deviceId,
serviceId: '0000ffe0-0000-1000-8000-00805f9b34fb',
characteristicId,
success: (res) => {
console.log('开启notify成功', res)
},
fail: (res) => {
console.log('开启notify失败', res)
}
})
wx.onBLECharacteristicValueChange((res) => {
console.log(`characteristic ${res.characteristicId} has changed, now is ${res.value}`)
})
},
sendData(e) {
const { connectedDeviceId, characteristics, inputValue } = this.data
const buffer = new ArrayBuffer(inputValue.length)
const dataView = new DataView(buffer)
for (let i = 0; i < inputValue.length; i++) {
dataView.setUint8(i, inputValue.charAt(i).charCodeAt())
}
wx.writeBLECharacteristicValue({
deviceId: connectedDeviceId,
serviceId: '0000ffe0-0000-1000-8000-00805f9b34fb',
characteristicId: characteristics[0].uuid,
value: buffer,
success: (res) => {
console.log('发送数据成功', res)
this.setData({
inputValue: ''
})
},
fail: (res) => {
console.log('发送数据失败', res)
}
})
},
inputData(e) {
this.setData({
inputValue: e.detail.value
})
},
onShow() {
wx.getSystemInfo({
success: (res) => {
if (res.platform === 'ios') {
this.setData({
isIos: true
})
}
}
})
this.openBluetoothAdapter()
}
})
```
这段代码主要实现了一些功能,包括搜索蓝牙设备、连接蓝牙设备、获取服务、获取特征值、开启notify、发送数据等。
以上是一个简单的微信小程序实现蓝牙连接和数据传输的代码,可根据实际需要进行修改和完善。
阅读全文