ble.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940
  1. /**
  2. * 艾灸椅 BLE Pinia Store
  3. * 真正的应用级单例,跨页面共享蓝牙状态
  4. *
  5. * 用法:
  6. * import { useBleStore } from '@/stores/ble'
  7. * const bleStore = useBleStore()
  8. *
  9. * // 扫描
  10. * await bleStore.startScan({ timeout: 15000, returnAll: true })
  11. *
  12. * // 连接
  13. * await bleStore.connectDevice(deviceId)
  14. *
  15. * // 发送指令
  16. * await bleStore.sendBasic({ power: 1, moxiState: 1 })
  17. *
  18. * // 读取状态(自动响应式)
  19. * bleStore.linked / bleStore.searching / bleStore.deviceStatus
  20. */
  21. import { defineStore } from 'pinia'
  22. import logger from '@/utils/ble/logger.js'
  23. import {
  24. DEFAULT_CONFIG, BLE_STATE, BLE_ERROR,
  25. POWER, MOXI_STATE, MUTE, MODE, SUB_MODE, TEMPERATURE, CHAIR_ANGLE
  26. } from '@/utils/ble/constants.js'
  27. import {
  28. encodeBasic, encodeModeParam1, encodeModeParam2, encodeAcupoints,
  29. bufferToArrayBuffer, arrayBufferToU8, bytesToHex, FrameParser
  30. } from '@/utils/ble/protocol.js'
  31. import { ensureBlePrerequisite, openLocationSettings } from '@/utils/ble/permission.js'
  32. // ========== 跨 nvue 页面共享内部变量(通过 globalData 确保单例) ==========
  33. function _getShared() {
  34. const app = getApp()
  35. if (!app.globalData) app.globalData = {}
  36. if (!app.globalData._bleInternal) {
  37. app.globalData._bleInternal = {
  38. instanceId: Date.now() + '_' + Math.random().toString(36).slice(2, 6),
  39. serviceId: null,
  40. writeCharId: null,
  41. notifyCharId: null,
  42. reconnectTimer: null,
  43. reconnectCount: 0,
  44. reconnectGeneration: 0, // 重连代数,用于丢弃僵尸回调
  45. writeLock: Promise.resolve(),
  46. bound: false,
  47. cancelScan: null,
  48. scanAborted: false, // 标记扫描已被外部中止,防止僵尸扫描
  49. onDeviceFound: null, // 当前扫描的设备发现回调
  50. scanStartHistory: [], // 近期 startDiscovery 调用时间戳,用于检测 Android 限流
  51. intentionalDisconnect: false, // 标记主动断开,防止系统回调误触发重连
  52. _connectedBeforeScan: false, // 标记扫描前是否处于已连接状态
  53. parser: null,
  54. config: { ...DEFAULT_CONFIG }
  55. }
  56. console.log(`[BLE Store] 首次创建共享实例,instanceId = ${app.globalData._bleInternal.instanceId}`)
  57. }
  58. return app.globalData._bleInternal
  59. }
  60. // 兼容模块加载阶段(getApp()可能未就绪),延迟到首次调用时获取
  61. let _shared = null
  62. function _S() {
  63. if (!_shared) _shared = _getShared()
  64. return _shared
  65. }
  66. // 便捷访问
  67. function _instanceId() { return _S().instanceId }
  68. // ========== 工具函数 ==========
  69. function _invoke(apiFn, params) {
  70. return new Promise((resolve, reject) => {
  71. apiFn({ ...params, success: resolve, fail: reject, complete: () => {} })
  72. })
  73. }
  74. function _err(code, origin) {
  75. const err = new Error(code)
  76. err.code = code
  77. if (origin) err.origin = origin
  78. return err
  79. }
  80. function _uuidEq(a, b) {
  81. return String(a || '').toLowerCase() === String(b || '').toLowerCase()
  82. }
  83. export const useBleStore = defineStore('ble', {
  84. state: () => ({
  85. // ===== 连接状态 =====
  86. bleState: BLE_STATE.IDLE,
  87. device: null, // { deviceId, name, RSSI }
  88. linked: false,
  89. // ===== 蓝牙开关状态 =====
  90. bleAdapterOff: false, // 蓝牙适配器未开启,页面可监听此状态展示提示
  91. // ===== 扫描 =====
  92. searching: false,
  93. scannedDevices: [],
  94. scanThrottled: false, // 检测到 Android 扫描限流时为 true,页面可监听此状态提示用户
  95. // ===== 设备运行状态(来自上报) =====
  96. deviceStatus: 0, // 0停止 1预热 2点火 3艾灸 4灭火 5暂停
  97. hotPercentage: '0%',
  98. ispreHot: false,
  99. subTime: '00:00:00',
  100. modeType: 0, // 0无艾灸 1专业 2自定义 3专家
  101. chairAngle: 90,
  102. // ===== 重连 =====
  103. reconnectDrawer: false,
  104. reconnectCount: 0,
  105. // ===== 异常 =====
  106. excepDrawer: false,
  107. exceTxt: 0,
  108. // ===== 耗材状态 =====
  109. otherSetting: {
  110. aijiuNum: '0',
  111. lvxinNum: '0',
  112. huishouNum: '0'
  113. }
  114. }),
  115. actions: {
  116. // ============== 配置 ==============
  117. configure(opt = {}) {
  118. const s = _S()
  119. s.config = { ...s.config, ...opt }
  120. logger.setEnabled(s.config.debug)
  121. },
  122. // ============== 内部状态管理 ==============
  123. _setState(s) {
  124. if (this.bleState === s) return
  125. const prevState = this.bleState
  126. this.bleState = s
  127. // 进入扫描状态时,如果当前有活跃连接,不应丢失 linked 状态
  128. if (s === BLE_STATE.SCANNING && prevState === BLE_STATE.READY_COMM) {
  129. _S()._connectedBeforeScan = true
  130. // linked 保持 true,仅更新 searching
  131. } else if (s === BLE_STATE.READY && _S()._connectedBeforeScan && this.device) {
  132. // 扫描结束恢复连接状态:物理连接仍存活
  133. _S()._connectedBeforeScan = false
  134. this.bleState = BLE_STATE.READY_COMM
  135. this.linked = true
  136. } else {
  137. _S()._connectedBeforeScan = false
  138. this.linked = (s === BLE_STATE.READY_COMM)
  139. }
  140. this.searching = (s === BLE_STATE.SCANNING)
  141. logger.info(`[instanceId=${_instanceId()}] state ->`, s, this.linked ? '(linked)' : '')
  142. },
  143. // ============== 初始化 / 释放 ==============
  144. async init() {
  145. console.log(`[BLE Store] init() called, instanceId = ${_instanceId()}`)
  146. if (this.bleState !== BLE_STATE.IDLE && this.bleState !== BLE_STATE.DISCONNECTED) {
  147. logger.info('蓝牙已初始化,跳过重复初始化')
  148. return
  149. }
  150. try {
  151. await _invoke(uni.openBluetoothAdapter, {})
  152. this.bleAdapterOff = false
  153. } catch (e) {
  154. logger.error('openBluetoothAdapter fail', e)
  155. const code = e && (e.errCode || e.code)
  156. const isOff = code === 10001
  157. if (isOff) {
  158. this.bleAdapterOff = true
  159. this._showBleOffPrompt('请先开启手机蓝牙,才能连接艾灸椅设备')
  160. }
  161. throw _err(isOff ? BLE_ERROR.ADAPTER_OFF : BLE_ERROR.NOT_SUPPORT, e)
  162. }
  163. this._bindSystemListeners()
  164. this._setState(BLE_STATE.READY)
  165. logger.info('蓝牙适配器已初始化')
  166. },
  167. async destroy() {
  168. this._clearReconnect()
  169. const s = _S()
  170. if (s.cancelScan) { s.cancelScan(); s.cancelScan = null }
  171. s.onDeviceFound = null
  172. try { await this.disconnect() } catch (_) {}
  173. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  174. this._unbindSystemListeners()
  175. this._setState(BLE_STATE.IDLE)
  176. if (s.parser) s.parser.reset()
  177. },
  178. /**
  179. * 轻量级重置:只关闭适配器并重置状态,不解绑全局监听器
  180. * 适用于页面切换时清除残留扫描/连接状态
  181. */
  182. async resetAdapter() {
  183. const s = _S()
  184. s.intentionalDisconnect = true
  185. this._clearReconnect()
  186. if (s.cancelScan) { s.cancelScan(); s.cancelScan = null }
  187. s.onDeviceFound = null
  188. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  189. this._setState(BLE_STATE.IDLE)
  190. if (s.parser) s.parser.reset()
  191. s.intentionalDisconnect = false
  192. },
  193. /**
  194. * 绑定BLE系统监听器 - 必须在 App.vue onLaunch 中调用
  195. * 确保回调绑定到 App.vue 的 taskCenter(永不销毁)
  196. */
  197. bindGlobalListeners() {
  198. if (_S().bound) return
  199. this._bindSystemListeners()
  200. },
  201. _bindSystemListeners() {
  202. const s = _S()
  203. if (s.bound) return
  204. // 初始化帧解析器
  205. if (!s.parser) {
  206. s.parser = new FrameParser(
  207. (decoded, frame) => this._onFrame(decoded, frame),
  208. (err, frame) => logger.warn('frame parse error', err.message, bytesToHex(frame))
  209. )
  210. }
  211. uni.onBluetoothAdapterStateChange(this._onAdapterStateChange = (res) => {
  212. logger.info('adapterStateChange', res)
  213. const s = _S()
  214. if (!res.available) {
  215. // 主动关闭适配器时不显示提示且不触发重连
  216. if (s.intentionalDisconnect) return
  217. this.bleAdapterOff = true
  218. this._showBleOffPrompt('蓝牙已关闭,设备连接已断开。请重新开启蓝牙以继续使用')
  219. this._handleDisconnected(BLE_ERROR.ADAPTER_OFF)
  220. } else {
  221. this.bleAdapterOff = false
  222. // 蓝牙重新开启:如果之前有连接过的设备且当前处于断连状态,自动发起重连
  223. this._onAdapterRestored()
  224. }
  225. })
  226. uni.onBLEConnectionStateChange(this._onConnStateChange = (res) => {
  227. logger.info('connectionStateChange', res)
  228. if (!res.connected && this.device && res.deviceId === this.device.deviceId) {
  229. this._handleDisconnected(BLE_ERROR.DISCONNECTED)
  230. }
  231. })
  232. uni.onBLECharacteristicValueChange(this._onCharChange = (res) => {
  233. const u8 = arrayBufferToU8(res.value)
  234. logger.log('<=', bytesToHex(u8))
  235. if (s.parser) s.parser.feed(u8)
  236. })
  237. // 永久注册设备发现监听器(不可反复 on/off,否则多次后系统丢失监听)
  238. uni.onBluetoothDeviceFound((res) => {
  239. const deviceCount = res && res.devices ? res.devices.length : 0
  240. console.log(`[BLE Global] onBluetoothDeviceFound 触发, 设备数=${deviceCount}, s.onDeviceFound=${!!s.onDeviceFound}`)
  241. // 立即在系统回调内转换 advertisData,避免原生 ArrayBuffer 被平台回收
  242. if (res && res.devices) {
  243. res.devices.forEach(device => {
  244. if (device.advertisData && device.advertisData.byteLength > 0) {
  245. const bytes = new Uint8Array(device.advertisData)
  246. device._advertisDataHex = Array.from(bytes).map(b => b.toString(16).padStart(2, '0')).join('')
  247. console.log(`[BLE Scan] 广播数据: ${device._advertisDataHex}`)
  248. } else {
  249. device._advertisDataHex = ''
  250. }
  251. })
  252. }
  253. if (s.onDeviceFound) s.onDeviceFound(res)
  254. })
  255. s.bound = true
  256. logger.info(`[instanceId=${s.instanceId}] BLE系统监听器已全局绑定(含onBluetoothDeviceFound)`)
  257. },
  258. _unbindSystemListeners() {
  259. // 全局监听器不再主动解绑,防止 taskCenter 丢失
  260. // 仅在极端情况下(如蓝牙完全不再使用)才解绑
  261. },
  262. // ============== 确保就绪 ==============
  263. async _ensureReady() {
  264. if (this.bleState === BLE_STATE.IDLE) await this.init()
  265. try {
  266. const res = await _invoke(uni.getBluetoothAdapterState, {})
  267. if (!res.available) {
  268. this.bleAdapterOff = true
  269. this._showBleOffPrompt('请先开启手机蓝牙,才能连接艾灸椅设备')
  270. throw _err(BLE_ERROR.ADAPTER_OFF)
  271. }
  272. this.bleAdapterOff = false
  273. } catch (e) {
  274. if (e && e.code && String(e.code).startsWith('BLE_')) throw e
  275. throw _err(BLE_ERROR.ADAPTER_OFF, e)
  276. }
  277. },
  278. // ============== 扫描 ==============
  279. async startScan(opt = {}) {
  280. const s = _S()
  281. const platform = uni.getSystemInfoSync().platform
  282. console.log(`[BLE Scan] ====== startScan 开始 ====== platform=${platform}, instanceId=${s.instanceId}`)
  283. console.log(`[BLE Scan] 当前状态: bleState=${this.bleState}, searching=${this.searching}, linked=${this.linked}, bound=${s.bound}`)
  284. // 重置中止标记
  285. s.scanAborted = false
  286. this.scanThrottled = false
  287. // 取消上一次残留扫描
  288. if (s.cancelScan) {
  289. console.log('[BLE Scan] 取消上一次残留扫描')
  290. s.cancelScan(); s.cancelScan = null
  291. }
  292. // 停止上一次发现(不使用 await _invoke,因为 iOS 无活跃扫描时不回调会导致卡死)
  293. console.log('[BLE Scan] 调用 stopBluetoothDevicesDiscovery 清除上一次扫描')
  294. try {
  295. uni.stopBluetoothDevicesDiscovery({
  296. success: () => console.log('[BLE Scan] stopDiscovery 成功'),
  297. fail: (e) => console.log('[BLE Scan] stopDiscovery 失败(无害):', JSON.stringify(e)),
  298. complete: () => {}
  299. })
  300. } catch (e) {
  301. console.log('[BLE Scan] stopDiscovery 异常(无害):', e)
  302. }
  303. // 给 iOS 一点时间处理 stop
  304. await new Promise(r => setTimeout(r, 100))
  305. console.log('[BLE Scan] stopDiscovery 处理完毕,继续...')
  306. // iOS 专用修复:关闭并重新打开蓝牙适配器以清除 CoreBluetooth 外设缓存
  307. // iOS 的 CBCentralManager 会缓存已发现的外设,单纯 stop/start 不会清除缓存
  308. // 导致重新扫描时系统不再上报之前已发现的设备
  309. // 只有 close + open adapter 才能让 CoreBluetooth 重置外设缓存
  310. if (platform === 'ios' && !this.linked) {
  311. console.log('[BLE Scan] [iOS] 开始回收适配器以清除 CoreBluetooth 缓存...')
  312. s.intentionalDisconnect = true
  313. s.onDeviceFound = null
  314. try {
  315. await _invoke(uni.closeBluetoothAdapter, {})
  316. console.log('[BLE Scan] [iOS] closeBluetoothAdapter 成功')
  317. } catch (e) {
  318. console.log('[BLE Scan] [iOS] closeBluetoothAdapter 失败(无害):', JSON.stringify(e))
  319. }
  320. this._setState(BLE_STATE.IDLE)
  321. s.intentionalDisconnect = false
  322. // 等待 iOS BLE 栈完全释放资源
  323. await new Promise(r => setTimeout(r, 300))
  324. console.log('[BLE Scan] [iOS] 等待 300ms 后重新打开适配器...')
  325. // 重新打开适配器
  326. try {
  327. await _invoke(uni.openBluetoothAdapter, {})
  328. this.bleAdapterOff = false
  329. this._setState(BLE_STATE.READY)
  330. console.log('[BLE Scan] [iOS] openBluetoothAdapter 成功, state=READY')
  331. } catch (e) {
  332. console.log('[BLE Scan] [iOS] openBluetoothAdapter 失败:', JSON.stringify(e))
  333. const code = e && (e.errCode || e.code)
  334. if (code === 10001) {
  335. this.bleAdapterOff = true
  336. throw _err(BLE_ERROR.ADAPTER_OFF, e)
  337. }
  338. throw _err(BLE_ERROR.NOT_SUPPORT, e)
  339. }
  340. // 再等 200ms 让 adapter 完全就绪
  341. await new Promise(r => setTimeout(r, 200))
  342. console.log('[BLE Scan] [iOS] 适配器回收完成,准备开始扫描')
  343. }
  344. console.log('[BLE Scan] 调用 _ensureReady...')
  345. await this._ensureReady()
  346. console.log('[BLE Scan] _ensureReady 完成, bleState=', this.bleState)
  347. // 如果在 await 期间页面已卸载并调用了 stopScan,直接中止
  348. if (s.scanAborted) {
  349. console.log('[BLE Scan] 扫描已被中止(scanAborted=true),直接返回')
  350. return opt.returnAll ? [] : null
  351. }
  352. const {
  353. namePrefix = s.config.deviceNamePrefix,
  354. deviceName,
  355. services,
  356. timeout = s.config.scanTimeout,
  357. returnAll = false
  358. } = opt
  359. // 清空上次扫描结果
  360. this.scannedDevices = []
  361. console.log(`[BLE Scan] 扫描参数: namePrefix=${namePrefix || '(无)'}, deviceName=${deviceName || '(无)'}, timeout=${timeout}, returnAll=${returnAll}`)
  362. // Android 限流检测(30秒内最多5次,iOS 无此限制)
  363. if (platform === 'android') {
  364. const now = Date.now()
  365. s.scanStartHistory = s.scanStartHistory.filter(t => now - t < 30000)
  366. if (s.scanStartHistory.length >= 4) {
  367. this.scanThrottled = true
  368. logger.warn(`BLE scan throttle: ${s.scanStartHistory.length + 1} starts in 30s, system may ignore`)
  369. }
  370. s.scanStartHistory.push(now)
  371. }
  372. const devices = new Map()
  373. const matched = []
  374. // iOS 上使用 allowDuplicatesKey=true 确保系统持续上报所有设备
  375. // 避免 CoreBluetooth 缓存导致重新扫描时不报告已知设备
  376. const allowDuplicates = (platform === 'ios')
  377. console.log(`[BLE Scan] allowDuplicatesKey=${allowDuplicates} (iOS=${platform === 'ios'})`)
  378. return new Promise(async (resolve, reject) => {
  379. let finished = false
  380. let foundCount = 0
  381. // 保存扫描前的连接状态,扫描结束后恢复,避免覆盖 READY_COMM
  382. const wasConnected = (this.bleState === BLE_STATE.READY_COMM)
  383. const onFound = (res) => {
  384. if (finished) return
  385. for (const d of res.devices) {
  386. const advertisDataHex = d._advertisDataHex || ''
  387. const name = d.name || d.localName || ''
  388. // 重复设备:如果本次带有 advertisData 但之前没有,补充更新
  389. if (devices.has(d.deviceId)) {
  390. if (advertisDataHex) {
  391. const existing = this.scannedDevices.find(item => item.deviceId === d.deviceId)
  392. if (existing && !existing.advertisData) {
  393. existing.advertisData = advertisDataHex
  394. console.log(`[BLE Scan] 补充广播数据: ${name || d.deviceId} -> ${advertisDataHex}`)
  395. }
  396. }
  397. continue
  398. }
  399. devices.set(d.deviceId, d)
  400. foundCount++
  401. console.log(`[BLE Scan] 发现设备 #${foundCount}: name=${name}, deviceId=${d.deviceId}, RSSI=${d.RSSI}`)
  402. const hit =
  403. (deviceName && name === deviceName) ||
  404. (namePrefix && name.startsWith(namePrefix)) ||
  405. (!deviceName && !namePrefix)
  406. if (hit) {
  407. matched.push(d)
  408. const exists = this.scannedDevices.find(item => item.deviceId === d.deviceId)
  409. if (!exists) {
  410. console.log(`[BLE Scan] ✅ 设备匹配并加入列表: ${name || d.deviceId}, 广播数据: ${advertisDataHex}`)
  411. this.scannedDevices.push({
  412. deviceId: d.deviceId,
  413. name: name,
  414. RSSI: d.RSSI || '',
  415. advertisData: advertisDataHex
  416. })
  417. }
  418. if (!returnAll) { finish(null, d); return }
  419. }
  420. }
  421. }
  422. const timer = setTimeout(() => {
  423. console.log(`[BLE Scan] 扫描超时(${timeout}ms),共发现 ${foundCount} 个设备,匹配 ${matched.length} 个`)
  424. if (returnAll) finish(null, matched)
  425. else if (matched.length) finish(null, matched[0])
  426. else finish(_err(BLE_ERROR.SCAN_FAIL, { msg: '扫描超时,未发现目标设备' }))
  427. }, timeout)
  428. const finish = (err, data) => {
  429. if (finished) return
  430. finished = true
  431. console.log(`[BLE Scan] finish 被调用, err=${err ? err.message || err.code : 'null'}, 设备数=${Array.isArray(data) ? data.length : (data ? 1 : 0)}, wasConnected=${wasConnected}`)
  432. s.cancelScan = null
  433. s.onDeviceFound = null
  434. clearTimeout(timer)
  435. try {
  436. uni.stopBluetoothDevicesDiscovery({ success() {}, fail() {}, complete() {} })
  437. } catch (_) {}
  438. // 如果扫描前是连接状态,恢复为 READY_COMM,不要降级为 READY
  439. if (wasConnected) {
  440. this._setState(BLE_STATE.READY_COMM)
  441. } else {
  442. this._setState(BLE_STATE.READY)
  443. }
  444. this.searching = false
  445. err ? reject(err) : resolve(data)
  446. }
  447. s.cancelScan = () => finish(null, returnAll ? matched : (matched[0] || null))
  448. // 通过共享回调分发事件(监听器已在 _bindSystemListeners 中永久注册)
  449. s.onDeviceFound = onFound
  450. // 如果当前已连接,不调用 _setState 避免覆盖 linked 状态
  451. if (!wasConnected) {
  452. this._setState(BLE_STATE.SCANNING)
  453. } else {
  454. this.searching = true
  455. }
  456. console.log(`[BLE Scan] s.onDeviceFound 已设置, s.bound=${s.bound}, wasConnected=${wasConnected}, 准备调用 startBluetoothDevicesDiscovery`)
  457. try {
  458. await _invoke(uni.startBluetoothDevicesDiscovery, {
  459. allowDuplicatesKey: allowDuplicates,
  460. interval: 0,
  461. services
  462. })
  463. console.log('[BLE Scan] ✅ startBluetoothDevicesDiscovery 调用成功,等待设备回调...')
  464. } catch (e) {
  465. console.log('[BLE Scan] ❌ startBluetoothDevicesDiscovery 失败:', JSON.stringify(e))
  466. finish(_err(BLE_ERROR.SCAN_FAIL, e))
  467. }
  468. })
  469. },
  470. /** 停止扫描 */
  471. stopScan() {
  472. const s = _S()
  473. s.scanAborted = true
  474. s.onDeviceFound = null
  475. if (s.cancelScan) {
  476. s.cancelScan()
  477. s.cancelScan = null
  478. } else {
  479. try {
  480. uni.stopBluetoothDevicesDiscovery({ success() {}, fail() {} })
  481. } catch (e) {}
  482. }
  483. this.searching = false
  484. this.scanThrottled = false
  485. if (this.bleState === BLE_STATE.SCANNING) {
  486. // _setState(READY) 内部会检测 _connectedBeforeScan,
  487. // 若扫描前有连接则自动恢复为 READY_COMM
  488. this._setState(BLE_STATE.READY)
  489. }
  490. },
  491. // ============== 连接 ==============
  492. async connectDevice(deviceId) {
  493. const s = _S()
  494. console.log(`[BLE Store] connectDevice() called, instanceId = ${s.instanceId}`)
  495. if (!deviceId) throw _err(BLE_ERROR.CONNECT_FAIL, { msg: 'deviceId 不能为空' })
  496. await this._ensureReady()
  497. if (this.bleState === BLE_STATE.CONNECTING) throw _err(BLE_ERROR.BUSY)
  498. this._setState(BLE_STATE.CONNECTING)
  499. this.device = { deviceId, name: '' }
  500. console.log("连接蓝牙时的设备id",this.device)
  501. try {
  502. await _invoke(uni.createBLEConnection, {
  503. deviceId,
  504. timeout: s.config.connectTimeout
  505. })
  506. this._setState(BLE_STATE.CONNECTED)
  507. // Android 提升 MTU
  508. // #ifdef APP-PLUS
  509. if (uni.getSystemInfoSync().platform === 'android' && uni.setBLEMTU) {
  510. try { await _invoke(uni.setBLEMTU, { deviceId, mtu: 185 }) } catch (_) {}
  511. }
  512. // #endif
  513. await this._discoverAndSubscribe(deviceId)
  514. this._setState(BLE_STATE.READY_COMM)
  515. s.reconnectCount = 0
  516. } catch (e) {
  517. this._setState(BLE_STATE.DISCONNECTED)
  518. this.device = null // 连接失败,清空 device 防止延迟回调误触发重连
  519. try { await _invoke(uni.closeBLEConnection, { deviceId }) } catch (_) {}
  520. const code = e && (e.errCode || e.code)
  521. if (code === 10003 || code === -1) {
  522. throw _err(BLE_ERROR.CONNECT_TIMEOUT, e)
  523. }
  524. throw _err(BLE_ERROR.CONNECT_FAIL, e)
  525. }
  526. },
  527. /** 扫描 + 连接一步到位(支持 deviceId 直连优先,跳过扫描) */
  528. async scanAndConnect(opt = {}) {
  529. const { deviceId: directId, deviceName, advertisData: passedAdvertisData, ...restOpt } = opt
  530. console.log("连接opt",opt,directId,passedAdvertisData,restOpt)
  531. // 策略:如果已有 deviceId,先尝试直连(不扫描),失败后回退扫描
  532. if (directId) {
  533. try {
  534. logger.info(`directConnect attempt, deviceId=${directId}`)
  535. await this.connectDevice(directId)
  536. this.device.name = deviceName || this.device.name || ''
  537. // 存储 advertisData 作为跨平台设备标识
  538. if (passedAdvertisData) {
  539. console.log("连接passedAdvertisData",passedAdvertisData)
  540. this.device.advertisData = passedAdvertisData
  541. }
  542. logger.info('directConnect success, scan skipped')
  543. return this.device
  544. } catch (e) {
  545. logger.warn('directConnect failed, fallback to scan', e.message || e.code)
  546. // connectDevice 失败时已清空 this.device 并关闭连接,无需额外处理
  547. }
  548. }
  549. // 回退:扫描 + 连接
  550. const scanOpt = { ...restOpt }
  551. if (deviceName) scanOpt.deviceName = deviceName
  552. const device = await this.startScan(scanOpt)
  553. await this.connectDevice(device.deviceId)
  554. this.device.name = device.name || device.localName || ''
  555. console.log("连接device._advertisDataHex",device._advertisDataHex)
  556. // 存储 advertisData(hex 字符串):优先用传入的(后台 deviceCode),其次用扫描结果的 hex
  557. // 注意:device.advertisData 是原始 ArrayBuffer,不能直接存储,需使用 _advertisDataHex
  558. this.device.advertisData = passedAdvertisData || device.advertisData || ''
  559. return this.device
  560. },
  561. /** 主动断开 */
  562. async disconnect() {
  563. const s = _S()
  564. s.intentionalDisconnect = true
  565. this._clearReconnect()
  566. if (!this.device) {
  567. s.intentionalDisconnect = false
  568. return
  569. }
  570. const { deviceId } = this.device
  571. // 先置空 device,防止 onBLEConnectionStateChange 回调误匹配
  572. this.device = null
  573. this._setState(BLE_STATE.DISCONNECTED)
  574. try { await _invoke(uni.closeBLEConnection, { deviceId }) } catch (_) {}
  575. s.intentionalDisconnect = false
  576. },
  577. /** 发现服务并订阅通知 */
  578. async _discoverAndSubscribe(deviceId) {
  579. const s = _S()
  580. const svcRes = await _invoke(uni.getBLEDeviceServices, { deviceId })
  581. const services = svcRes.services || []
  582. const targetSvc = services.find(sv => _uuidEq(sv.uuid, s.config.serviceId))
  583. || services.find(sv => sv.isPrimary)
  584. || services[0]
  585. if (!targetSvc) throw _err(BLE_ERROR.SERVICE_NOT_FOUND)
  586. s.serviceId = targetSvc.uuid
  587. const charRes = await _invoke(uni.getBLEDeviceCharacteristics, {
  588. deviceId, serviceId: s.serviceId
  589. })
  590. const chars = charRes.characteristics || []
  591. const writeChar = chars.find(c => _uuidEq(c.uuid, s.config.writeCharId))
  592. || chars.find(c => c.properties && (c.properties.write || c.properties.writeNoResponse || c.properties.writeDefault))
  593. const notifyChar = chars.find(c => _uuidEq(c.uuid, s.config.notifyCharId))
  594. || chars.find(c => c.properties && (c.properties.notify || c.properties.indicate))
  595. if (!writeChar) throw _err(BLE_ERROR.CHAR_NOT_FOUND, { msg: '未找到写特征' })
  596. if (!notifyChar) throw _err(BLE_ERROR.CHAR_NOT_FOUND, { msg: '未找到通知特征' })
  597. s.writeCharId = writeChar.uuid
  598. s.notifyCharId = notifyChar.uuid
  599. await _invoke(uni.notifyBLECharacteristicValueChange, {
  600. deviceId,
  601. serviceId: s.serviceId,
  602. characteristicId: s.notifyCharId,
  603. state: true
  604. })
  605. },
  606. // ============== 断连处理 & 自动重连 ==============
  607. _handleDisconnected(reason) {
  608. const s = _S()
  609. // 主动断开/重置时不触发重连
  610. if (s.intentionalDisconnect) return
  611. if (this.bleState === BLE_STATE.DISCONNECTED || this.bleState === BLE_STATE.IDLE) return
  612. const device = this.device
  613. this._setState(BLE_STATE.DISCONNECTED)
  614. if (s.parser) s.parser.reset()
  615. this._attemptReconnect(device, reason)
  616. },
  617. _attemptReconnect(device, reason) {
  618. const s = _S()
  619. if (!s.config.autoReconnect || !device || s.reconnectCount >= s.config.maxReconnect) {
  620. if (s.reconnectCount >= s.config.maxReconnect) {
  621. logger.warn('reconnect max reached, waiting for adapter restore')
  622. s.reconnectCount = 0
  623. this.reconnectDrawer = false
  624. this.reconnectCount = 0
  625. }
  626. return
  627. }
  628. s.reconnectCount++
  629. this.reconnectCount = s.reconnectCount
  630. this.reconnectDrawer = true
  631. const delay = Math.min(1000 * s.reconnectCount, 5000)
  632. logger.warn(`reconnect in ${delay}ms (${s.reconnectCount}/${s.config.maxReconnect})`)
  633. const gen = s.reconnectGeneration
  634. s.reconnectTimer = setTimeout(async () => {
  635. if (s.reconnectGeneration !== gen) {
  636. logger.info('reconnect callback aborted (generation mismatch)')
  637. return
  638. }
  639. try {
  640. // 先关闭适配器清除脏状态(加标志防止回调干扰)
  641. s.intentionalDisconnect = true
  642. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  643. s.intentionalDisconnect = false
  644. this._setState(BLE_STATE.IDLE)
  645. if (s.reconnectGeneration !== gen) return
  646. // 优先使用 deviceId 直连,避免不必要的扫描触发 Android 限流
  647. const scanOpt = { timeout: 8000 }
  648. if (device.deviceId) scanOpt.deviceId = device.deviceId
  649. if (device.name) scanOpt.deviceName = device.name
  650. await this.scanAndConnect(scanOpt)
  651. if (s.reconnectGeneration !== gen) return
  652. this.reconnectDrawer = false
  653. this.reconnectCount = 0
  654. logger.info('reconnect success')
  655. } catch (e) {
  656. if (s.reconnectGeneration !== gen) return
  657. logger.error('reconnect fail', e)
  658. this._attemptReconnect(device, reason)
  659. }
  660. }, delay)
  661. },
  662. _clearReconnect() {
  663. const s = _S()
  664. if (s.reconnectTimer) { clearTimeout(s.reconnectTimer); s.reconnectTimer = null }
  665. s.reconnectCount = 0
  666. s.reconnectGeneration++ // 递增代数,使正在执行的僵尸回调自动失效
  667. this.reconnectCount = 0
  668. this.reconnectDrawer = false
  669. },
  670. /**
  671. * 蓝牙适配器从关闭恢复为开启时调用
  672. * 如果之前有连接过的设备且当前处于断连状态,自动扫描并重新连接
  673. */
  674. _onAdapterRestored() {
  675. const device = this.device
  676. if (!device || !device.deviceId) return
  677. if (this.bleState !== BLE_STATE.DISCONNECTED && this.bleState !== BLE_STATE.IDLE) return
  678. logger.info('adapter restored, auto reconnecting to', device.name || device.deviceId)
  679. // 重置重连计数,发起新一轮重连
  680. this._clearReconnect()
  681. this._setState(BLE_STATE.IDLE)
  682. // 延迟 1.5s 等待适配器完全就绪(Android 蓝牙状态延迟)
  683. const s = _S()
  684. const gen = s.reconnectGeneration
  685. this.reconnectDrawer = true
  686. this.reconnectCount = 1
  687. s.reconnectTimer = setTimeout(async () => {
  688. if (s.reconnectGeneration !== gen) return
  689. try {
  690. // 关闭旧适配器,确保重新打开时状态干净
  691. s.intentionalDisconnect = true
  692. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  693. s.intentionalDisconnect = false
  694. if (s.reconnectGeneration !== gen) return
  695. // 优先直连,避免扫描触发限流
  696. const scanOpt = { timeout: 8000 }
  697. if (device.deviceId) scanOpt.deviceId = device.deviceId
  698. if (device.name) scanOpt.deviceName = device.name
  699. await this.scanAndConnect(scanOpt)
  700. if (s.reconnectGeneration !== gen) return
  701. this.reconnectDrawer = false
  702. this.reconnectCount = 0
  703. logger.info('adapter restore reconnect success')
  704. } catch (e) {
  705. if (s.reconnectGeneration !== gen) return
  706. logger.error('adapter restore reconnect fail', e)
  707. // 失败后进入常规重连流程(还有2次机会)
  708. s.reconnectCount = 1
  709. this._attemptReconnect(device, BLE_ERROR.ADAPTER_OFF)
  710. }
  711. }, 1500)
  712. },
  713. // ============== 收包处理 ==============
  714. _onFrame(decoded, frame) {
  715. console.log("获取到消息",decoded)
  716. logger.info('frame received', decoded.funcCode)
  717. if (decoded.parsed) {
  718. if (decoded.parsed.type === 'GROUP_1') {
  719. this._handleGroup1(decoded.parsed)
  720. } else if (decoded.parsed.type === 'GROUP_2') {
  721. this._handleGroup2(decoded.parsed)
  722. }
  723. }
  724. },
  725. /** 解析参数组1 */
  726. _handleGroup1(data) {
  727. // 设备运行状态
  728. switch (data.runtimeState) {
  729. case 0x00: this.deviceStatus = 0; break
  730. case 0x01:
  731. case 0x02: this.deviceStatus = 1; break
  732. case 0x03: this.deviceStatus = 3; break
  733. case 0x04: this.deviceStatus = 4; break
  734. case 0x05: this.deviceStatus = 5; break
  735. }
  736. // 模式
  737. switch (data.mode) {
  738. case MODE.LEISURE: this.modeType = 0; break
  739. case MODE.PROFESSIONAL: this.modeType = 1; break
  740. case MODE.PERSONAL: this.modeType = 2; break
  741. case MODE.EXPERT: this.modeType = 3; break
  742. }
  743. // 剩余时间
  744. const m = data.remainMinute || 0
  745. const s = data.remainSecond || 0
  746. const h = Math.floor(m / 60)
  747. const m1 = m % 60
  748. this.subTime = `${h.toString().padStart(2, '0')}:${m1.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  749. // 异常检测
  750. if (data.foreignDetect === 0x02) {
  751. this.excepDrawer = true
  752. this.exceTxt = 1
  753. }
  754. // 耗材状态
  755. this.otherSetting.aijiuNum = String(data.consumable || 0)
  756. this.otherSetting.lvxinNum = String(data.filterPercent || 0)
  757. this.otherSetting.huishouNum = String(data.recycleBinPct || 0)
  758. },
  759. /** 解析参数组2 */
  760. _handleGroup2(data) {
  761. if (data.preheatPercent < 100) {
  762. this.ispreHot = false
  763. this.hotPercentage = data.preheatPercent + '%'
  764. } else {
  765. this.ispreHot = true
  766. this.hotPercentage = data.ignitePercent + '%'
  767. }
  768. // 椅子角度
  769. if (data.chairAngle) {
  770. const angleMap = {
  771. 1: 90, 2: 105, 3: 120, 4: 135, 5: 150
  772. }
  773. if (angleMap[data.chairAngle]) {
  774. this.chairAngle = angleMap[data.chairAngle]
  775. }
  776. }
  777. },
  778. // ============== 发送指令 ==============
  779. async writeRaw(u8) {
  780. if (!this.linked) throw _err(BLE_ERROR.DISCONNECTED)
  781. const s = _S()
  782. const payload = bufferToArrayBuffer(u8)
  783. s.writeLock = s.writeLock.then(async () => {
  784. logger.log('=>', bytesToHex(u8))
  785. logger.log('write params:', {
  786. deviceId: this.device.deviceId,
  787. serviceId: s.serviceId,
  788. characteristicId: s.writeCharId,
  789. valueByteLength: payload.byteLength
  790. })
  791. try {
  792. await _invoke(uni.writeBLECharacteristicValue, {
  793. deviceId: this.device.deviceId,
  794. serviceId: s.serviceId,
  795. characteristicId: s.writeCharId,
  796. value: payload
  797. })
  798. } catch (e) {
  799. logger.error('writeBLE origin error:', JSON.stringify(e))
  800. throw _err(BLE_ERROR.WRITE_FAIL, e)
  801. }
  802. })
  803. return s.writeLock
  804. },
  805. /** 下发基本功能指令 (0x01) */
  806. sendBasic(opt) { return this.writeRaw(encodeBasic(opt)) },
  807. /** 下发模式参数 1 (步骤 1-7) */
  808. sendModeParam1(opt) { return this.writeRaw(encodeModeParam1(opt)) },
  809. /** 下发模式参数 2 (步骤 8-14) */
  810. sendModeParam2(opt) { return this.writeRaw(encodeModeParam2(opt)) },
  811. /** 下发穴位坐标 */
  812. async sendAcupoints(points = []) {
  813. for (let i = 0; i < points.length; i += 2) {
  814. const pair = points.slice(i, i + 2)
  815. await this.writeRaw(encodeAcupoints(pair))
  816. }
  817. },
  818. // ---- 常用快捷方法 ----
  819. powerOn() { return this.sendBasic({ power: POWER.ON }) },
  820. powerOff() { return this.sendBasic({ power: POWER.OFF }) },
  821. startMoxi(opt = {}) { return this.sendBasic({ power: POWER.ON, moxiState: MOXI_STATE.START, ...opt }) },
  822. pauseMoxi() { return this.sendBasic({ moxiState: MOXI_STATE.PAUSE }) },
  823. stopMoxi() { return this.sendBasic({ moxiState: MOXI_STATE.DONE }) },
  824. setMute(on) { return this.sendBasic({ mute: on ? MUTE.ON : MUTE.OFF }) },
  825. setTemperature(v) { return this.sendBasic({ temperature: v }) },
  826. setChairAngle(v) { return this.sendBasic({ angle: v }) },
  827. // ============== 蓝牙关闭提示 ==============
  828. /**
  829. * 弹窗提示用户蓝牙未开启,引导用户前往设置开启
  830. * 内部做防抖,避免短时间内重复弹窗
  831. */
  832. _showBleOffPrompt(message) {
  833. const s = _S()
  834. // 弹窗正在显示中,不重复弹出
  835. if (s._bleOffPromptShowing) return
  836. s._bleOffPromptShowing = true
  837. uni.showModal({
  838. title: '蓝牙未开启',
  839. content: message || '请开启手机蓝牙后重试',
  840. confirmText: '去设置',
  841. cancelText: '取消',
  842. success: (res) => {
  843. s._bleOffPromptShowing = false
  844. if (res.confirm) {
  845. // #ifdef APP-PLUS
  846. const platform = uni.getSystemInfoSync().platform
  847. if (platform === 'android') {
  848. try {
  849. const main = plus.android.runtimeMainActivity()
  850. const Intent = plus.android.importClass('android.content.Intent')
  851. const Settings = plus.android.importClass('android.provider.Settings')
  852. const intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
  853. main.startActivity(intent)
  854. } catch (e) {
  855. logger.error('跳转蓝牙设置失败', e)
  856. }
  857. } else if (platform === 'ios') {
  858. // iOS 可以打开 App 设置页
  859. plus.runtime.openURL('App-Prefs:root=Bluetooth')
  860. }
  861. // #endif
  862. }
  863. }
  864. })
  865. }
  866. }
  867. })