fix:最新
This commit is contained in:
306
src/utils/amap.ts
Normal file
306
src/utils/amap.ts
Normal file
@@ -0,0 +1,306 @@
|
||||
import { getAmapWebKey } from '@/config/app-env'
|
||||
|
||||
export interface MapLocationPoint {
|
||||
name?: string
|
||||
address: string
|
||||
latitude: number
|
||||
longitude: number
|
||||
}
|
||||
|
||||
export interface AmapSearchResult {
|
||||
places: MapLocationPoint[]
|
||||
error?: string
|
||||
}
|
||||
|
||||
interface AmapBaseResponse {
|
||||
status?: string | number
|
||||
info?: string
|
||||
infocode?: string
|
||||
}
|
||||
|
||||
interface AmapRegeoResponse extends AmapBaseResponse {
|
||||
regeocode?: {
|
||||
formatted_address?: string
|
||||
addressComponent?: {
|
||||
province?: string
|
||||
city?: string | string[]
|
||||
district?: string
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function getAmapApiBaseUrl(): string {
|
||||
// #ifdef H5
|
||||
if (import.meta.env.DEV) return '/amap-api'
|
||||
// #endif
|
||||
return 'https://restapi.amap.com'
|
||||
}
|
||||
|
||||
interface AmapInputTip {
|
||||
id?: string
|
||||
name?: string
|
||||
district?: string
|
||||
address?: string
|
||||
location?: string
|
||||
}
|
||||
|
||||
interface AmapInputTipsResponse extends AmapBaseResponse {
|
||||
tips?: AmapInputTip[]
|
||||
}
|
||||
|
||||
interface AmapPoi {
|
||||
name?: string
|
||||
address?: string
|
||||
pname?: string
|
||||
cityname?: string
|
||||
adname?: string
|
||||
location?: string
|
||||
distance?: string
|
||||
}
|
||||
|
||||
interface AmapPlaceSearchResponse extends AmapBaseResponse {
|
||||
pois?: AmapPoi[]
|
||||
}
|
||||
|
||||
function isAmapOk(status?: string | number): boolean {
|
||||
return String(status) === '1'
|
||||
}
|
||||
|
||||
function parseAmapLocation(location?: string): { longitude: number; latitude: number } | null {
|
||||
if (!location || location === '[]') return null
|
||||
const [lngText, latText] = location.split(',')
|
||||
const longitude = Number(lngText)
|
||||
const latitude = Number(latText)
|
||||
if (!Number.isFinite(longitude) || !Number.isFinite(latitude)) return null
|
||||
return { longitude, latitude }
|
||||
}
|
||||
|
||||
function parseAmapBody<T>(raw: unknown): T | null {
|
||||
if (raw == null) return null
|
||||
if (typeof raw === 'string') {
|
||||
try {
|
||||
return JSON.parse(raw) as T
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
return raw as T
|
||||
}
|
||||
|
||||
function resolveCityName(component?: AmapRegeoResponse['regeocode']): string {
|
||||
const city = component?.addressComponent?.city
|
||||
if (Array.isArray(city)) {
|
||||
const first = city.find((item) => item?.trim())
|
||||
if (first) return first.trim()
|
||||
} else if (typeof city === 'string' && city.trim()) {
|
||||
return city.trim()
|
||||
}
|
||||
const province = component?.addressComponent?.province?.trim()
|
||||
const district = component?.addressComponent?.district?.trim()
|
||||
return province || district || ''
|
||||
}
|
||||
|
||||
function dedupePlaces(list: MapLocationPoint[]): MapLocationPoint[] {
|
||||
const seen = new Set<string>()
|
||||
const result: MapLocationPoint[] = []
|
||||
for (const item of list) {
|
||||
const key = `${item.longitude.toFixed(6)},${item.latitude.toFixed(6)}`
|
||||
if (seen.has(key)) continue
|
||||
seen.add(key)
|
||||
result.push(item)
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
function mapPois(pois: AmapPoi[] | undefined): MapLocationPoint[] {
|
||||
if (!Array.isArray(pois)) return []
|
||||
const results: MapLocationPoint[] = []
|
||||
for (const poi of pois) {
|
||||
const name = poi.name?.trim()
|
||||
if (!name) continue
|
||||
const coords = parseAmapLocation(poi.location)
|
||||
if (!coords) continue
|
||||
const region = [poi.pname, poi.cityname, poi.adname].filter(Boolean).join('')
|
||||
const address = poi.address?.trim() || region || name
|
||||
results.push({
|
||||
name,
|
||||
address,
|
||||
latitude: coords.latitude,
|
||||
longitude: coords.longitude,
|
||||
})
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
function mapInputTips(body: AmapInputTipsResponse | null): MapLocationPoint[] {
|
||||
if (!body || !isAmapOk(body.status) || !Array.isArray(body.tips)) return []
|
||||
const results: MapLocationPoint[] = []
|
||||
for (const tip of body.tips) {
|
||||
const name = tip.name?.trim()
|
||||
if (!name) continue
|
||||
const coords = parseAmapLocation(tip.location)
|
||||
if (!coords) continue
|
||||
const address = tip.address?.trim() || tip.district?.trim() || name
|
||||
results.push({
|
||||
name,
|
||||
address,
|
||||
latitude: coords.latitude,
|
||||
longitude: coords.longitude,
|
||||
})
|
||||
}
|
||||
return results
|
||||
}
|
||||
|
||||
function mapAmapError(body: AmapBaseResponse | null, fallback = '地点搜索失败'): string {
|
||||
if (!body) return fallback
|
||||
const info = body.info?.trim()
|
||||
if (!info || info === 'OK') return fallback
|
||||
if (/USERKEY_PLAT_NWM/i.test(info)) {
|
||||
return '地图 Key 平台不匹配,请在高德控制台开启 Web 服务'
|
||||
}
|
||||
if (/INVALID_USER_KEY|USERKEY_PLAT/i.test(info)) {
|
||||
return '地图服务 Key 无效,请检查配置'
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
export function formatMapLocation(point: { name?: string; address?: string }): string {
|
||||
const name = point.name?.trim()
|
||||
const address = point.address?.trim()
|
||||
if (name && address && name !== address) return `${name} · ${address}`
|
||||
return name || address || ''
|
||||
}
|
||||
|
||||
export function toMapCoords(point: Pick<MapLocationPoint, 'latitude' | 'longitude'>) {
|
||||
return {
|
||||
latitude: point.latitude,
|
||||
longitude: point.longitude,
|
||||
}
|
||||
}
|
||||
|
||||
async function requestAmap<T extends AmapBaseResponse>(
|
||||
url: string,
|
||||
data: Record<string, string>,
|
||||
): Promise<T | null> {
|
||||
const key = getAmapWebKey()
|
||||
if (!key) return null
|
||||
try {
|
||||
const res = await uni.request({
|
||||
url: `${getAmapApiBaseUrl()}${url}`,
|
||||
method: 'GET',
|
||||
data: { ...data, key },
|
||||
timeout: 15000,
|
||||
})
|
||||
const statusCode = res.statusCode ?? 200
|
||||
if (statusCode < 200 || statusCode >= 300) return null
|
||||
return parseAmapBody<T>(res.data)
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
/** 高德逆地理编码(需配置 VITE_AMAP_WEB_KEY) */
|
||||
export async function reverseGeocodeAmap(
|
||||
latitude: number,
|
||||
longitude: number,
|
||||
): Promise<string | undefined> {
|
||||
const detail = await reverseGeocodeAmapDetail(latitude, longitude)
|
||||
return detail?.address
|
||||
}
|
||||
|
||||
/** 逆地理编码,附带城市信息(供搜索限定范围) */
|
||||
export async function reverseGeocodeAmapDetail(
|
||||
latitude: number,
|
||||
longitude: number,
|
||||
): Promise<{ address: string; city: string } | undefined> {
|
||||
const data = await requestAmap<AmapRegeoResponse>('/v3/geocode/regeo', {
|
||||
location: `${longitude},${latitude}`,
|
||||
extensions: 'base',
|
||||
})
|
||||
if (!data || !isAmapOk(data.status)) return undefined
|
||||
const address = data.regeocode?.formatted_address?.trim()
|
||||
const city = resolveCityName(data.regeocode)
|
||||
if (!address && !city) return undefined
|
||||
return {
|
||||
address: address || '',
|
||||
city,
|
||||
}
|
||||
}
|
||||
|
||||
/** 高德地点搜索(周边 + 输入提示 + 文本搜索) */
|
||||
export async function searchAmapPlaces(
|
||||
keyword: string,
|
||||
options?: { latitude?: number; longitude?: number; city?: string },
|
||||
): Promise<AmapSearchResult> {
|
||||
const trimmed = keyword.trim()
|
||||
if (!trimmed) return { places: [] }
|
||||
if (!getAmapWebKey()) {
|
||||
return { places: [], error: '地图搜索服务未配置' }
|
||||
}
|
||||
|
||||
const hasCoords = options?.latitude != null && options?.longitude != null
|
||||
const location = hasCoords
|
||||
? `${options!.longitude},${options!.latitude}`
|
||||
: undefined
|
||||
let city = options?.city?.trim() || ''
|
||||
|
||||
if (!city && hasCoords) {
|
||||
const detail = await reverseGeocodeAmapDetail(options!.latitude!, options!.longitude!)
|
||||
city = detail?.city || ''
|
||||
}
|
||||
|
||||
const tipsData: Record<string, string> = {
|
||||
keywords: trimmed,
|
||||
datatype: 'all',
|
||||
}
|
||||
if (city) tipsData.city = city
|
||||
if (location) tipsData.location = location
|
||||
|
||||
const textData: Record<string, string> = {
|
||||
keywords: trimmed,
|
||||
offset: '20',
|
||||
page: '1',
|
||||
extensions: 'base',
|
||||
}
|
||||
if (city) {
|
||||
textData.city = city
|
||||
textData.citylimit = 'true'
|
||||
}
|
||||
|
||||
const [aroundBody, tipsBody, textBody] = await Promise.all([
|
||||
location
|
||||
? requestAmap<AmapPlaceSearchResponse>('/v3/place/around', {
|
||||
keywords: trimmed,
|
||||
location,
|
||||
radius: '50000',
|
||||
offset: '20',
|
||||
page: '1',
|
||||
extensions: 'base',
|
||||
sortrule: 'distance',
|
||||
})
|
||||
: Promise.resolve(null),
|
||||
requestAmap<AmapInputTipsResponse>('/v3/assistant/inputtips', tipsData),
|
||||
requestAmap<AmapPlaceSearchResponse>('/v3/place/text', textData),
|
||||
])
|
||||
|
||||
const places = dedupePlaces([
|
||||
...mapPois(aroundBody?.pois),
|
||||
...mapInputTips(tipsBody),
|
||||
...mapPois(textBody?.pois),
|
||||
])
|
||||
|
||||
if (places.length) {
|
||||
return { places }
|
||||
}
|
||||
|
||||
const failed = [aroundBody, tipsBody, textBody].find((item) => item && !isAmapOk(item.status))
|
||||
if (failed) {
|
||||
return { places: [], error: mapAmapError(failed) }
|
||||
}
|
||||
|
||||
return { places: [] }
|
||||
}
|
||||
|
||||
export function hasAmapWebKey(): boolean {
|
||||
return !!getAmapWebKey()
|
||||
}
|
||||
@@ -22,9 +22,30 @@ export function unwrapApiData<T>(body: ApiResponse<T> & Record<string, unknown>)
|
||||
return body as T
|
||||
}
|
||||
|
||||
const NETWORK_ERROR_PATTERN = /request:fail|network\s*error|unable to resolve host|no address associated|failed to connect|connection\s*(refused|reset|timed out|timeout)|timed?\s*out|offline|statuscode:\s*-1|err_connection|net::/i
|
||||
|
||||
/** 将 uni.request / 系统层英文网络错误转为中文提示 */
|
||||
export function normalizeNetworkErrorMessage(
|
||||
message?: string,
|
||||
fallback = '网络异常,请检查网络后重试',
|
||||
): string {
|
||||
const text = message?.trim() ?? ''
|
||||
if (!text) return fallback
|
||||
if (NETWORK_ERROR_PATTERN.test(text)) return fallback
|
||||
return text
|
||||
}
|
||||
|
||||
export function getErrorMessage(err: unknown, fallback = '请求失败'): string {
|
||||
if (err instanceof ApiError) return err.message
|
||||
if (err instanceof Error && err.message) return err.message
|
||||
if (err instanceof ApiError) {
|
||||
return normalizeNetworkErrorMessage(err.message, fallback)
|
||||
}
|
||||
if (err instanceof Error && err.message) {
|
||||
return normalizeNetworkErrorMessage(err.message, fallback)
|
||||
}
|
||||
if (err && typeof err === 'object' && 'errMsg' in err) {
|
||||
const errMsg = String((err as { errMsg?: string }).errMsg || '')
|
||||
if (errMsg) return normalizeNetworkErrorMessage(errMsg, fallback)
|
||||
}
|
||||
if (err && typeof err === 'object' && 'data' in err) {
|
||||
const data = (err as { data?: ApiResponse }).data
|
||||
if (data?.msg) return data.msg
|
||||
|
||||
84
src/utils/ble-device-name.ts
Normal file
84
src/utils/ble-device-name.ts
Normal file
@@ -0,0 +1,84 @@
|
||||
import { getBleDeviceNamePrefix } from '@/config/app-env'
|
||||
import { compactMacAddress, normalizeMacAddress } from '@/utils/bluetooth'
|
||||
|
||||
export { getBleDeviceNamePrefix }
|
||||
|
||||
const BLE_NAME_SUFFIX_PATTERN = /^[0-9A-Fa-f]{12}$/
|
||||
|
||||
/** 从广播名解析 12 位 MAC(无分隔符) */
|
||||
export function parseMacFromBleDeviceName(name: string): string | undefined {
|
||||
const prefix = getBleDeviceNamePrefix()
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed.startsWith(prefix)) return undefined
|
||||
const suffix = trimmed.slice(prefix.length)
|
||||
if (!BLE_NAME_SUFFIX_PATTERN.test(suffix)) return undefined
|
||||
return suffix.toUpperCase()
|
||||
}
|
||||
|
||||
/** 是否为本品牌 BLE 设备(广播名符合 Z2_A_<12位MAC>) */
|
||||
export function isValidBleDeviceName(name: string): boolean {
|
||||
return !!parseMacFromBleDeviceName(name)
|
||||
}
|
||||
|
||||
export function isBrandBleDevice(device: UniApp.BluetoothDeviceInfo): boolean {
|
||||
const candidates = [device.name, device.localName]
|
||||
.filter(Boolean)
|
||||
.map((item) => String(item).trim())
|
||||
return candidates.some((item) => isValidBleDeviceName(item))
|
||||
}
|
||||
|
||||
/** 生成标准蓝牙广播名:Z2_A_<12位MAC> */
|
||||
export function buildBleDeviceName(mac: string): string {
|
||||
const compact = compactMacAddress(mac)
|
||||
if (compact.length !== 12) {
|
||||
throw new Error('MAC 地址无效,无法生成蓝牙名称')
|
||||
}
|
||||
return `${getBleDeviceNamePrefix()}${compact}`
|
||||
}
|
||||
|
||||
/** 广播名已是标准格式时无需再下发改名指令(避免设备重启导致断连) */
|
||||
export function isStandardBleDeviceName(mac: string, name?: string): boolean {
|
||||
const value = name?.trim()
|
||||
if (!value || !mac) return false
|
||||
try {
|
||||
return value === buildBleDeviceName(mac)
|
||||
} catch {
|
||||
return isValidBleDeviceName(value) && parseMacFromBleDeviceName(value) === compactMacAddress(mac)
|
||||
}
|
||||
}
|
||||
|
||||
/** 优先从 deviceId(Android)或广播名(iOS)解析 MAC */
|
||||
export function resolveBleDeviceMac(device: UniApp.BluetoothDeviceInfo): string | undefined {
|
||||
const fromId = normalizeMacAddress(device.deviceId)
|
||||
if (fromId) return compactMacAddress(fromId)
|
||||
|
||||
const candidates = [device.name, device.localName]
|
||||
.filter(Boolean)
|
||||
.map((item) => String(item).trim())
|
||||
|
||||
for (const name of candidates) {
|
||||
const parsed = parseMacFromBleDeviceName(name)
|
||||
if (parsed) return parsed
|
||||
}
|
||||
|
||||
return undefined
|
||||
}
|
||||
|
||||
export function resolveBleDeviceDisplayName(device: UniApp.BluetoothDeviceInfo): string {
|
||||
const candidates = [device.name, device.localName]
|
||||
.filter(Boolean)
|
||||
.map((item) => String(item).trim())
|
||||
const matched = candidates.find((item) => isValidBleDeviceName(item))
|
||||
if (matched) return matched
|
||||
|
||||
const mac = resolveBleDeviceMac(device)
|
||||
if (mac) {
|
||||
try {
|
||||
return buildBleDeviceName(mac)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
return candidates[0] || '未命名设备'
|
||||
}
|
||||
@@ -10,6 +10,8 @@ export class BluetoothError extends Error {
|
||||
|
||||
type UniFail = UniApp.GeneralCallbackResult
|
||||
|
||||
export const BLUETOOTH_DISABLED_MESSAGE = '请先打开手机蓝牙后再试'
|
||||
|
||||
function toBluetoothError(err: UniFail, fallback: string): BluetoothError {
|
||||
const msg = err.errMsg || fallback
|
||||
return new BluetoothError(getBluetoothErrorMessage({ errCode: err.errCode, errMsg: msg }), err.errCode)
|
||||
@@ -64,7 +66,70 @@ export async function ensureBluetoothReady(): Promise<void> {
|
||||
|
||||
const state = await getAdapterState()
|
||||
if (!state.available) {
|
||||
throw new BluetoothError('本机不支持蓝牙', 10009)
|
||||
throw new BluetoothError(BLUETOOTH_DISABLED_MESSAGE, 10001)
|
||||
}
|
||||
}
|
||||
|
||||
export function isBluetoothDisabledError(err: unknown): boolean {
|
||||
if (err instanceof BluetoothError && err.errCode === 10001) return true
|
||||
const code = (err as UniFail)?.errCode
|
||||
if (code === 10001) return true
|
||||
const message = err instanceof BluetoothError
|
||||
? err.message
|
||||
: String((err as UniFail)?.errMsg || (err instanceof Error ? err.message : ''))
|
||||
const lower = message.toLowerCase()
|
||||
return (
|
||||
message === BLUETOOTH_DISABLED_MESSAGE
|
||||
|| /请先打开手机蓝牙/.test(message)
|
||||
|| /bluetooth adapter not available|adapter not available|not init|not open|bluetooth.*off/i.test(lower)
|
||||
)
|
||||
}
|
||||
|
||||
export function openSystemBluetoothSetting(): Promise<void> {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof uni.openSystemBluetoothSetting !== 'function') {
|
||||
reject(new BluetoothError('当前环境无法打开系统蓝牙设置'))
|
||||
return
|
||||
}
|
||||
uni.openSystemBluetoothSetting({
|
||||
success: () => resolve(),
|
||||
fail: (err) => reject(toBluetoothError(err, '无法打开蓝牙设置')),
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
export function promptEnableBluetooth(content?: string) {
|
||||
uni.showModal({
|
||||
title: '请开启蓝牙',
|
||||
content: content || '添加设备需要使用手机蓝牙,请先在系统设置中打开蓝牙',
|
||||
confirmText: '去开启',
|
||||
cancelText: '取消',
|
||||
success: (res) => {
|
||||
if (!res.confirm) return
|
||||
void openSystemBluetoothSetting().catch(() => {
|
||||
uni.showToast({ title: BLUETOOTH_DISABLED_MESSAGE, icon: 'none' })
|
||||
})
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
export function isBluetoothPermissionError(err: unknown): boolean {
|
||||
const message = getBluetoothErrorMessage(err)
|
||||
return /定位权限|蓝牙相关权限|permission/i.test(message)
|
||||
}
|
||||
|
||||
/** 确认蓝牙已开启且可扫描(添加设备流程入口使用) */
|
||||
export async function assertBluetoothEnabledForScan(): Promise<void> {
|
||||
try {
|
||||
await ensureBluetoothReady()
|
||||
await startBluetoothDiscovery()
|
||||
await stopBluetoothDiscovery()
|
||||
} catch (err) {
|
||||
if (isBluetoothDisabledError(err) || isBluetoothPermissionError(err)) {
|
||||
throw err
|
||||
}
|
||||
// 部分机型蓝牙未开时 openAdapter 仍成功,扫描失败会落到通用错误
|
||||
throw new BluetoothError(BLUETOOTH_DISABLED_MESSAGE, 10001)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -217,6 +282,53 @@ export function closeBleConnection(bleDeviceId: string): Promise<void> {
|
||||
})
|
||||
}
|
||||
|
||||
/** 断开当前已连接的全部 BLE 设备,避免重连时 operate timeout */
|
||||
export async function closeAllBleConnections(): Promise<void> {
|
||||
if (typeof uni.getConnectedBluetoothDevices !== 'function') return
|
||||
try {
|
||||
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
|
||||
uni.getConnectedBluetoothDevices({
|
||||
success: resolve,
|
||||
fail: reject,
|
||||
})
|
||||
})
|
||||
for (const device of res.devices ?? []) {
|
||||
await closeBleConnection(device.deviceId).catch(() => {})
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
|
||||
export async function releaseBleDevice(bleDeviceId?: string): Promise<void> {
|
||||
if (!bleDeviceId) return
|
||||
await closeBleConnection(bleDeviceId).catch(() => {})
|
||||
}
|
||||
|
||||
/** 从系统已连接 BLE 列表中按 MAC 查找(GATT 已连接时扫描往往找不到设备) */
|
||||
export async function getConnectedBleDeviceByMac(
|
||||
mac: string,
|
||||
): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
if (typeof uni.getConnectedBluetoothDevices !== 'function') return null
|
||||
const normalizedMac = normalizeMacAddress(mac)
|
||||
if (!normalizedMac) return null
|
||||
|
||||
try {
|
||||
const res = await new Promise<UniApp.GetConnectedBluetoothDevicesSuccess>((resolve, reject) => {
|
||||
uni.getConnectedBluetoothDevices({
|
||||
success: resolve,
|
||||
fail: reject,
|
||||
})
|
||||
})
|
||||
for (const device of res.devices ?? []) {
|
||||
if (deviceMatchesMac(device, normalizedMac)) return device
|
||||
}
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
return null
|
||||
}
|
||||
|
||||
export function subscribeBleConnectionStateChange(
|
||||
onChange: (res: { deviceId: string; connected: boolean }) => void,
|
||||
): () => void {
|
||||
@@ -245,11 +357,12 @@ function deviceMatchesName(
|
||||
/** 扫描并匹配 MAC 或广播名的 BLE 设备(iOS 需依赖名称) */
|
||||
export async function scanForBleDeviceByMac(
|
||||
mac: string,
|
||||
options: { timeoutMs?: number; name?: string } = {},
|
||||
options: { timeoutMs?: number; name?: string; skipCached?: boolean } = {},
|
||||
): Promise<UniApp.BluetoothDeviceInfo | null> {
|
||||
const timeoutMs = options.timeoutMs ?? 15000
|
||||
const normalizedMac = normalizeMacAddress(mac)
|
||||
const targetName = options.name?.trim()
|
||||
const skipCached = options.skipCached ?? false
|
||||
|
||||
if (!normalizedMac && !targetName) return null
|
||||
|
||||
@@ -263,7 +376,7 @@ export async function scanForBleDeviceByMac(
|
||||
matched = device
|
||||
return true
|
||||
}
|
||||
if (targetName && deviceMatchesName(device, targetName)) {
|
||||
if (!normalizedMac && targetName && deviceMatchesName(device, targetName)) {
|
||||
matched = device
|
||||
return true
|
||||
}
|
||||
@@ -271,9 +384,11 @@ export async function scanForBleDeviceByMac(
|
||||
return false
|
||||
}
|
||||
|
||||
const existing = await getDiscoveredBluetoothDevices()
|
||||
if (pickMatch(existing)) {
|
||||
return matched
|
||||
if (!skipCached) {
|
||||
const existing = await getDiscoveredBluetoothDevices()
|
||||
if (pickMatch(existing)) {
|
||||
return matched
|
||||
}
|
||||
}
|
||||
|
||||
const unsubscribe = subscribeBluetoothDevicesFound((devices) => {
|
||||
@@ -371,11 +486,70 @@ export function findDeviceInBleScan(
|
||||
return null
|
||||
}
|
||||
|
||||
function mapBluetoothErrMsg(msg?: string): string | null {
|
||||
if (!msg) return null
|
||||
const lower = msg.toLowerCase()
|
||||
|
||||
if (
|
||||
lower.includes('operate time out')
|
||||
|| lower.includes('operation timeout')
|
||||
|| lower.includes('timed out')
|
||||
|| lower.includes('time out')
|
||||
) {
|
||||
return '蓝牙连接超时,请确认设备已开机并靠近手机后重试'
|
||||
}
|
||||
|
||||
if (lower.includes('createbleconnection')) {
|
||||
return '蓝牙连接失败,请确认设备已开机并靠近手机后重试'
|
||||
}
|
||||
|
||||
if (lower.includes('already connect') || lower.includes('already connected')) {
|
||||
return '设备已连接'
|
||||
}
|
||||
|
||||
if (
|
||||
lower.includes('bluetooth adapter not available')
|
||||
|| lower.includes('adapter not available')
|
||||
|| lower.includes('not init')
|
||||
|| lower.includes('not open')
|
||||
) {
|
||||
return '请先打开手机蓝牙后再试'
|
||||
}
|
||||
|
||||
if (lower.includes('no device') || lower.includes('device not found')) {
|
||||
return '没有找到指定设备,请确认已开机并靠近手机'
|
||||
}
|
||||
|
||||
if (lower.includes('connection fail') || lower.includes('connect fail')) {
|
||||
return '蓝牙连接失败,请靠近设备后重试'
|
||||
}
|
||||
|
||||
if (lower.includes('location') && lower.includes('permission')) {
|
||||
return '请开启定位权限后再使用蓝牙功能'
|
||||
}
|
||||
|
||||
if (lower.includes('permission')) {
|
||||
return '请授予蓝牙相关权限后重试'
|
||||
}
|
||||
|
||||
if (/:fail\b/i.test(msg) && /[a-z]/i.test(msg)) {
|
||||
return '蓝牙操作失败,请重试'
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
|
||||
export function getBluetoothErrorMessage(err: unknown): string {
|
||||
if (err instanceof BluetoothError) return err.message
|
||||
if (err instanceof BluetoothError) {
|
||||
const mapped = mapBluetoothErrMsg(err.message)
|
||||
if (mapped) return mapped
|
||||
return err.message
|
||||
}
|
||||
|
||||
const code = (err as UniFail)?.errCode
|
||||
const msg = (err as UniFail)?.errMsg
|
||||
const mapped = mapBluetoothErrMsg(msg)
|
||||
if (mapped) return mapped
|
||||
|
||||
switch (code) {
|
||||
case 10001:
|
||||
@@ -408,6 +582,6 @@ export function getBluetoothErrorMessage(err: unknown): string {
|
||||
case 10013:
|
||||
return '设备标识无效'
|
||||
default:
|
||||
return msg || '蓝牙不可用,请检查权限与系统设置'
|
||||
return mapBluetoothErrMsg(msg) || '蓝牙不可用,请检查权限与系统设置'
|
||||
}
|
||||
}
|
||||
|
||||
72
src/utils/location-permission.ts
Normal file
72
src/utils/location-permission.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
/** App 端请求定位权限(Android 需运行时授权;iOS 依赖 manifest 隐私描述) */
|
||||
export async function ensureLocationPermission(): Promise<boolean> {
|
||||
// #ifdef APP-PLUS
|
||||
const system = uni.getSystemInfoSync()
|
||||
if (system.platform === 'android') {
|
||||
return requestAndroidLocationPermission()
|
||||
}
|
||||
// #endif
|
||||
return true
|
||||
}
|
||||
|
||||
// #ifdef APP-PLUS
|
||||
function requestAndroidLocationPermission(): Promise<boolean> {
|
||||
return new Promise((resolve) => {
|
||||
plus.android.requestPermissions(
|
||||
[
|
||||
'android.permission.ACCESS_FINE_LOCATION',
|
||||
'android.permission.ACCESS_COARSE_LOCATION',
|
||||
],
|
||||
(result) => {
|
||||
const granted = (result.granted?.length ?? 0) > 0
|
||||
if (!granted) {
|
||||
promptOpenAppSettings('请在系统设置中允许使用位置信息,以便选择家庭位置')
|
||||
}
|
||||
resolve(granted)
|
||||
},
|
||||
() => resolve(false),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
function promptOpenAppSettings(content: string) {
|
||||
uni.showModal({
|
||||
title: '需要定位权限',
|
||||
content,
|
||||
confirmText: '去设置',
|
||||
success: (res) => {
|
||||
if (!res.confirm) return
|
||||
try {
|
||||
const Intent = plus.android.importClass('android.content.Intent') as {
|
||||
new (action: string): { setData: (uri: unknown) => void }
|
||||
}
|
||||
const Settings = plus.android.importClass('android.provider.Settings') as {
|
||||
ACTION_APPLICATION_DETAILS_SETTINGS: string
|
||||
}
|
||||
const Uri = plus.android.importClass('android.net.Uri') as {
|
||||
parse: (uri: string) => unknown
|
||||
}
|
||||
const main = plus.android.runtimeMainActivity() as { getPackageName: () => string; startActivity: (intent: unknown) => void }
|
||||
const intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS)
|
||||
intent.setData(Uri.parse(`package:${main.getPackageName()}`))
|
||||
main.startActivity(intent)
|
||||
} catch {
|
||||
// ignore
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
// #endif
|
||||
|
||||
export function getLocationFailHint(err: unknown): string {
|
||||
const message = err && typeof err === 'object' && 'errMsg' in err
|
||||
? String((err as { errMsg?: string }).errMsg || '')
|
||||
: ''
|
||||
if (/auth|denied|permission|authorize/i.test(message)) {
|
||||
return '定位权限未开启,请在系统设置中允许使用位置信息'
|
||||
}
|
||||
if (/timeout|timed out/i.test(message)) {
|
||||
return '定位超时,请确认已开启手机定位服务后重试'
|
||||
}
|
||||
return '定位失败,请检查定位权限与手机定位服务'
|
||||
}
|
||||
@@ -61,7 +61,7 @@ function resolveMessageWsBase(): string {
|
||||
return configured.replace(/[?#].*$/, '').replace(/\/$/, '')
|
||||
}
|
||||
|
||||
const httpBase = getApiBaseUrl() || 'http://192.168.0.222:8082'
|
||||
const httpBase = getApiBaseUrl() || 'https://smart.bugtc.com'
|
||||
const wsBase = httpBase.replace(/^https/i, 'wss').replace(/^http/i, 'ws')
|
||||
return `${wsBase}/app/ws/message`
|
||||
}
|
||||
|
||||
32
src/utils/password-modified-at.ts
Normal file
32
src/utils/password-modified-at.ts
Normal file
@@ -0,0 +1,32 @@
|
||||
const STORAGE_KEY = 'czzj_password_modified_at'
|
||||
|
||||
/** 密码修改成功后记录时间戳 */
|
||||
export function markPasswordModified(at = Date.now()): void {
|
||||
uni.setStorageSync(STORAGE_KEY, at)
|
||||
}
|
||||
|
||||
export function getPasswordModifiedAt(): number | null {
|
||||
const value = uni.getStorageSync(STORAGE_KEY)
|
||||
if (typeof value === 'number' && value > 0) return value
|
||||
if (typeof value === 'string' && /^\d+$/.test(value)) return Number(value)
|
||||
return null
|
||||
}
|
||||
|
||||
/** 展示「上次修改:刚刚 / 3天前」等文案 */
|
||||
export function formatPasswordModifiedDesc(at: number | null): string {
|
||||
if (!at) return '上次修改:暂无记录'
|
||||
|
||||
const diff = Date.now() - at
|
||||
if (diff < 0) return '上次修改:刚刚'
|
||||
|
||||
const minute = 60 * 1000
|
||||
const hour = 60 * minute
|
||||
const day = 24 * hour
|
||||
|
||||
if (diff < minute) return '上次修改:刚刚'
|
||||
if (diff < hour) return `上次修改:${Math.floor(diff / minute)}分钟前`
|
||||
if (diff < day) return `上次修改:${Math.floor(diff / hour)}小时前`
|
||||
if (diff < 30 * day) return `上次修改:${Math.floor(diff / day)}天前`
|
||||
if (diff < 365 * day) return `上次修改:${Math.floor(diff / (30 * day))}个月前`
|
||||
return `上次修改:${Math.floor(diff / (365 * day))}年前`
|
||||
}
|
||||
16
src/utils/selected-home.ts
Normal file
16
src/utils/selected-home.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
import { parseId } from '@/utils/device-id'
|
||||
|
||||
export const SELECTED_HOME_ID_KEY = 'device_selected_home_id'
|
||||
|
||||
export function readStoredHomeId(): string {
|
||||
try {
|
||||
return parseId(uni.getStorageSync(SELECTED_HOME_ID_KEY) as string | number | undefined)
|
||||
} catch {
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function saveSelectedHomeId(id: string) {
|
||||
if (!id) return
|
||||
uni.setStorageSync(SELECTED_HOME_ID_KEY, id)
|
||||
}
|
||||
@@ -7,7 +7,7 @@ import iconPassword from '@/static/icon-password.png'
|
||||
import iconDeviceDetailSettings from '@/static/icon-device-settings.png'
|
||||
import deviceDetailHeroBg from '@/static/device-detail-hero-bg@2x.png'
|
||||
import iconRunModeInfo from '@/static/icon-run-mode-info@2x.png'
|
||||
import iconHomeSelector from '@/static/icon-home-selector.png'
|
||||
import iconHomeSelector from '@/static/house.png'
|
||||
import iconHomeArrow from '@/static/icon-home-arrow.png'
|
||||
import iconHomeSelected from '@/static/icon-home-selected@2x.png'
|
||||
import iconNotify from '@/static/icon-notify.png'
|
||||
@@ -21,10 +21,10 @@ import iconBindSecure from '@/static/icon-bind-secure@2x.png'
|
||||
import iconScanDevice from '@/static/icon-scan-device@2x.png'
|
||||
import iconScanDeviceAction from '@/static/icon-scan-device-action@2x.png'
|
||||
import iconScanDeviceActionDisabled from '@/static/icon-scan-device-action-disabled@2x.png'
|
||||
import tabDevice from '@/static/tab-device-active.png'
|
||||
import tabDeviceActive from '@/static/tab-device.png'
|
||||
import tabMine from '@/static/tab-mine-active.png'
|
||||
import tabMineActive from '@/static/tab-mine.png'
|
||||
import tabDevice from '@/static/linear@4x.png'
|
||||
import tabDeviceActive from '@/static/home-2@4x.png'
|
||||
import tabMine from '@/static/user@4x (1).png'
|
||||
import tabMineActive from '@/static/user@4x.png'
|
||||
import iconChevronLeft from '@/static/icon-chevron-left.png'
|
||||
import iconSupportMic from '@/static/icon-support-mic.png'
|
||||
import iconSupportPhoto from '@/static/icon-support-photo.png'
|
||||
|
||||
@@ -49,6 +49,34 @@ export const Z2_BLE_CMD = {
|
||||
FILTER_RESET: 'F',
|
||||
} as const
|
||||
|
||||
/** 蓝牙改名结果(Notify: R=) */
|
||||
export const Z2_BLE_RENAME_RESULT = {
|
||||
SUCCESS: 2,
|
||||
TIMEOUT: 3,
|
||||
} as const
|
||||
|
||||
/** 蓝牙改名阶段(Notify: S=) */
|
||||
export const Z2_BLE_RENAME_STAGE = {
|
||||
AT: 1,
|
||||
READ_MAC: 2,
|
||||
SET_CLASSIC_NAME: 3,
|
||||
SET_BLE_NAME: 4,
|
||||
DONE_RESTART: 5,
|
||||
} as const
|
||||
|
||||
export type Z2RenameResultCode =
|
||||
(typeof Z2_BLE_RENAME_RESULT)[keyof typeof Z2_BLE_RENAME_RESULT]
|
||||
|
||||
export type Z2RenameStageCode =
|
||||
(typeof Z2_BLE_RENAME_STAGE)[keyof typeof Z2_BLE_RENAME_STAGE]
|
||||
|
||||
export interface Z2RenameProgress {
|
||||
result?: Z2RenameResultCode
|
||||
stage?: Z2RenameStageCode
|
||||
/** 改名过程中收到的串口字节数(Notify: C=) */
|
||||
serialBytes?: number
|
||||
}
|
||||
|
||||
export function normalizeBleUuid(value: string): string {
|
||||
return value.replace(/-/g, '').toUpperCase()
|
||||
}
|
||||
@@ -328,6 +356,130 @@ export function mapZ2StateToRuntimePatch(state: Z2DeviceState) {
|
||||
}
|
||||
}
|
||||
|
||||
function parseRenameStage(value: string): Z2RenameStageCode | undefined {
|
||||
const stage = Number(value)
|
||||
if (stage === Z2_BLE_RENAME_STAGE.AT) return Z2_BLE_RENAME_STAGE.AT
|
||||
if (stage === Z2_BLE_RENAME_STAGE.READ_MAC) return Z2_BLE_RENAME_STAGE.READ_MAC
|
||||
if (stage === Z2_BLE_RENAME_STAGE.SET_CLASSIC_NAME) return Z2_BLE_RENAME_STAGE.SET_CLASSIC_NAME
|
||||
if (stage === Z2_BLE_RENAME_STAGE.SET_BLE_NAME) return Z2_BLE_RENAME_STAGE.SET_BLE_NAME
|
||||
if (stage === Z2_BLE_RENAME_STAGE.DONE_RESTART) return Z2_BLE_RENAME_STAGE.DONE_RESTART
|
||||
return undefined
|
||||
}
|
||||
|
||||
function parseRenameResult(value: string): Z2RenameResultCode | undefined {
|
||||
const result = Number(value)
|
||||
if (result === Z2_BLE_RENAME_RESULT.SUCCESS) return Z2_BLE_RENAME_RESULT.SUCCESS
|
||||
if (result === Z2_BLE_RENAME_RESULT.TIMEOUT) return Z2_BLE_RENAME_RESULT.TIMEOUT
|
||||
return undefined
|
||||
}
|
||||
|
||||
/** 解析改名 Notify,如 `S=3;R=2;C=128` */
|
||||
export function parseZ2RenameNotifyLine(line: string): Z2RenameProgress {
|
||||
const patch: Z2RenameProgress = {}
|
||||
const segments = line.split(';').filter(Boolean)
|
||||
|
||||
for (const segment of segments) {
|
||||
const eqIndex = segment.indexOf('=')
|
||||
if (eqIndex <= 0) continue
|
||||
|
||||
const key = normalizeToken(segment.slice(0, eqIndex))
|
||||
const value = segment.slice(eqIndex + 1).trim().replace(/\0/g, '')
|
||||
if (!value) continue
|
||||
|
||||
switch (key) {
|
||||
case 'R': {
|
||||
const result = parseRenameResult(value)
|
||||
if (result != null) patch.result = result
|
||||
break
|
||||
}
|
||||
case 'S': {
|
||||
const stage = parseRenameStage(value)
|
||||
if (stage != null) patch.stage = stage
|
||||
break
|
||||
}
|
||||
case 'C': {
|
||||
const serialBytes = Number(value)
|
||||
if (Number.isFinite(serialBytes)) patch.serialBytes = serialBytes
|
||||
break
|
||||
}
|
||||
default:
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return patch
|
||||
}
|
||||
|
||||
export function mergeZ2RenameProgress(
|
||||
base: Z2RenameProgress,
|
||||
patch: Z2RenameProgress,
|
||||
): Z2RenameProgress {
|
||||
return {
|
||||
...base,
|
||||
...patch,
|
||||
}
|
||||
}
|
||||
|
||||
export function parseZ2RenameNotifyPayload(lines: string[]): Z2RenameProgress {
|
||||
let progress: Z2RenameProgress = {}
|
||||
for (const line of lines) {
|
||||
for (const record of splitZ2NotifyRecords(line)) {
|
||||
progress = mergeZ2RenameProgress(progress, parseZ2RenameNotifyLine(record))
|
||||
}
|
||||
}
|
||||
return progress
|
||||
}
|
||||
|
||||
export function isZ2RenameFinished(progress: Z2RenameProgress): boolean {
|
||||
return progress.result === Z2_BLE_RENAME_RESULT.SUCCESS
|
||||
|| progress.result === Z2_BLE_RENAME_RESULT.TIMEOUT
|
||||
}
|
||||
|
||||
export function isZ2RenameSuccessful(progress: Z2RenameProgress): boolean {
|
||||
return progress.result === Z2_BLE_RENAME_RESULT.SUCCESS
|
||||
}
|
||||
|
||||
export function getZ2RenameStageLabel(stage?: Z2RenameStageCode): string {
|
||||
switch (stage) {
|
||||
case Z2_BLE_RENAME_STAGE.AT:
|
||||
return '进入 AT 阶段'
|
||||
case Z2_BLE_RENAME_STAGE.READ_MAC:
|
||||
return '读取 MAC'
|
||||
case Z2_BLE_RENAME_STAGE.SET_CLASSIC_NAME:
|
||||
return '设置经典蓝牙名称'
|
||||
case Z2_BLE_RENAME_STAGE.SET_BLE_NAME:
|
||||
return '设置 BLE 名称'
|
||||
case Z2_BLE_RENAME_STAGE.DONE_RESTART:
|
||||
return '设置完成,设备重启中'
|
||||
default:
|
||||
return '正在改名…'
|
||||
}
|
||||
}
|
||||
|
||||
export function getZ2RenameResultLabel(result?: Z2RenameResultCode): string {
|
||||
switch (result) {
|
||||
case Z2_BLE_RENAME_RESULT.SUCCESS:
|
||||
return '改名成功'
|
||||
case Z2_BLE_RENAME_RESULT.TIMEOUT:
|
||||
return '改名超时失败'
|
||||
default:
|
||||
return ''
|
||||
}
|
||||
}
|
||||
|
||||
export function getZ2RenameProgressLabel(progress: Z2RenameProgress): string {
|
||||
const resultLabel = getZ2RenameResultLabel(progress.result)
|
||||
if (resultLabel) return resultLabel
|
||||
return getZ2RenameStageLabel(progress.stage)
|
||||
}
|
||||
|
||||
/** 发送改名指令(Notify 回报 R/S/C);名称须为 Z2_A_<12位MAC> */
|
||||
export function encodeZ2RenameCommand(bleName: string): string {
|
||||
const value = bleName.trim()
|
||||
if (!value) throw new Error('蓝牙名称不能为空')
|
||||
return `N=${value}`
|
||||
}
|
||||
|
||||
export function encodeRunModeBleCommand(runMode: string): string {
|
||||
switch (runMode) {
|
||||
case '1': return Z2_BLE_CMD.WORK_MODE_CAR
|
||||
|
||||
@@ -1,8 +1,13 @@
|
||||
import { BluetoothError } from '@/utils/bluetooth'
|
||||
import { BluetoothError, getBluetoothErrorMessage } from '@/utils/bluetooth'
|
||||
import {
|
||||
bleUuidMatches,
|
||||
encodeZ2RenameCommand,
|
||||
isZ2RenameFinished,
|
||||
mergeZ2RenameProgress,
|
||||
normalizeZ2NotifyText,
|
||||
parseZ2NotifyPayload,
|
||||
parseZ2RenameNotifyLine,
|
||||
parseZ2RenameNotifyPayload,
|
||||
splitZ2NotifyRecords,
|
||||
Z2_BLE_NOTIFY_CHAR_ALIASES,
|
||||
Z2_BLE_NOTIFY_CHAR_UUID,
|
||||
@@ -10,13 +15,15 @@ import {
|
||||
Z2_BLE_WRITE_CHAR_ALIASES,
|
||||
Z2_BLE_WRITE_CHAR_UUID,
|
||||
type Z2DeviceState,
|
||||
type Z2RenameProgress,
|
||||
} from '@/utils/z2-ble-protocol'
|
||||
|
||||
type BleCharacteristic = UniApp.GetBLEDeviceCharacteristicsSuccess['characteristics'][number]
|
||||
|
||||
function toBluetoothError(err: UniApp.GeneralCallbackResult, fallback: string): BluetoothError {
|
||||
const fail = err as UniApp.GeneralCallbackResult & { errCode?: number }
|
||||
return new BluetoothError(fail.errMsg || fallback, fail.errCode)
|
||||
const message = getBluetoothErrorMessage(fail) || fallback
|
||||
return new BluetoothError(message, fail.errCode)
|
||||
}
|
||||
|
||||
function sleep(ms: number): Promise<void> {
|
||||
@@ -305,9 +312,16 @@ function resolveNotifyRecords(buffer: string): string[] {
|
||||
return records.length ? records : normalized ? [normalized] : []
|
||||
}
|
||||
|
||||
interface CollectNotifyOptions {
|
||||
maxWaitMs?: number
|
||||
idleMs?: number
|
||||
onRecords?: (records: string[]) => void
|
||||
shouldStop?: (records: string[]) => boolean
|
||||
}
|
||||
|
||||
async function collectNotifyLines(
|
||||
deviceId: string,
|
||||
options: { maxWaitMs?: number; idleMs?: number } = {},
|
||||
options: CollectNotifyOptions = {},
|
||||
): Promise<string[]> {
|
||||
const maxWaitMs = options.maxWaitMs ?? 6000
|
||||
const idleMs = options.idleMs ?? 400
|
||||
@@ -327,6 +341,15 @@ async function collectNotifyLines(
|
||||
resolve(records)
|
||||
}
|
||||
|
||||
const emitRecords = () => {
|
||||
const records = resolveNotifyRecords(buffer)
|
||||
if (!records.length) return
|
||||
options.onRecords?.(records)
|
||||
if (options.shouldStop?.(records)) {
|
||||
finish()
|
||||
}
|
||||
}
|
||||
|
||||
const scheduleIdleFinish = () => {
|
||||
if (idleTimer) clearTimeout(idleTimer)
|
||||
idleTimer = setTimeout(finish, idleMs)
|
||||
@@ -338,6 +361,7 @@ async function collectNotifyLines(
|
||||
if (!text) return
|
||||
logZ2BleDebug('notify chunk', text)
|
||||
buffer = appendNotifyText(buffer, text)
|
||||
emitRecords()
|
||||
scheduleIdleFinish()
|
||||
}
|
||||
|
||||
@@ -410,6 +434,56 @@ export async function queryZ2BleState(deviceId: string): Promise<Z2DeviceState>
|
||||
return sendZ2BleCommand(deviceId, 'Q', { timeoutMs: 6000 })
|
||||
}
|
||||
|
||||
/** 蓝牙改名(Notify 回报 S 阶段 / R 结果 / C 字节数) */
|
||||
export async function sendZ2BleRenameCommand(
|
||||
deviceId: string,
|
||||
name: string,
|
||||
options: {
|
||||
timeoutMs?: number
|
||||
onProgress?: (progress: Z2RenameProgress) => void
|
||||
} = {},
|
||||
): Promise<Z2RenameProgress> {
|
||||
const command = encodeZ2RenameCommand(name)
|
||||
const handles = await resolveZ2BleHandles(deviceId)
|
||||
let progress: Z2RenameProgress = {}
|
||||
|
||||
const maxWaitMs = options.timeoutMs ?? 90000
|
||||
const notifyPromise = collectNotifyLines(deviceId, {
|
||||
maxWaitMs,
|
||||
idleMs: 800,
|
||||
onRecords: (records) => {
|
||||
for (const record of records) {
|
||||
progress = mergeZ2RenameProgress(progress, parseZ2RenameNotifyLine(record))
|
||||
}
|
||||
options.onProgress?.(progress)
|
||||
},
|
||||
shouldStop: (records) => isZ2RenameFinished(parseZ2RenameNotifyPayload(records)),
|
||||
})
|
||||
|
||||
const notifyTarget = await enableBleNotify(
|
||||
deviceId,
|
||||
handles.serviceId,
|
||||
handles.notifyCandidates,
|
||||
)
|
||||
|
||||
handleCache.set(deviceId, {
|
||||
serviceId: handles.serviceId,
|
||||
writeCharId: handles.writeChar.uuid,
|
||||
notifyCharId: notifyTarget.charId,
|
||||
notifyHandle: notifyTarget.handle,
|
||||
})
|
||||
|
||||
await sleep(200)
|
||||
logZ2BleDebug('write rename command', command)
|
||||
await writeBleAscii(deviceId, handles.serviceId, handles.writeChar.uuid, command)
|
||||
|
||||
const lines = await notifyPromise
|
||||
progress = parseZ2RenameNotifyPayload(lines)
|
||||
options.onProgress?.(progress)
|
||||
logZ2BleDebug('rename finished', progress)
|
||||
return progress
|
||||
}
|
||||
|
||||
export function clearZ2BleHandleCache(deviceId?: string) {
|
||||
if (deviceId) {
|
||||
handleCache.delete(deviceId)
|
||||
|
||||
Reference in New Issue
Block a user