ble.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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. // advertisData为空的设备跳过,无法区分同名设备
  403. if (!advertisDataHex) {
  404. console.log(`[BLE Scan] 跳过无广播数据的设备: ${name || d.deviceId}`)
  405. continue
  406. }
  407. const hit =
  408. (deviceName && name === deviceName) ||
  409. (namePrefix && name.startsWith(namePrefix)) ||
  410. (!deviceName && !namePrefix)
  411. if (hit) {
  412. matched.push(d)
  413. const exists = this.scannedDevices.find(item => item.deviceId === d.deviceId)
  414. if (!exists) {
  415. console.log(`[BLE Scan] ✅ 设备匹配并加入列表: ${name || d.deviceId}, 广播数据: ${advertisDataHex}`)
  416. this.scannedDevices.push({
  417. deviceId: d.deviceId,
  418. name: name,
  419. RSSI: d.RSSI || '',
  420. advertisData: advertisDataHex
  421. })
  422. }
  423. if (!returnAll) { finish(null, d); return }
  424. }
  425. }
  426. }
  427. const timer = setTimeout(() => {
  428. console.log(`[BLE Scan] 扫描超时(${timeout}ms),共发现 ${foundCount} 个设备,匹配 ${matched.length} 个`)
  429. if (returnAll) finish(null, matched)
  430. else if (matched.length) finish(null, matched[0])
  431. else finish(_err(BLE_ERROR.SCAN_FAIL, { msg: '扫描超时,未发现目标设备' }))
  432. }, timeout)
  433. const finish = (err, data) => {
  434. if (finished) return
  435. finished = true
  436. console.log(`[BLE Scan] finish 被调用, err=${err ? err.message || err.code : 'null'}, 设备数=${Array.isArray(data) ? data.length : (data ? 1 : 0)}, wasConnected=${wasConnected}`)
  437. s.cancelScan = null
  438. s.onDeviceFound = null
  439. clearTimeout(timer)
  440. try {
  441. uni.stopBluetoothDevicesDiscovery({ success() {}, fail() {}, complete() {} })
  442. } catch (_) {}
  443. // 如果扫描前是连接状态,恢复为 READY_COMM,不要降级为 READY
  444. if (wasConnected) {
  445. this._setState(BLE_STATE.READY_COMM)
  446. } else {
  447. this._setState(BLE_STATE.READY)
  448. }
  449. this.searching = false
  450. err ? reject(err) : resolve(data)
  451. }
  452. s.cancelScan = () => finish(null, returnAll ? matched : (matched[0] || null))
  453. // 通过共享回调分发事件(监听器已在 _bindSystemListeners 中永久注册)
  454. s.onDeviceFound = onFound
  455. // 如果当前已连接,不调用 _setState 避免覆盖 linked 状态
  456. if (!wasConnected) {
  457. this._setState(BLE_STATE.SCANNING)
  458. } else {
  459. this.searching = true
  460. }
  461. console.log(`[BLE Scan] s.onDeviceFound 已设置, s.bound=${s.bound}, wasConnected=${wasConnected}, 准备调用 startBluetoothDevicesDiscovery`)
  462. try {
  463. await _invoke(uni.startBluetoothDevicesDiscovery, {
  464. allowDuplicatesKey: allowDuplicates,
  465. interval: 0,
  466. services
  467. })
  468. console.log('[BLE Scan] ✅ startBluetoothDevicesDiscovery 调用成功,等待设备回调...')
  469. } catch (e) {
  470. console.log('[BLE Scan] ❌ startBluetoothDevicesDiscovery 失败:', JSON.stringify(e))
  471. finish(_err(BLE_ERROR.SCAN_FAIL, e))
  472. }
  473. })
  474. },
  475. /** 停止扫描 */
  476. stopScan() {
  477. const s = _S()
  478. s.scanAborted = true
  479. s.onDeviceFound = null
  480. if (s.cancelScan) {
  481. s.cancelScan()
  482. s.cancelScan = null
  483. } else {
  484. try {
  485. uni.stopBluetoothDevicesDiscovery({ success() {}, fail() {} })
  486. } catch (e) {}
  487. }
  488. this.searching = false
  489. this.scanThrottled = false
  490. if (this.bleState === BLE_STATE.SCANNING) {
  491. // _setState(READY) 内部会检测 _connectedBeforeScan,
  492. // 若扫描前有连接则自动恢复为 READY_COMM
  493. this._setState(BLE_STATE.READY)
  494. }
  495. },
  496. // ============== 连接 ==============
  497. async connectDevice(deviceId) {
  498. const s = _S()
  499. console.log(`[BLE Store] connectDevice() called, instanceId = ${s.instanceId}`)
  500. if (!deviceId) throw _err(BLE_ERROR.CONNECT_FAIL, { msg: 'deviceId 不能为空' })
  501. await this._ensureReady()
  502. if (this.bleState === BLE_STATE.CONNECTING) throw _err(BLE_ERROR.BUSY)
  503. this._setState(BLE_STATE.CONNECTING)
  504. this.device = { deviceId, name: '' }
  505. console.log("连接蓝牙时的设备id",this.device)
  506. try {
  507. await _invoke(uni.createBLEConnection, {
  508. deviceId,
  509. timeout: s.config.connectTimeout
  510. })
  511. this._setState(BLE_STATE.CONNECTED)
  512. // Android 提升 MTU
  513. // #ifdef APP-PLUS
  514. if (uni.getSystemInfoSync().platform === 'android' && uni.setBLEMTU) {
  515. try { await _invoke(uni.setBLEMTU, { deviceId, mtu: 185 }) } catch (_) {}
  516. }
  517. // #endif
  518. await this._discoverAndSubscribe(deviceId)
  519. this._setState(BLE_STATE.READY_COMM)
  520. s.reconnectCount = 0
  521. } catch (e) {
  522. console.log("蓝牙连接失败",e)
  523. this._setState(BLE_STATE.DISCONNECTED)
  524. this.device = null // 连接失败,清空 device 防止延迟回调误触发重连
  525. try { await _invoke(uni.closeBLEConnection, { deviceId }) } catch (_) {}
  526. const code = e && (e.errCode || e.code)
  527. if (code === 10003 || code === -1) {
  528. throw _err(BLE_ERROR.CONNECT_TIMEOUT, e)
  529. }
  530. throw _err(BLE_ERROR.CONNECT_FAIL, e)
  531. }
  532. },
  533. /** 扫描 + 连接一步到位(支持 deviceId 直连优先,跳过扫描) */
  534. async scanAndConnect(opt = {}) {
  535. const { deviceId: directId, deviceName, advertisData: passedAdvertisData, ...restOpt } = opt
  536. console.log("连接opt",opt,directId,passedAdvertisData,restOpt,{ ...restOpt })
  537. // 策略:如果已有 deviceId,先尝试直连(不扫描),失败后回退扫描
  538. if (directId) {
  539. try {
  540. logger.info(`directConnect attempt, deviceId=${directId}`)
  541. await this.connectDevice(directId)
  542. this.device.name = deviceName || this.device.name || ''
  543. // 存储 advertisData 作为跨平台设备标识
  544. if (passedAdvertisData) {
  545. console.log("连接passedAdvertisData",passedAdvertisData)
  546. this.device.advertisData = passedAdvertisData
  547. }
  548. logger.info('directConnect success, scan skipped')
  549. return this.device
  550. } catch (e) {
  551. logger.warn('directConnect failed, fallback to scan', e.message || e.code)
  552. // connectDevice 失败时已清空 this.device 并关闭连接,无需额外处理
  553. }
  554. }
  555. // 回退:扫描 + 连接
  556. const scanOpt = { ...restOpt }
  557. let device = null
  558. if (passedAdvertisData) {
  559. // 有 advertisData 时:不传 deviceName 做名称过滤(后端名与蓝牙广播名可能不一致)
  560. // 扫描所有设备,再通过 advertisData 精确定位目标
  561. scanOpt.returnAll = true
  562. const devices = await this.startScan(scanOpt)
  563. console.log(`[BLE scanAndConnect] 扫描到 ${devices.length} 个设备,目标 advertisData=${passedAdvertisData}`)
  564. // 精确匹配 advertisData
  565. device = devices.find(d => {
  566. const hex = d._advertisDataHex || d.advertisData || ''
  567. return hex === passedAdvertisData
  568. })
  569. if (!device) {
  570. throw _err(BLE_ERROR.SCAN_FAIL, { msg: '未找到目标设备(advertisData不匹配)' })
  571. }
  572. console.log(`[BLE scanAndConnect] ✅ 通过advertisData匹配到设备: name=${device.name || device.localName}, deviceId=${device.deviceId}`)
  573. } else {
  574. // 无 advertisData 时按设备名过滤,返回第一个匹配设备
  575. if (deviceName) scanOpt.deviceName = deviceName
  576. device = await this.startScan(scanOpt)
  577. }
  578. await this.connectDevice(device.deviceId)
  579. this.device.name = device.name || device.localName || ''
  580. console.log("连接device._advertisDataHex",device._advertisDataHex)
  581. // 存储 advertisData(hex 字符串):优先用传入的(后台 deviceCode),其次用扫描结果的 hex
  582. // 注意:device.advertisData 是原始 ArrayBuffer,不能直接存储,需使用 _advertisDataHex
  583. this.device.advertisData = passedAdvertisData || device._advertisDataHex || device.advertisData || ''
  584. return this.device
  585. },
  586. /** 主动断开 */
  587. async disconnect() {
  588. const s = _S()
  589. s.intentionalDisconnect = true
  590. this._clearReconnect()
  591. if (!this.device) {
  592. s.intentionalDisconnect = false
  593. return
  594. }
  595. const { deviceId } = this.device
  596. // 先置空 device,防止 onBLEConnectionStateChange 回调误匹配
  597. this.device = null
  598. this._setState(BLE_STATE.DISCONNECTED)
  599. try { await _invoke(uni.closeBLEConnection, { deviceId }) } catch (_) {}
  600. s.intentionalDisconnect = false
  601. },
  602. /** 发现服务并订阅通知 */
  603. async _discoverAndSubscribe(deviceId) {
  604. const s = _S()
  605. const svcRes = await _invoke(uni.getBLEDeviceServices, { deviceId })
  606. const services = svcRes.services || []
  607. const strict = s.config.strictUUID
  608. const targetSvc = (strict && services.find(sv => _uuidEq(sv.uuid, s.config.serviceId)))
  609. || services.find(sv => sv.isPrimary)
  610. || services[0]
  611. if (!targetSvc) throw _err(BLE_ERROR.SERVICE_NOT_FOUND)
  612. s.serviceId = targetSvc.uuid
  613. const charRes = await _invoke(uni.getBLEDeviceCharacteristics, {
  614. deviceId, serviceId: s.serviceId
  615. })
  616. const chars = charRes.characteristics || []
  617. const writeChar = (strict && chars.find(c => _uuidEq(c.uuid, s.config.writeCharId)))
  618. || chars.find(c => c.properties && (c.properties.write || c.properties.writeNoResponse || c.properties.writeDefault))
  619. const notifyChar = (strict && chars.find(c => _uuidEq(c.uuid, s.config.notifyCharId)))
  620. || chars.find(c => c.properties && (c.properties.notify || c.properties.indicate))
  621. if (!writeChar) throw _err(BLE_ERROR.CHAR_NOT_FOUND, { msg: '未找到写特征' })
  622. if (!notifyChar) throw _err(BLE_ERROR.CHAR_NOT_FOUND, { msg: '未找到通知特征' })
  623. s.writeCharId = writeChar.uuid
  624. s.notifyCharId = notifyChar.uuid
  625. await _invoke(uni.notifyBLECharacteristicValueChange, {
  626. deviceId,
  627. serviceId: s.serviceId,
  628. characteristicId: s.notifyCharId,
  629. state: true
  630. })
  631. },
  632. // ============== 断连处理 & 自动重连 ==============
  633. _handleDisconnected(reason) {
  634. const s = _S()
  635. // 主动断开/重置时不触发重连
  636. if (s.intentionalDisconnect) return
  637. if (this.bleState === BLE_STATE.DISCONNECTED || this.bleState === BLE_STATE.IDLE) return
  638. const device = this.device
  639. this._setState(BLE_STATE.DISCONNECTED)
  640. if (s.parser) s.parser.reset()
  641. this._attemptReconnect(device, reason)
  642. },
  643. _attemptReconnect(device, reason) {
  644. const s = _S()
  645. if (!s.config.autoReconnect || !device || s.reconnectCount >= s.config.maxReconnect) {
  646. if (s.reconnectCount >= s.config.maxReconnect) {
  647. logger.warn('reconnect max reached, waiting for adapter restore')
  648. s.reconnectCount = 0
  649. this.reconnectDrawer = false
  650. this.reconnectCount = 0
  651. }
  652. return
  653. }
  654. s.reconnectCount++
  655. this.reconnectCount = s.reconnectCount
  656. this.reconnectDrawer = true
  657. const delay = Math.min(1000 * s.reconnectCount, 5000)
  658. logger.warn(`reconnect in ${delay}ms (${s.reconnectCount}/${s.config.maxReconnect})`)
  659. const gen = s.reconnectGeneration
  660. s.reconnectTimer = setTimeout(async () => {
  661. if (s.reconnectGeneration !== gen) {
  662. logger.info('reconnect callback aborted (generation mismatch)')
  663. return
  664. }
  665. try {
  666. // 先关闭适配器清除脏状态(加标志防止回调干扰)
  667. s.intentionalDisconnect = true
  668. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  669. s.intentionalDisconnect = false
  670. this._setState(BLE_STATE.IDLE)
  671. if (s.reconnectGeneration !== gen) return
  672. // 优先使用 deviceId 直连,避免不必要的扫描触发 Android 限流
  673. const scanOpt = { timeout: 8000 }
  674. if (device.deviceId) scanOpt.deviceId = device.deviceId
  675. if (device.name) scanOpt.deviceName = device.name
  676. await this.scanAndConnect(scanOpt)
  677. if (s.reconnectGeneration !== gen) return
  678. this.reconnectDrawer = false
  679. this.reconnectCount = 0
  680. logger.info('reconnect success')
  681. } catch (e) {
  682. if (s.reconnectGeneration !== gen) return
  683. logger.error('reconnect fail', e)
  684. this._attemptReconnect(device, reason)
  685. }
  686. }, delay)
  687. },
  688. _clearReconnect() {
  689. const s = _S()
  690. if (s.reconnectTimer) { clearTimeout(s.reconnectTimer); s.reconnectTimer = null }
  691. s.reconnectCount = 0
  692. s.reconnectGeneration++ // 递增代数,使正在执行的僵尸回调自动失效
  693. this.reconnectCount = 0
  694. this.reconnectDrawer = false
  695. },
  696. /**
  697. * 蓝牙适配器从关闭恢复为开启时调用
  698. * 如果之前有连接过的设备且当前处于断连状态,自动扫描并重新连接
  699. */
  700. _onAdapterRestored() {
  701. const device = this.device
  702. if (!device || !device.deviceId) return
  703. if (this.bleState !== BLE_STATE.DISCONNECTED && this.bleState !== BLE_STATE.IDLE) return
  704. logger.info('adapter restored, auto reconnecting to', device.name || device.deviceId)
  705. // 重置重连计数,发起新一轮重连
  706. this._clearReconnect()
  707. this._setState(BLE_STATE.IDLE)
  708. // 延迟 1.5s 等待适配器完全就绪(Android 蓝牙状态延迟)
  709. const s = _S()
  710. const gen = s.reconnectGeneration
  711. this.reconnectDrawer = true
  712. this.reconnectCount = 1
  713. s.reconnectTimer = setTimeout(async () => {
  714. if (s.reconnectGeneration !== gen) return
  715. try {
  716. // 关闭旧适配器,确保重新打开时状态干净
  717. s.intentionalDisconnect = true
  718. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  719. s.intentionalDisconnect = false
  720. if (s.reconnectGeneration !== gen) return
  721. // 优先直连,避免扫描触发限流
  722. const scanOpt = { timeout: 8000 }
  723. if (device.deviceId) scanOpt.deviceId = device.deviceId
  724. if (device.name) scanOpt.deviceName = device.name
  725. await this.scanAndConnect(scanOpt)
  726. if (s.reconnectGeneration !== gen) return
  727. this.reconnectDrawer = false
  728. this.reconnectCount = 0
  729. logger.info('adapter restore reconnect success')
  730. } catch (e) {
  731. if (s.reconnectGeneration !== gen) return
  732. logger.error('adapter restore reconnect fail', e)
  733. // 失败后进入常规重连流程(还有2次机会)
  734. s.reconnectCount = 1
  735. this._attemptReconnect(device, BLE_ERROR.ADAPTER_OFF)
  736. }
  737. }, 1500)
  738. },
  739. // ============== 收包处理 ==============
  740. _onFrame(decoded, frame) {
  741. console.log("获取到消息",decoded)
  742. logger.info('frame received', decoded.funcCode)
  743. if (decoded.parsed) {
  744. if (decoded.parsed.type === 'GROUP_1') {
  745. this._handleGroup1(decoded.parsed)
  746. } else if (decoded.parsed.type === 'GROUP_2') {
  747. this._handleGroup2(decoded.parsed)
  748. }
  749. }
  750. },
  751. /** 解析参数组1 */
  752. _handleGroup1(data) {
  753. // 设备运行状态
  754. switch (data.runtimeState) {
  755. case 0x00: this.deviceStatus = 0; break
  756. case 0x01:
  757. case 0x02: this.deviceStatus = 1; break
  758. case 0x03: this.deviceStatus = 3; break
  759. case 0x04: this.deviceStatus = 4; break
  760. case 0x05: this.deviceStatus = 5; break
  761. }
  762. // 模式
  763. switch (data.mode) {
  764. case MODE.LEISURE: this.modeType = 0; break
  765. case MODE.PROFESSIONAL: this.modeType = 1; break
  766. case MODE.PERSONAL: this.modeType = 2; break
  767. case MODE.EXPERT: this.modeType = 3; break
  768. }
  769. // 剩余时间
  770. const m = data.remainMinute || 0
  771. const s = data.remainSecond || 0
  772. const h = Math.floor(m / 60)
  773. const m1 = m % 60
  774. this.subTime = `${h.toString().padStart(2, '0')}:${m1.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  775. // 异常检测
  776. if (data.foreignDetect === 0x02) {
  777. this.excepDrawer = true
  778. this.exceTxt = 1
  779. }
  780. // 耗材状态
  781. this.otherSetting.aijiuNum = String(data.consumable || 0)
  782. this.otherSetting.lvxinNum = String(data.filterPercent || 0)
  783. this.otherSetting.huishouNum = String(data.recycleBinPct || 0)
  784. },
  785. /** 解析参数组2 */
  786. _handleGroup2(data) {
  787. if (data.preheatPercent < 100) {
  788. this.ispreHot = false
  789. this.hotPercentage = data.preheatPercent + '%'
  790. } else {
  791. this.ispreHot = true
  792. this.hotPercentage = data.ignitePercent + '%'
  793. }
  794. // 椅子角度
  795. if (data.chairAngle) {
  796. const angleMap = {
  797. 1: 90, 2: 105, 3: 120, 4: 135, 5: 150
  798. }
  799. if (angleMap[data.chairAngle]) {
  800. this.chairAngle = angleMap[data.chairAngle]
  801. }
  802. }
  803. },
  804. // ============== 发送指令 ==============
  805. async writeRaw(u8) {
  806. if (!this.linked) throw _err(BLE_ERROR.DISCONNECTED)
  807. const s = _S()
  808. const payload = bufferToArrayBuffer(u8)
  809. s.writeLock = s.writeLock.then(async () => {
  810. logger.log('=>', bytesToHex(u8))
  811. logger.log('write params:', {
  812. deviceId: this.device.deviceId,
  813. serviceId: s.serviceId,
  814. characteristicId: s.writeCharId,
  815. valueByteLength: payload.byteLength
  816. })
  817. try {
  818. await _invoke(uni.writeBLECharacteristicValue, {
  819. deviceId: this.device.deviceId,
  820. serviceId: s.serviceId,
  821. characteristicId: s.writeCharId,
  822. value: payload
  823. })
  824. } catch (e) {
  825. logger.error('writeBLE origin error:', JSON.stringify(e))
  826. throw _err(BLE_ERROR.WRITE_FAIL, e)
  827. }
  828. })
  829. return s.writeLock
  830. },
  831. /** 下发基本功能指令 (0x01) */
  832. sendBasic(opt) { return this.writeRaw(encodeBasic(opt)) },
  833. /** 下发模式参数 1 (步骤 1-7) */
  834. sendModeParam1(opt) { return this.writeRaw(encodeModeParam1(opt)) },
  835. /** 下发模式参数 2 (步骤 8-14) */
  836. sendModeParam2(opt) { return this.writeRaw(encodeModeParam2(opt)) },
  837. /** 下发穴位坐标 */
  838. async sendAcupoints(points = []) {
  839. for (let i = 0; i < points.length; i += 2) {
  840. const pair = points.slice(i, i + 2)
  841. await this.writeRaw(encodeAcupoints(pair))
  842. }
  843. },
  844. // ---- 常用快捷方法 ----
  845. powerOn() { return this.sendBasic({ power: POWER.ON }) },
  846. powerOff() { return this.sendBasic({ power: POWER.OFF }) },
  847. startMoxi(opt = {}) { return this.sendBasic({ power: POWER.ON, moxiState: MOXI_STATE.START, ...opt }) },
  848. pauseMoxi() { return this.sendBasic({ moxiState: MOXI_STATE.PAUSE }) },
  849. stopMoxi() { return this.sendBasic({ moxiState: MOXI_STATE.DONE }) },
  850. setMute(on) { return this.sendBasic({ mute: on ? MUTE.ON : MUTE.OFF }) },
  851. setTemperature(v) { return this.sendBasic({ temperature: v }) },
  852. setChairAngle(v) { return this.sendBasic({ angle: v }) },
  853. // ============== 蓝牙关闭提示 ==============
  854. /**
  855. * 弹窗提示用户蓝牙未开启,引导用户前往设置开启
  856. * 内部做防抖,避免短时间内重复弹窗
  857. */
  858. _showBleOffPrompt(message) {
  859. const s = _S()
  860. // 弹窗正在显示中,不重复弹出
  861. if (s._bleOffPromptShowing) return
  862. s._bleOffPromptShowing = true
  863. uni.showModal({
  864. title: '蓝牙未开启',
  865. content: message || '请开启手机蓝牙后重试',
  866. confirmText: '去设置',
  867. cancelText: '取消',
  868. success: (res) => {
  869. s._bleOffPromptShowing = false
  870. if (res.confirm) {
  871. // #ifdef APP-PLUS
  872. const platform = uni.getSystemInfoSync().platform
  873. if (platform === 'android') {
  874. try {
  875. const main = plus.android.runtimeMainActivity()
  876. const Intent = plus.android.importClass('android.content.Intent')
  877. const Settings = plus.android.importClass('android.provider.Settings')
  878. const intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
  879. main.startActivity(intent)
  880. } catch (e) {
  881. logger.error('跳转蓝牙设置失败', e)
  882. }
  883. } else if (platform === 'ios') {
  884. // iOS 可以打开 App 设置页
  885. plus.runtime.openURL('App-Prefs:root=Bluetooth')
  886. }
  887. // #endif
  888. }
  889. }
  890. })
  891. }
  892. }
  893. })