



<view class="rice_logo">
<image src="../../image/rice_logo.png" style="width: 227px; height: 100px;"></image>
</view>
<view class="devices_summary">
<view>
<text>已发现 {{devices.length}} 个BLE设备:</text>
<view class="devices_scan_btn">
<button size="mini" style="width:22vw; font-size: 4vw" bindtap="openBluetoothAdapter">开始扫描</button>
<button size="mini" style="width:22vw; font-size: 4vw" bindtap="closeBluetoothAdapter">停止扫描</button>
</view>
</view>
</view>
<scroll-view class="device_list" scroll-y scroll-with-animation>
<view wx:for="{{devices}}" wx:key="index"
data-device-id="{{item.deviceId}}"
data-name="{{item.name || item.localName}}"
bindtap="bindcreateBLEConnection"
class="device_item"
hover-class="device_item_hover">
<view style="font-size: 16px; color: #333;">{{item.name}}</view>
<view style="font-size: 10px">信号强度: {{item.RSSI}}dBm ({{utils.max(0, item.RSSI + 100)}}%)</view>
<view style="font-size: 10px">UUID: {{item.deviceId}}</view>
<view style="font-size: 10px">Service数量: {{utils.len(item.advertisServiceUUIDs)}}</view>
</view>
</scroll-view>
<view class="connected_info" wx:if="{{connected}}">
<text>已连接到{{name}}</text>
<view class="data_title">接收数据:</view>
<view class="read_data">
<textarea style="height: 3em" placeholder="接收到的数据"/>
</view>
<view class="data_title">发送数据:</view>
<view class="write_data">
<textarea bindblur="bindWriteData" style="height: 4em" placeholder="输入要发送的数据" />
</view>
<view class="operation">
<view class="data-type" wx:if="{{canWrite}}">
<!-- <view class="data-type"> -->
<radio-group bindchange="dataTypeSelect">
<label class="radio">
<radio value="hex" checked="false"/>HEX
</label>
<label class="radio">
<radio value="ascii" checked="true" />ASCII
</label>
</radio-group>
</view>
<view class="devices_func_btn">
<button wx:if="{{canWrite}}" size="mini" style="width:22vw; font-size: 4vw" bindtap="writeBLECharacteristicValue">写数据</button>
<button size="mini" style="width:22vw; font-size: 4vw" bindtap="closeBLEConnection">断开连接</button>
</view>
</view>
</view>
<view class="log_title">log:</view>
<scroll-view class="log_list" scroll-y scroll-with-animation>
<text style="font-size: 10px">{{log_list}}</text>
</scroll-view>
<button class="clear_log" bindtap="bindClearLog">清空调试信息</button>


openBluetoothAdapter() {
this.printLog("启动蓝牙适配器...");
this.setData({
devices: [],
connected: false,
chs: [],
canWrite: false,
})
wx.openBluetoothAdapter({
success: (res) => {
this.printLog("蓝牙启动成功,开始进入发现设备");
this.startBluetoothDevicesDiscovery()
},
fail: (res) => {
this.printInfo("请先打开蓝牙")
if (res.errCode === 10001) {
wx.onBluetoothAdapterStateChange(function (res) {
if (res.available) {
this.printLog("蓝牙启动成功,开始进入发现设备");
this.startBluetoothDevicesDiscovery()
}
})
}
}
})
},
closeBluetoothAdapter() {
this.printLog("停止扫描");
wx.closeBluetoothAdapter()
this.stopBluetoothDevicesDiscovery()
this._discoveryStarted = false
},
startBluetoothDevicesDiscovery() {
if(this._discoveryStarted) {
this.printLog("已经正在发现设备...")
return
}
this._discoveryStarted = true
wx.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true,
success: (res) => {
this.printLog("开始发现设备...")
this.onBluetoothDeviceFound()
},
})
},
stopBluetoothDevicesDiscovery() {
this.printLog('停止发现设备')
this._discoveryStarted = false
wx.stopBluetoothDevicesDiscovery()
},
onBluetoothDeviceFound() {
this.printLog('正在发现设备...')
wx.onBluetoothDeviceFound((res) => {
res.devices.forEach(device => {
if (!device.name && !device.localName) {
return
}
const foundDevices = this.data.devices
const idx = inArray(foundDevices, 'deviceId', device.deviceId)
const data = {}
if (idx === -1) {
data[`devices[${foundDevices.length}]`] = device
} else {
data[`devices[${idx}]`] = device
}
this.setData(data)
})
})
},
bindcreateBLEConnection(e) {
const ds = e.currentTarget.dataset
const deviceId = ds.deviceId
const name = ds.name
this.printLog("开始连接设备 [" + name + "]")
wx.createBLEConnection({
deviceId,
success: (res) => {
this.setData({
connected: true,
name,
deviceId,
})
this.getBLEDeviceServices(deviceId)
}
})
// this.stopBluetoothDevicesDiscovery()
},
getBLEDeviceServices(deviceId) {
this.printLog("获取设备服务: " + deviceId)
wx.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
}
}
}
})
},
getBLEDeviceCharacteristics(deviceId, serviceId) {
this.printLog('开始获取设备属性: ' + deviceId + serviceId)
wx.getBLEDeviceCharacteristics({
deviceId,
serviceId,
success: (res) => {
this.printLog('成功获取设备属性')
for (let i = 0; i < res.characteristics.length; i++) {
let item = res.characteristics[i]
if (item.properties.read) {
wx.readBLECharacteristicValue({
deviceId,
serviceId,
characteristicId: item.uuid,
})
}
if (item.properties.write) {
this.setData({
canWrite: true
})
this._deviceId = deviceId
this._serviceId = serviceId
this._characteristicId = item.uuid
// this.writeBLECharacteristicValue()
}
if (item.properties.notify || item.properties.indicate) {
wx.notifyBLECharacteristicValueChange({
deviceId,
serviceId,
characteristicId: item.uuid,
state: true,
})
}
}
},
fail(res) {
this.printLog('设备属性获取失败')
}
})
},
writeBLECharacteristicValue() {
var that = this;
if(this.data.dataType)
{
var buffer = stringToBytes(this.data.sendData)
that.printLog("发送数据:" + this.data.sendData)
console.log("ascii")
}
else
{
console.log("hex")
}
wx.writeBLECharacteristicValue({
deviceId: this._deviceId,
serviceId: this._serviceId,
characteristicId: this._characteristicId,
value: buffer,
success (res) {
// that.printLog("发送数据:" + that.data.sendData)
// that.printLog("发送数据成功");
},
fail (res) {
that.printLog("发送数据失败")
}
})
},
printLog:function(log) {
var logs = this.data.logs;
logs.push(log);
this.setData({log_list: logs.join('\n')})
},
printInfo:function(info) {
wx.showToast({
title: info,
icon: 'none',
duration: 1200,
mask: true
})
},
printTimer:function() {
var timestamp = Date.parse(new Date())
timestamp = timestamp / 1000;
var n = timestamp * 1000;
var date = new Date(n);
//年
var Y = date.getFullYear();
//月
var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
//日
var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
//时
var h = date.getHours();
//分
var m = date.getMinutes();
//秒
var s = date.getSeconds();
this.printLog("当前时间:" +Y+"-"+M+"-"+D+" "+h+":"+m+":"+s)
},


本文分享自 Rice 嵌入式开发技术分享 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!