2025年04月25日17:19:26

This commit is contained in:
luojiayi 2025-04-25 17:19:37 +08:00
parent 220ab56208
commit 499babed26
5 changed files with 77 additions and 58 deletions

View File

@ -14,6 +14,7 @@ export default function Index() {
router.navigate('/pages/deviceList/index') router.navigate('/pages/deviceList/index')
} }
const deviceCallBack = () => { const deviceCallBack = () => {
console.log(BLESDK.deviceInfo, '解绑2');
setIsLink(BLESDK.deviceInfo.state) setIsLink(BLESDK.deviceInfo.state)
} }
useDidShow(() => { useDidShow(() => {
@ -28,7 +29,7 @@ export default function Index() {
success: (res) => { success: (res) => {
if (res.confirm) { if (res.confirm) {
setIsLink(false) setIsLink(false)
BLESDK.unBindDevice() BLESDK.closeBluetoothAdapter()
Taro.showToast({ title: '设备解绑成功', icon: 'success' }) Taro.showToast({ title: '设备解绑成功', icon: 'success' })
} }
} }

View File

@ -23,7 +23,7 @@ export default function Index() {
setTimeout(() => { setTimeout(() => {
Taro.hideLoading() Taro.hideLoading()
}, 3000) }, 1500)
return () => { return () => {
BLESDK.stopBluetoothDevicesDiscovery() BLESDK.stopBluetoothDevicesDiscovery()
} }
@ -35,7 +35,6 @@ export default function Index() {
} }
BLESDK.onBluetoothDeviceFound((item) => { BLESDK.onBluetoothDeviceFound((item) => {
if (JSON.stringify(deviceList).indexOf(item.mac) != -1) return
deviceList.push(item) deviceList.push(item)
setDeviceList([...deviceList]) setDeviceList([...deviceList])
}) })

View File

@ -21,8 +21,6 @@ export default function Index() {
}) })
} }
const handleColorPicker = (e) => { const handleColorPicker = (e) => {
console.log(e);
if (e) { if (e) {
setCurColor(e) setCurColor(e)
} }
@ -62,6 +60,12 @@ export default function Index() {
}) })
} }
BLESDK.onBLECharacteristicValueChange((bytes) => {
if (bytes[0] == 0x7A && bytes[4] == 0xB3) {
Taro.showToast({ title: '操作成功', icon: 'none' })
}
})
return ( return (
<View className="index"> <View className="index">
<View className='head'> <View className='head'>

View File

@ -5,7 +5,7 @@ import ble from "@/assets/ble.png";
import soundCard from "@/assets/soundCard.png"; import soundCard from "@/assets/soundCard.png";
import game from "@/assets/game.png"; import game from "@/assets/game.png";
import ai from "@/assets/ai.png"; import ai from "@/assets/ai.png";
import Taro from '@tarojs/taro'; import Taro, { useDidShow } from '@tarojs/taro';
import { useCallback, useState } from 'react'; import { useCallback, useState } from 'react';
import { hex, strInsert } from '@/utils/sendOrder'; import { hex, strInsert } from '@/utils/sendOrder';
import { debounce } from '@/utils/index' import { debounce } from '@/utils/index'
@ -37,10 +37,12 @@ export default function Index() {
BLESDK.writeBleValue(new Uint8Array(strInsert(e)).buffer) BLESDK.writeBleValue(new Uint8Array(strInsert(e)).buffer)
}), []) }), [])
const handleChange = (e, key) => { const handleChange = (e, key) => {
if (key !== 'nextAndPre') {
setRuleForm({ setRuleForm({
...ruleForm, ...ruleForm,
[key]: e [key]: e
}) })
}
let str = '' let str = ''
switch (key) { switch (key) {
case 'volume': case 'volume':
@ -61,8 +63,8 @@ export default function Index() {
case 'playMode': case 'playMode':
str = `7B05EA0AB2${hex(e)}` str = `7B05EA0AB2${hex(e)}`
break; break;
case 'musicControl': case 'playPause':
str = `7B05EA0BB2${hex(e)}` str = `7B05EA0BB2${hex(e ? 1 : 2)}`
break; break;
case 'girth': case 'girth':
str = `7B05EA0CB2${hex(e)}` str = `7B05EA0CB2${hex(e)}`
@ -76,23 +78,25 @@ export default function Index() {
case 'AI': case 'AI':
str = `7B05EA11B2${hex(e)}` str = `7B05EA11B2${hex(e)}`
break; break;
case 'musicMode':
str = `7B05EA0AB2${hex(e)}`
break;
case 'nextAndPre':
str = `7B05EA0BB2${hex(e)}`
break;
} }
sendCode(str) sendCode(str)
} }
// 0 1 2 3 4
const musicControl = (num) => {
let str = `7B05EA0BB2${hex(num)}`
sendCode(str)
}
const handelMusicMode = (type) => { const handelMusicMode = (type) => {
let num = ruleForm.girth let num = ruleForm.musicMode
if (type == "+" && ruleForm.girth < 3) { if (type == "+" && ruleForm.musicMode < 3) {
num++ num++
} else if (type == "-" && ruleForm.girth > 0) { } else if (type == "-" && ruleForm.musicMode > 0) {
num-- num--
} }
handleChange(num, 'girth') if (num == ruleForm.musicMode) return
handleChange(num, 'musicMode')
} }
const control = (type) => { const control = (type) => {
@ -102,8 +106,17 @@ export default function Index() {
} else if (type == "-" && ruleForm.girth > 0) { } else if (type == "-" && ruleForm.girth > 0) {
num-- num--
} }
if (num == ruleForm.girth) return
handleChange(num, 'girth') handleChange(num, 'girth')
} }
const BleCallBack = (bytes) => {
if (bytes[0] == 0x7D && bytes[4] == 0xB0) {
Taro.showToast({ title: bytes[5] == 0x00 ? '操作失败' : '操作成功', icon: 'none' })
}
}
useDidShow(() => {
BLESDK.onBLECharacteristicValueChange(BleCallBack)
})
return ( return (
<View className="index"> <View className="index">
@ -138,12 +151,11 @@ export default function Index() {
</View> </View>
</View> </View>
<View className='play'> <View className='play'>
<View className='play-icon pre' onClick={() => musicControl(3)}></View> <View className='play-icon pre' onClick={() => handleChange(3, 'nextAndPre')}></View>
<View className={ruleForm.playPause ? 'play-pause' : 'play-play'} onClick={() => { <View className={ruleForm.playPause ? 'play-pause' : 'play-play'} onClick={() => {
musicControl(ruleForm.playPause ? 2 : 1)
handleChange(!ruleForm.playPause, 'playPause') handleChange(!ruleForm.playPause, 'playPause')
}}></View> }}></View>
<View className='play-icon next' onClick={() => musicControl(4)}></View> <View className='play-icon next' onClick={() => handleChange(4, 'nextAndPre')}></View>
</View> </View>
<View className='card'> <View className='card'>
<View className='funitem'> <View className='funitem'>
@ -205,7 +217,10 @@ export default function Index() {
<View className='funitem-text'>话筒混响模式</View> <View className='funitem-text'>话筒混响模式</View>
<View className='numlist'> <View className='numlist'>
{[1, 2, 3, 4, 5, 6].map(item => { {[1, 2, 3, 4, 5, 6].map(item => {
return <View className={`numlist-num ${ruleForm.reverb == item ? 'active' : ''} `} key={item} onClick={() => handleChange(item, 'reverb')}>{item}</View> return <View className={`numlist-num ${ruleForm.reverb == item ? 'active' : ''} `} key={item} onClick={() => {
if (item == ruleForm.reverb) return
handleChange(item, 'reverb')
}}>{item}</View>
})} })}
</View> </View>
</View> </View>

View File

@ -21,13 +21,13 @@ const errMsg = {
class Bluetooth { class Bluetooth {
config = { config = {
// serviceId: "4E31BF4A-8507-3A2B-7344-C7EDACD38104", //设备服务id serviceId: "4E31BF4A-8507-3A2B-7344-C7EDACD38104", //设备服务id
// NotifyUUID: "4E31BF4B-8507-3A2B-7344-C7EDACD38104", NotifyUUID: "4E31BF4B-8507-3A2B-7344-C7EDACD38104",
// WriteUUID: "4E31BF4C-8507-3A2B-7344-C7EDACD38104", WriteUUID: "4E31BF4C-8507-3A2B-7344-C7EDACD38104",
serviceId: 'C7E6FAE0-E966-1000-8000-BEF9C723DF6A', //设备服务id // serviceId: 'C7E6FAE0-E966-1000-8000-BEF9C723DF6A', //设备服务id
NotifyUUID: 'C7E6FAE1-E966-1000-8000-BEF9C723DF6A', // NotifyUUID: 'C7E6FAE1-E966-1000-8000-BEF9C723DF6A',
WriteUUID: 'C7E6FAE2-E966-1000-8000-BEF9C723DF6A', // WriteUUID: 'C7E6FAE2-E966-1000-8000-BEF9C723DF6A',
}; };
// 连接状态 // 连接状态
@ -45,7 +45,7 @@ class Bluetooth {
platform = Taro.getSystemInfoSync().platform; platform = Taro.getSystemInfoSync().platform;
appAuthorize = Taro.getAppAuthorizeSetting(); appAuthorize = Taro.getAppAuthorizeSetting();
deviceInfo = Taro.getStorageSync('deviceInfo') || {} deviceInfo = {}
callBack = () => { }; callBack = () => { };
searchBack = () => { }; searchBack = () => { };
@ -91,6 +91,7 @@ class Bluetooth {
success: () => { success: () => {
console.log("初始化蓝牙模块"); console.log("初始化蓝牙模块");
this.isInit = true; this.isInit = true;
this.deviceInfo = Taro.getStorageSync('deviceInfo') || {}
if (this.deviceInfo.name) { if (this.deviceInfo.name) {
this.createBleConnection() this.createBleConnection()
} }
@ -108,7 +109,7 @@ class Bluetooth {
if (this.appAuthorize.locationAuthorized != "authorized" && this.platform == "android") if (this.appAuthorize.locationAuthorized != "authorized" && this.platform == "android")
return Taro.showToast({ title: "请打开微信定位权限", icon: "none", duration: 3000 }); return Taro.showToast({ title: "请打开微信定位权限", icon: "none", duration: 3000 });
Taro.startBluetoothDevicesDiscovery({ Taro.startBluetoothDevicesDiscovery({
allowDuplicatesKey: true, // allowDuplicatesKey: true,
powerLevel: "high", powerLevel: "high",
success: (res) => { success: (res) => {
this.isFindBt = setTimeout(() => { this.isFindBt = setTimeout(() => {
@ -146,9 +147,9 @@ class Bluetooth {
const mac = this.strInsert(String(advertisData).substring(4, 16)).toLocaleUpperCase(); const mac = this.strInsert(String(advertisData).substring(4, 16)).toLocaleUpperCase();
// 判断是否有搜索到设备 // 判断是否有搜索到设备
this.isFindBt && this.clearTimeoutFn("isFindBt"); this.isFindBt && this.clearTimeoutFn("isFindBt");
// if (devices.name && devices.name == "W53A") { // if (devices.name && devices.name == "W53A") {
if (devices.name && devices.name == "LE-AB2020") { if (devices.name && devices.name == "LE-AB2020") {
console.log(JSON.stringify(res), "搜索到设备");
const item = { const item = {
deviceId: devices.deviceId, deviceId: devices.deviceId,
mac: mac, mac: mac,
@ -166,7 +167,7 @@ class Bluetooth {
Taro.setStorageSync("deviceInfo", this.deviceInfo); Taro.setStorageSync("deviceInfo", this.deviceInfo);
console.log("正在连接设备"); console.log("正在连接设备");
Taro.createBLEConnection({ Taro.createBLEConnection({
timeout: 8000, timeout: 3000,
deviceId: this.deviceInfo.deviceId, deviceId: this.deviceInfo.deviceId,
success: () => { success: () => {
this.deviceInfo.state = true; this.deviceInfo.state = true;
@ -224,7 +225,7 @@ class Bluetooth {
success: (res) => { success: (res) => {
console.log("连接成功"); console.log("连接成功");
Taro.setStorageSync("deviceInfo", { ...this.deviceInfo, state: false }); Taro.setStorageSync("deviceInfo", { ...this.deviceInfo, state: false });
handshake1() // handshake1()
this.callBack(this.deviceInfo); this.callBack(this.deviceInfo);
}, },
fail: (err) => this.fail(err), fail: (err) => this.fail(err),
@ -234,12 +235,12 @@ class Bluetooth {
onBLECharacteristicValueChange(fn) { onBLECharacteristicValueChange(fn) {
Taro.onBLECharacteristicValueChange((data) => { Taro.onBLECharacteristicValueChange((data) => {
let bytes = new Uint8Array(data.value); let bytes = new Uint8Array(data.value);
let value = String(this.ab2hex(bytes)); let value = String(this.ab2hex(bytes)).toLocaleUpperCase();
// 第二次握手 // 第二次握手
if (bytes[2] == 0xea && bytes[3] == 0x01) { // if (bytes[2] == 0xea && bytes[3] == 0x01) {
handshake2() // handshake2()
} // }
console.log(`设备回复====>${value}`); console.log(`设备回复====>${value}`);
TASK.executeTask(); TASK.executeTask();
fn && fn(bytes, value); fn && fn(bytes, value);
@ -247,11 +248,11 @@ class Bluetooth {
} }
// 向蓝牙写入数据 // 向蓝牙写入数据
writeBleValue(value) { writeBleValue(value) {
console.log("发送指令====>" + String(this.ab2hex(value)).toLocaleUpperCase());
if (!this.deviceInfo.state) { if (!this.deviceInfo.state) {
console.log("蓝牙未连接") // console.log("蓝牙未连接")
return return
} }
console.log("发送指令====>" + String(this.ab2hex(value)).toLocaleUpperCase());
return Taro.writeBLECharacteristicValue({ return Taro.writeBLECharacteristicValue({
deviceId: this.deviceInfo.deviceId, deviceId: this.deviceInfo.deviceId,
serviceId: this.config.serviceId, serviceId: this.config.serviceId,
@ -285,17 +286,16 @@ class Bluetooth {
} }
// 断开与蓝牙低功耗设备的连接 // 断开与蓝牙低功耗设备的连接
closeBluetoothAdapter() { closeBluetoothAdapter() {
return new Promise((resolve, reject) => {
this.linkFlag = false; this.linkFlag = false;
this.deviceInfo = { state: false }; this.deviceInfo = { state: false };
wx.removeStorageSync("deviceInfo"); wx.removeStorageSync("deviceInfo");
this.callBack(this.deviceInfo);
Taro.closeBluetoothAdapter({ Taro.closeBluetoothAdapter({
success: (res) => { success: (res) => {
this.openBluetoothAdapter().then(resolve).catch(reject); console.log(this.deviceInfo, '解绑1');
this.callBack(this.deviceInfo);
this.openBluetoothAdapter()
}, },
}); });
})
} }
// 设备响应回调 // 设备响应回调
deviceCallBack(fn) { deviceCallBack(fn) {
@ -309,11 +309,11 @@ class Bluetooth {
}); });
return hexArr.join("").toLocaleLowerCase(); return hexArr.join("").toLocaleLowerCase();
} }
unBindDevice() { // unBindDevice() {
this.deviceInfo = {} // this.deviceInfo = {}
wx.removeStorageSync('deviceInfo') // wx.removeStorageSync('deviceInfo')
this.closeBluetoothAdapter() // this.closeBluetoothAdapter()
} // }
/** /**
* 字符串插入字符 * 字符串插入字符
* @param {*} str 字符串 * @param {*} str 字符串