增加中文日志输出 优化导出日志功能
This commit is contained in:
@@ -141,27 +141,65 @@ Page({
|
||||
// 先取消旧的发现监听,避免多次注册造成干扰
|
||||
this.teardownDeviceFoundListener()
|
||||
this._foundCount = 0
|
||||
const now = Date.now()
|
||||
// 防护:避免短时间内频繁触发扫描(系统限制)
|
||||
if (this._lastScanAt && now - this._lastScanAt < 2000) {
|
||||
try { this.appendLog && this.appendLog('WARN', 'skip startBluetoothDevicesDiscovery: throttled') } catch (e) {}
|
||||
return
|
||||
}
|
||||
this._lastScanAt = now
|
||||
console.info('[BLE] start scan, prefix:', prefix || 'ALL')
|
||||
// 先停止可能已有的搜索,待停止完成后再启动,避免竞态
|
||||
wx.stopBluetoothDevicesDiscovery({
|
||||
complete: () => {
|
||||
wx.startBluetoothDevicesDiscovery({
|
||||
allowDuplicatesKey: true, // 允许重复上报,提升二次搜索的发现率
|
||||
success: () => {
|
||||
|
||||
const doStart = () => {
|
||||
// 先停止可能已有的搜索,待停止完成后再启动,避免竞态
|
||||
wx.stopBluetoothDevicesDiscovery({
|
||||
complete: () => {
|
||||
wx.startBluetoothDevicesDiscovery({
|
||||
allowDuplicatesKey: true, // 允许重复上报,提升二次搜索的发现率
|
||||
success: () => {
|
||||
this.setupDeviceFoundListener(prefix)
|
||||
// 定时停止,避免长时间占用
|
||||
setTimeout(() => {
|
||||
this.stopBluetoothDiscovery()
|
||||
}, 6000)
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('开始搜索蓝牙设备失败', err)
|
||||
// 若为系统提示搜索过于频繁,可稍后重试一次
|
||||
const code = err && (err.errCode || (err.errMsg && Number((err.errMsg.match(/\d+/)||[])[0])))
|
||||
if (code === 10008) {
|
||||
try { this.appendLog && this.appendLog('WARN', 'startBluetoothDevicesDiscovery failed: scanning too frequently, retrying shortly') } catch (e) {}
|
||||
setTimeout(() => { try { doStart() } catch (e) {} }, 1500)
|
||||
return
|
||||
}
|
||||
wx.hideLoading()
|
||||
wx.showToast({ title: '搜索失败', icon: 'none' })
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 优先查询适配器状态,若系统正在扫描则直接注册监听并返回
|
||||
if (typeof wx.getBluetoothAdapterState === 'function') {
|
||||
wx.getBluetoothAdapterState({
|
||||
success: (res) => {
|
||||
if (res && res.discovering) {
|
||||
try { this.appendLog && this.appendLog('CFG', 'adapter already discovering, attach listener') } catch (e) {}
|
||||
this.setupDeviceFoundListener(prefix)
|
||||
// 定时停止,避免长时间占用
|
||||
setTimeout(() => {
|
||||
this.stopBluetoothDiscovery()
|
||||
}, 6000)
|
||||
},
|
||||
fail: (err) => {
|
||||
console.error('开始搜索蓝牙设备失败', err)
|
||||
wx.hideLoading()
|
||||
wx.showToast({ title: '搜索失败', icon: 'none' })
|
||||
wx.showToast({ title: '正在搜索中', icon: 'none' })
|
||||
return
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
doStart()
|
||||
},
|
||||
fail: () => {
|
||||
doStart()
|
||||
}
|
||||
})
|
||||
} else {
|
||||
doStart()
|
||||
}
|
||||
},
|
||||
|
||||
setupDeviceFoundListener(prefix) {
|
||||
@@ -262,6 +300,7 @@ Page({
|
||||
? `${base}&serviceId=${encodeURIComponent(svc)}&txCharId=${encodeURIComponent(tx)}&rxCharId=${encodeURIComponent(rx)}`
|
||||
: base
|
||||
console.log('navigateTo:', withParams)
|
||||
try { this._navigatingToB13 = true } catch (e) { /* ignore */ }
|
||||
wx.navigateTo({ url: withParams })
|
||||
|
||||
|
||||
@@ -305,30 +344,49 @@ Page({
|
||||
}
|
||||
|
||||
wx.showLoading({ title: '连接中...', mask: true })
|
||||
// 使用 BLE 直连,不再使用模拟延迟
|
||||
wx.createBLEConnection({
|
||||
deviceId: device.id,
|
||||
success: () => {
|
||||
const list = this.data.deviceList.map((d, i) => ({ ...d, connected: i === index }))
|
||||
this.setData({ deviceList: list, currentDeviceId: device.id })
|
||||
// 设置MTU为256,提升传输效率
|
||||
if (typeof wx.setBLEMTU === 'function') {
|
||||
wx.setBLEMTU({
|
||||
deviceId: device.id,
|
||||
mtu: 500,
|
||||
fail: () => console.warn('[BLE] set MTU 256 failed'),
|
||||
success: () => console.info('[BLE] set MTU 256 success')
|
||||
})
|
||||
}
|
||||
// 连接成功后发现服务与特征
|
||||
this.discoverBleChannels(device)
|
||||
},
|
||||
fail: (err) => {
|
||||
// 在尝试 createBLEConnection 前确保适配器已打开(处理息屏后 closeBluetoothAdapter 场景)
|
||||
this.ensureBluetoothReady()
|
||||
.then(() => {
|
||||
// 使用 BLE 直连
|
||||
wx.createBLEConnection({
|
||||
deviceId: device.id,
|
||||
success: () => {
|
||||
const list = this.data.deviceList.map((d, i) => ({ ...d, connected: i === index }))
|
||||
this.setData({ deviceList: list, currentDeviceId: device.id })
|
||||
// 设置MTU为256,提升传输效率(若支持)
|
||||
if (typeof wx.setBLEMTU === 'function') {
|
||||
wx.setBLEMTU({
|
||||
deviceId: device.id,
|
||||
mtu: 500,
|
||||
fail: () => console.warn('[BLE] set MTU 256 failed'),
|
||||
success: () => console.info('[BLE] set MTU 256 success')
|
||||
})
|
||||
}
|
||||
// 连接成功后发现服务与特征
|
||||
this.discoverBleChannels(device)
|
||||
},
|
||||
fail: (err) => {
|
||||
wx.hideLoading()
|
||||
console.error('BLE 连接失败', err)
|
||||
const errmsg = (err && (err.errMsg || err.message)) || ''
|
||||
const isAlreadyConnected = errmsg.indexOf('already connect') >= 0 || errmsg.indexOf('already connected') >= 0 || (err && (err.errCode === -1 || err.errno === 1509007))
|
||||
if (isAlreadyConnected) {
|
||||
try { this.appendLog && this.appendLog('CFG', 'createBLEConnection: already connected, treating as connected') } catch (e) {}
|
||||
const list = this.data.deviceList.map((d, i) => ({ ...d, connected: i === index }))
|
||||
this.setData({ deviceList: list, currentDeviceId: device.id })
|
||||
// 继续发现服务与特征以恢复页面状态
|
||||
try { this.discoverBleChannels(device) } catch (e) {}
|
||||
return
|
||||
}
|
||||
wx.showToast({ title: '连接失败', icon: 'none' })
|
||||
}
|
||||
})
|
||||
})
|
||||
.catch((err) => {
|
||||
wx.hideLoading()
|
||||
console.error('BLE 连接失败', err)
|
||||
wx.showToast({ title: '连接失败', icon: 'none' })
|
||||
}
|
||||
})
|
||||
console.error('蓝牙未初始化,无法连接', err)
|
||||
wx.showToast({ title: '蓝牙未初始化', icon: 'none' })
|
||||
})
|
||||
},
|
||||
|
||||
// 发现包含 FFE1(写) / FFE2(订阅) 的服务与特征,并启用 FFE2 通知
|
||||
@@ -383,8 +441,9 @@ Page({
|
||||
if (this.data.activeTab === 'W13') {
|
||||
const devName = device.name || 'W13设备'
|
||||
const url = `/pages/basics/BluetoothDebugging/B13page/B13page?DevName=${encodeURIComponent(devName)}&mac=${encodeURIComponent(deviceId)}&serviceId=${encodeURIComponent(serviceId)}&txCharId=${encodeURIComponent(ffe1.uuid)}&rxCharId=${encodeURIComponent(ffe2.uuid)}`
|
||||
console.log(url)
|
||||
wx.navigateTo({ url })
|
||||
console.log(url)
|
||||
try { this._navigatingToB13 = true } catch (e) { /* ignore */ }
|
||||
wx.navigateTo({ url })
|
||||
// this.sendFixedCommand(deviceId, serviceId, ffe1.uuid)
|
||||
}
|
||||
}
|
||||
@@ -482,6 +541,11 @@ Page({
|
||||
|
||||
// 断开当前连接设备(如果有真实连接)
|
||||
disconnectCurrentDevice() {
|
||||
// 如果正在导航到 B13 页面,避免主动断开连接以保持会话
|
||||
if (this._navigatingToB13) {
|
||||
try { this.appendLog && this.appendLog('CFG', 'skip disconnectCurrentDevice during navigate to B13') } catch (e) {}
|
||||
return
|
||||
}
|
||||
const idx = this.data.deviceList.findIndex(d => d.connected)
|
||||
if (idx >= 0) {
|
||||
// 标记断开状态
|
||||
@@ -530,5 +594,105 @@ Page({
|
||||
this.loadDevicesByTab(this.data.activeTab)
|
||||
// 同步执行一次蓝牙搜索(按 W13 过滤规则)
|
||||
this.searchBluetooth()
|
||||
},
|
||||
|
||||
onShow() {
|
||||
// 返回到此页面时,清理导航标记
|
||||
if (this._navigatingToB13) {
|
||||
this._navigatingToB13 = false
|
||||
return
|
||||
}
|
||||
|
||||
try { this.appendLog && this.appendLog('CFG', 'onShow: resume, ensuring adapter and forcing discovery') } catch (e) {}
|
||||
// 息屏唤醒后可能适配器被关闭,先确保打开后短延迟再搜索一次
|
||||
this.ensureBluetoothReady()
|
||||
.then(() => {
|
||||
setTimeout(() => {
|
||||
try {
|
||||
this.startBluetoothDevicesDiscovery(this.data.activeTab)
|
||||
} catch (e) { /* ignore */ }
|
||||
}, 300)
|
||||
|
||||
// 尝试获取系统已连接设备,优先恢复之前连接的设备显示(防止已连接但不广播的设备无法被扫描到)
|
||||
try {
|
||||
const svc = this.data.currentServiceId
|
||||
const isW13 = this.data.activeTab === 'W13'
|
||||
const prefix = this.data.activeTab
|
||||
const matchByTab = (name) => {
|
||||
const n = name || ''
|
||||
if (isW13) return /^BLV_(W13|C13)_.+$/i.test(n)
|
||||
return prefix ? n.startsWith(prefix) : true
|
||||
}
|
||||
|
||||
if (typeof wx.getConnectedBluetoothDevices === 'function' && svc) {
|
||||
wx.getConnectedBluetoothDevices({ services: [svc], success: (res) => {
|
||||
const devices = (res && res.devices) || []
|
||||
if (devices.length) {
|
||||
// 将已连接设备合并到列表并按过滤规则筛选
|
||||
const list = [...this.data.deviceList]
|
||||
devices.forEach(d => {
|
||||
const name = d.name || d.localName || ''
|
||||
if (!matchByTab(name)) return
|
||||
const idx = list.findIndex(x => x.id === d.deviceId)
|
||||
const mapped = { id: d.deviceId, name, mac: d.deviceId, connected: true, RSSI: d.RSSI || 0, serviceUUIDs: d.serviceUUIDs || [] }
|
||||
if (idx >= 0) list[idx] = { ...list[idx], ...mapped }
|
||||
else list.unshift(mapped)
|
||||
})
|
||||
this.setData({ deviceList: list })
|
||||
try { this.appendLog && this.appendLog('CFG', 'restored connected devices from system') } catch (e) {}
|
||||
}
|
||||
}})
|
||||
} else if (typeof wx.getBluetoothDevices === 'function') {
|
||||
// 作为兜底,查询最近缓存的设备并按过滤规则合并
|
||||
wx.getBluetoothDevices({ success: (res) => {
|
||||
const devices = (res && res.devices) || []
|
||||
if (devices.length) {
|
||||
const list = [...this.data.deviceList]
|
||||
devices.forEach(d => {
|
||||
const name = d.name || d.localName || ''
|
||||
if (!matchByTab(name)) return
|
||||
const idx = list.findIndex(x => x.id === d.deviceId)
|
||||
const mapped = { id: d.deviceId, name, mac: d.deviceId, connected: !!d.connected, RSSI: d.RSSI || 0, serviceUUIDs: d.serviceUUIDs || [] }
|
||||
if (idx >= 0) list[idx] = { ...list[idx], ...mapped }
|
||||
else list.push(mapped)
|
||||
})
|
||||
this.setData({ deviceList: list })
|
||||
}
|
||||
}})
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
})
|
||||
.catch((err) => {
|
||||
try { this.appendLog && this.appendLog('WARN', 'onShow ensureBluetoothReady failed') } catch (e) {}
|
||||
})
|
||||
},
|
||||
|
||||
onHide() {
|
||||
// 如果正在导航到 B13 页面,跳过 onHide 的断开/重置流程,保留连接
|
||||
if (this._navigatingToB13) {
|
||||
try { this.appendLog && this.appendLog('CFG', 'onHide skipped due to navigation to B13') } catch (e) {}
|
||||
// 清理标记,后续返回时 onShow 会再次执行
|
||||
this._navigatingToB13 = false
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// 停止发现,避免后台扫描
|
||||
if (typeof wx.stopBluetoothDevicesDiscovery === 'function') {
|
||||
wx.stopBluetoothDevicesDiscovery({ complete: () => { try { this.appendLog && this.appendLog('CFG', 'stopBluetoothDevicesDiscovery onHide') } catch (e) {} } })
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
try {
|
||||
// 断开当前连接(如果有)
|
||||
this.disconnectCurrentDevice()
|
||||
} catch (e) { /* ignore */ }
|
||||
|
||||
try {
|
||||
// 关闭蓝牙适配器以重置底层状态(部分 Android 机型息屏后需要此步骤)
|
||||
if (typeof wx.closeBluetoothAdapter === 'function') {
|
||||
wx.closeBluetoothAdapter({ complete: () => { try { this.appendLog && this.appendLog('CFG', 'closeBluetoothAdapter called onHide') } catch (e) {} } })
|
||||
}
|
||||
} catch (e) { /* ignore */ }
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user