Files
bodyWeight/miniprogram/pages/connectedDevice/connectedDevice.ts
T

103 lines
2.9 KiB
TypeScript

import { lefuService } from '../../lefu/index'
import type { ScannedDevice } from '../../lefu/index'
/** 展示用设备项 */
interface DeviceItem {
/** 设备名称 */
name: string
/** 是否已连接 */
connected: boolean
/** 原始设备对象(连接时传回给 SDK) */
_raw: ScannedDevice
}
/** 页面状态 */
type DeviceStatus = 'idle' | 'searching' | 'found' | 'empty'
Page({
data: {
/**
* 页面状态
* - idle: 未搜索(进入页面默认态)
* - searching: 扫描中
* - found: 扫描完成且有设备
* - empty: 扫描完成但无设备
*/
status: 'idle' as DeviceStatus,
/** 扫描到的设备列表 */
deviceList: [] as DeviceItem[],
},
onShow() {
// 注册回调后开始扫描
lefuService.onDevicesList((devices) => {
if (!devices.length) {
this.setData({ status: 'empty', deviceList: [] })
return
}
const list: DeviceItem[] = devices.map(d => ({
name: d.name,
connected: false,
_raw: d,
}))
this.setData({ status: 'found', deviceList: list })
})
lefuService.onConnectState((state) => {
const plugin = lefuService['_plugin']
if (!plugin) return
// 连接成功后跳转配网页
if (state === plugin.BLUE_STATE.CONNECTSUCCESS || state === plugin.BLUE_STATE.WIFISUCCESS) {
wx.navigateTo({ url: '/pages/connectedWifi/connectedWifi' })
}
})
this.onStartSearch()
},
onHide() {
// 页面隐藏时停止扫描,释放 bus 订阅
lefuService.stopScan()
},
onUnload() {
lefuService.stopScan()
},
/** 开始 / 重新搜索 */
onStartSearch() {
this.setData({ status: 'searching', deviceList: [] })
lefuService.startScan()
},
/** 连接指定设备 */
onConnect(e: WechatMiniprogram.TouchEvent) {
const index = e.currentTarget.dataset.index as number
const target = this.data.deviceList[index]
if (!target) return
// 更新 UI 连接状态
const list = this.data.deviceList.map((item, i) => ({
...item,
connected: i === index,
}))
this.setData({ deviceList: list })
// 调用 SDK 连接(BleAdv 类型已在 startScan 内自动处理,BleConnect 类型需此处触发)
lefuService.connect(target._raw)
},
/** 断开当前连接 */
onDisconnect() {
const list = this.data.deviceList.map(item => ({ ...item, connected: false }))
this.setData({ deviceList: list })
lefuService.disconnect()
},
/** 查看帮助 */
onOpenHelp() {
wx.showToast({ title: '请确保设备已开机且在附近', icon: 'none' })
},
})