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

178 lines
6.0 KiB
TypeScript

import { get } from '../../utils/request/index'
import { lefuService } from '../../lefu/index'
import type { RawDevice } from '../../lefu/types'
/** API 返回的设备记录 */
interface DeviceRecord {
id: string
userId: string
parentUserId: string | null
scaleDeviceId: string
deviceId: string | null
deviceType: string
dataType: number
userType: number
idCard: string
height: number
weight: number
birthday: string
sex: number
avatar: string | null
phone: string | null
thirdId: string
realname: string
bmi: number
createBy: string
createTime: string
updateBy: string
updateTime: string
delFlag: number
sn: string | null
workNo: string
remark: string | null
relationType: string | null
sex_dictText: string
/** 设备连接信息 JSON 字符串,与登录接口返回格式一致 */
connectDeviceInfo: string
}
/** 展示用设备项 */
interface DeviceItem {
id: string
scaleDeviceId: string
scaleDeviceName: string
connectDeviceInfo: string
realname: string
/** 蓝牙连接状态,接口不返回,由业务层更新 */
connected: boolean
}
Page({
data: {
loading: false,
deviceList: [] as DeviceItem[],
},
onShow() {
this.loadData()
},
onUnload() {
lefuService.stopScan()
lefuService.onDeviceConnect(() => {})
lefuService.onDeviceInfo(() => {})
},
/** 拉取已绑定设备列表,加载完成后检查缓存自动连接 */
loadData() {
this.setData({ loading: true })
const userInfo = wx.getStorageSync('userInfo')
get<DeviceRecord[]>('weighingScale/v3/list/device', { userId: userInfo?.userId })
.then(res => {
const list: DeviceItem[] = res.result.map(item => {
let scaleDeviceName = ''
try {
const info = JSON.parse(item.connectDeviceInfo || '{}')
scaleDeviceName = info.name ?? ''
} catch {}
return {
id: item.id,
scaleDeviceId: item.scaleDeviceId,
scaleDeviceName,
connectDeviceInfo: item.connectDeviceInfo ?? '',
realname: item.realname,
connected: false,
}
})
this.setData({ deviceList: list }, () => {
this._checkAndAutoConnect()
})
})
.finally(() => {
this.setData({ loading: false })
})
},
/** 检查缓存设备:已连接则直接标记,未连接则调 autoConnect 扫描重连 */
_checkAndAutoConnect() {
// 已连接且 deviceInfo 就绪,直接标记列表
if (lefuService.isConnected && lefuService.deviceInfo?.serialNumber) {
this._markConnected(lefuService.deviceInfo.serialNumber as string)
return
}
// 注册回调:连接成功后更新列表状态
lefuService.onDeviceInfo((info) => {
this._markConnected(info.serialNumber as string)
})
lefuService.autoConnect()
},
/** 将 serialNumber 对应的列表项标记为已连接,其余置为未连接 */
_markConnected(serialNumber: string) {
const list = this.data.deviceList.map(item => ({
...item,
connected: item.scaleDeviceId === serialNumber,
}))
this.setData({ deviceList: list })
},
/** 点击「连接」:扫描周边设备,找到 deviceId 匹配的设备后连接 */
onTapConnect(e: WechatMiniprogram.TouchEvent) {
const connectDeviceInfoStr = e.currentTarget.dataset.connectDeviceInfo as string
let cachedDevice: RawDevice | null = null
try {
cachedDevice = JSON.parse(connectDeviceInfoStr || '{}')
} catch {}
const targetDeviceId = cachedDevice?.deviceId as string | undefined
if (!targetDeviceId) return
if (lefuService.isConnected) lefuService.disconnect()
this.setData({ deviceList: this.data.deviceList.map(item => ({ ...item, connected: false })) })
let scanTimer: number | null = null
wx.showLoading({ title: '扫描中...', mask: true })
wx.openBluetoothAdapter({
success: () => {
scanTimer = setTimeout(() => {
lefuService.stopScan()
wx.hideLoading()
wx.showToast({ title: '未找到设备', icon: 'none' })
}, 15000)
lefuService.onDevicesList((devices) => {
const matched = devices.find(d => d.raw.deviceId === targetDeviceId)
if (!matched) return
if (scanTimer !== null) { clearTimeout(scanTimer); scanTimer = null }
lefuService.stopScan()
wx.showLoading({ title: '连接中...', mask: true })
lefuService.connect(matched.raw)
lefuService.onDeviceConnect(() => {
wx.hideLoading()
wx.setStorageSync('connectDeviceInfo', matched.raw)
})
lefuService.onDeviceInfo((info) => {
this._markConnected(info.serialNumber as string)
})
})
lefuService.startScan()
},
fail: () => {
wx.hideLoading()
wx.showToast({ title: '蓝牙未开启', icon: 'none' })
},
})
},
/* 点击「成员管理」→ 跳转成员管理页,sn 由目标页从缓存读取 */
onTapMember() {
wx.navigateTo({ url: '/pages/equipmentMember/equipmentMember' })
},
/* 点击「添加设备」→ 跳转设备搜索页 */
onTapAdd() {
wx.navigateTo({ url: '/pages/connectedDevice/connectedDevice' })
},
})