ble.js 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  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. if (s.onDeviceFound) s.onDeviceFound(res)
  240. })
  241. s.bound = true
  242. logger.info(`[instanceId=${s.instanceId}] BLE系统监听器已全局绑定(含onBluetoothDeviceFound)`)
  243. },
  244. _unbindSystemListeners() {
  245. // 全局监听器不再主动解绑,防止 taskCenter 丢失
  246. // 仅在极端情况下(如蓝牙完全不再使用)才解绑
  247. },
  248. // ============== 确保就绪 ==============
  249. async _ensureReady() {
  250. if (this.bleState === BLE_STATE.IDLE) await this.init()
  251. try {
  252. const res = await _invoke(uni.getBluetoothAdapterState, {})
  253. if (!res.available) {
  254. this.bleAdapterOff = true
  255. this._showBleOffPrompt('请先开启手机蓝牙,才能连接艾灸椅设备')
  256. throw _err(BLE_ERROR.ADAPTER_OFF)
  257. }
  258. this.bleAdapterOff = false
  259. } catch (e) {
  260. if (e && e.code && String(e.code).startsWith('BLE_')) throw e
  261. throw _err(BLE_ERROR.ADAPTER_OFF, e)
  262. }
  263. },
  264. // ============== 扫描 ==============
  265. async startScan(opt = {}) {
  266. const s = _S()
  267. console.log(`[BLE Store] startScan() called, instanceId = ${s.instanceId}`)
  268. // 重置中止标记
  269. s.scanAborted = false
  270. this.scanThrottled = false
  271. // 取消上一次残留扫描
  272. if (s.cancelScan) { s.cancelScan(); s.cancelScan = null }
  273. // 停止上一次发现
  274. await _invoke(uni.stopBluetoothDevicesDiscovery, {}).catch(() => {})
  275. await this._ensureReady()
  276. // 如果在 await 期间页面已卸载并调用了 stopScan,直接中止
  277. if (s.scanAborted) {
  278. logger.info('startScan aborted (page already unloaded)')
  279. return opt.returnAll ? [] : null
  280. }
  281. const {
  282. namePrefix = s.config.deviceNamePrefix,
  283. deviceName,
  284. services,
  285. timeout = s.config.scanTimeout,
  286. returnAll = false
  287. } = opt
  288. // 清空上次扫描结果
  289. this.scannedDevices = []
  290. // Android 限流检测(30秒内最多5次,iOS 无此限制)
  291. const platform = uni.getSystemInfoSync().platform
  292. if (platform === 'android') {
  293. const now = Date.now()
  294. s.scanStartHistory = s.scanStartHistory.filter(t => now - t < 30000)
  295. if (s.scanStartHistory.length >= 4) {
  296. this.scanThrottled = true
  297. logger.warn(`BLE scan throttle: ${s.scanStartHistory.length + 1} starts in 30s, system may ignore`)
  298. }
  299. s.scanStartHistory.push(now)
  300. }
  301. const devices = new Map()
  302. const matched = []
  303. return new Promise(async (resolve, reject) => {
  304. let finished = false
  305. const onFound = (res) => {
  306. if (finished) return
  307. for (const d of res.devices) {
  308. if (devices.has(d.deviceId)) continue
  309. devices.set(d.deviceId, d)
  310. const name = d.name || d.localName || ''
  311. const hit =
  312. (deviceName && name === deviceName) ||
  313. (namePrefix && name.startsWith(namePrefix)) ||
  314. (!deviceName && !namePrefix)
  315. if (hit) {
  316. matched.push(d)
  317. const exists = this.scannedDevices.find(item => item.deviceId === d.deviceId)
  318. if (!exists) {
  319. this.scannedDevices.push({
  320. deviceId: d.deviceId,
  321. name: name,
  322. RSSI: d.RSSI || ''
  323. })
  324. }
  325. if (!returnAll) { finish(null, d); return }
  326. }
  327. }
  328. }
  329. const timer = setTimeout(() => {
  330. if (returnAll) finish(null, matched)
  331. else if (matched.length) finish(null, matched[0])
  332. else finish(_err(BLE_ERROR.SCAN_FAIL, { msg: '扫描超时,未发现目标设备' }))
  333. }, timeout)
  334. const finish = (err, data) => {
  335. if (finished) return
  336. finished = true
  337. s.cancelScan = null
  338. s.onDeviceFound = null
  339. clearTimeout(timer)
  340. _invoke(uni.stopBluetoothDevicesDiscovery, {}).catch(() => {})
  341. this._setState(BLE_STATE.READY)
  342. err ? reject(err) : resolve(data)
  343. }
  344. s.cancelScan = () => finish(null, returnAll ? matched : (matched[0] || null))
  345. // 通过共享回调分发事件(监听器已在 _bindSystemListeners 中永久注册)
  346. s.onDeviceFound = onFound
  347. this._setState(BLE_STATE.SCANNING)
  348. try {
  349. await _invoke(uni.startBluetoothDevicesDiscovery, {
  350. allowDuplicatesKey: false,
  351. interval: 0,
  352. services
  353. })
  354. } catch (e) {
  355. finish(_err(BLE_ERROR.SCAN_FAIL, e))
  356. }
  357. })
  358. },
  359. /** 停止扫描 */
  360. stopScan() {
  361. const s = _S()
  362. s.scanAborted = true
  363. s.onDeviceFound = null
  364. if (s.cancelScan) {
  365. s.cancelScan()
  366. s.cancelScan = null
  367. } else {
  368. try {
  369. uni.stopBluetoothDevicesDiscovery({ success() {}, fail() {} })
  370. } catch (e) {}
  371. }
  372. this.searching = false
  373. this.scanThrottled = false
  374. if (this.bleState === BLE_STATE.SCANNING) {
  375. // _setState(READY) 内部会检测 _connectedBeforeScan,
  376. // 若扫描前有连接则自动恢复为 READY_COMM
  377. this._setState(BLE_STATE.READY)
  378. }
  379. },
  380. // ============== 连接 ==============
  381. async connectDevice(deviceId) {
  382. const s = _S()
  383. console.log(`[BLE Store] connectDevice() called, instanceId = ${s.instanceId}`)
  384. if (!deviceId) throw _err(BLE_ERROR.CONNECT_FAIL, { msg: 'deviceId 不能为空' })
  385. await this._ensureReady()
  386. if (this.bleState === BLE_STATE.CONNECTING) throw _err(BLE_ERROR.BUSY)
  387. this._setState(BLE_STATE.CONNECTING)
  388. this.device = { deviceId, name: '' }
  389. try {
  390. await _invoke(uni.createBLEConnection, {
  391. deviceId,
  392. timeout: s.config.connectTimeout
  393. })
  394. this._setState(BLE_STATE.CONNECTED)
  395. // Android 提升 MTU
  396. // #ifdef APP-PLUS
  397. if (uni.getSystemInfoSync().platform === 'android' && uni.setBLEMTU) {
  398. try { await _invoke(uni.setBLEMTU, { deviceId, mtu: 185 }) } catch (_) {}
  399. }
  400. // #endif
  401. await this._discoverAndSubscribe(deviceId)
  402. this._setState(BLE_STATE.READY_COMM)
  403. s.reconnectCount = 0
  404. } catch (e) {
  405. this._setState(BLE_STATE.DISCONNECTED)
  406. this.device = null // 连接失败,清空 device 防止延迟回调误触发重连
  407. try { await _invoke(uni.closeBLEConnection, { deviceId }) } catch (_) {}
  408. const code = e && (e.errCode || e.code)
  409. if (code === 10003 || code === -1) {
  410. throw _err(BLE_ERROR.CONNECT_TIMEOUT, e)
  411. }
  412. throw _err(BLE_ERROR.CONNECT_FAIL, e)
  413. }
  414. },
  415. /** 扫描 + 连接一步到位(支持 deviceId 直连优先,跳过扫描) */
  416. async scanAndConnect(opt = {}) {
  417. const { deviceId: directId, deviceName, ...restOpt } = opt
  418. // 策略:如果已有 deviceId,先尝试直连(不扫描),失败后回退扫描
  419. if (directId) {
  420. try {
  421. logger.info(`directConnect attempt, deviceId=${directId}`)
  422. await this.connectDevice(directId)
  423. this.device.name = deviceName || this.device.name || ''
  424. logger.info('directConnect success, scan skipped')
  425. return this.device
  426. } catch (e) {
  427. logger.warn('directConnect failed, fallback to scan', e.message || e.code)
  428. // connectDevice 失败时已清空 this.device 并关闭连接,无需额外处理
  429. }
  430. }
  431. // 回退:扫描 + 连接
  432. const scanOpt = { ...restOpt }
  433. if (deviceName) scanOpt.deviceName = deviceName
  434. const device = await this.startScan(scanOpt)
  435. await this.connectDevice(device.deviceId)
  436. this.device.name = device.name || device.localName || ''
  437. return this.device
  438. },
  439. /** 主动断开 */
  440. async disconnect() {
  441. const s = _S()
  442. s.intentionalDisconnect = true
  443. this._clearReconnect()
  444. if (!this.device) {
  445. s.intentionalDisconnect = false
  446. return
  447. }
  448. const { deviceId } = this.device
  449. // 先置空 device,防止 onBLEConnectionStateChange 回调误匹配
  450. this.device = null
  451. this._setState(BLE_STATE.DISCONNECTED)
  452. try { await _invoke(uni.closeBLEConnection, { deviceId }) } catch (_) {}
  453. s.intentionalDisconnect = false
  454. },
  455. /** 发现服务并订阅通知 */
  456. async _discoverAndSubscribe(deviceId) {
  457. const s = _S()
  458. const svcRes = await _invoke(uni.getBLEDeviceServices, { deviceId })
  459. const services = svcRes.services || []
  460. const targetSvc = services.find(sv => _uuidEq(sv.uuid, s.config.serviceId))
  461. || services.find(sv => sv.isPrimary)
  462. || services[0]
  463. if (!targetSvc) throw _err(BLE_ERROR.SERVICE_NOT_FOUND)
  464. s.serviceId = targetSvc.uuid
  465. const charRes = await _invoke(uni.getBLEDeviceCharacteristics, {
  466. deviceId, serviceId: s.serviceId
  467. })
  468. const chars = charRes.characteristics || []
  469. const writeChar = chars.find(c => _uuidEq(c.uuid, s.config.writeCharId))
  470. || chars.find(c => c.properties && (c.properties.write || c.properties.writeNoResponse || c.properties.writeDefault))
  471. const notifyChar = chars.find(c => _uuidEq(c.uuid, s.config.notifyCharId))
  472. || chars.find(c => c.properties && (c.properties.notify || c.properties.indicate))
  473. if (!writeChar) throw _err(BLE_ERROR.CHAR_NOT_FOUND, { msg: '未找到写特征' })
  474. if (!notifyChar) throw _err(BLE_ERROR.CHAR_NOT_FOUND, { msg: '未找到通知特征' })
  475. s.writeCharId = writeChar.uuid
  476. s.notifyCharId = notifyChar.uuid
  477. await _invoke(uni.notifyBLECharacteristicValueChange, {
  478. deviceId,
  479. serviceId: s.serviceId,
  480. characteristicId: s.notifyCharId,
  481. state: true
  482. })
  483. },
  484. // ============== 断连处理 & 自动重连 ==============
  485. _handleDisconnected(reason) {
  486. const s = _S()
  487. // 主动断开/重置时不触发重连
  488. if (s.intentionalDisconnect) return
  489. if (this.bleState === BLE_STATE.DISCONNECTED || this.bleState === BLE_STATE.IDLE) return
  490. const device = this.device
  491. this._setState(BLE_STATE.DISCONNECTED)
  492. if (s.parser) s.parser.reset()
  493. this._attemptReconnect(device, reason)
  494. },
  495. _attemptReconnect(device, reason) {
  496. const s = _S()
  497. if (!s.config.autoReconnect || !device || s.reconnectCount >= s.config.maxReconnect) {
  498. if (s.reconnectCount >= s.config.maxReconnect) {
  499. logger.warn('reconnect max reached, waiting for adapter restore')
  500. s.reconnectCount = 0
  501. this.reconnectDrawer = false
  502. this.reconnectCount = 0
  503. }
  504. return
  505. }
  506. s.reconnectCount++
  507. this.reconnectCount = s.reconnectCount
  508. this.reconnectDrawer = true
  509. const delay = Math.min(1000 * s.reconnectCount, 5000)
  510. logger.warn(`reconnect in ${delay}ms (${s.reconnectCount}/${s.config.maxReconnect})`)
  511. const gen = s.reconnectGeneration
  512. s.reconnectTimer = setTimeout(async () => {
  513. if (s.reconnectGeneration !== gen) {
  514. logger.info('reconnect callback aborted (generation mismatch)')
  515. return
  516. }
  517. try {
  518. // 先关闭适配器清除脏状态(加标志防止回调干扰)
  519. s.intentionalDisconnect = true
  520. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  521. s.intentionalDisconnect = false
  522. this._setState(BLE_STATE.IDLE)
  523. if (s.reconnectGeneration !== gen) return
  524. // 优先使用 deviceId 直连,避免不必要的扫描触发 Android 限流
  525. const scanOpt = { timeout: 8000 }
  526. if (device.deviceId) scanOpt.deviceId = device.deviceId
  527. if (device.name) scanOpt.deviceName = device.name
  528. await this.scanAndConnect(scanOpt)
  529. if (s.reconnectGeneration !== gen) return
  530. this.reconnectDrawer = false
  531. this.reconnectCount = 0
  532. logger.info('reconnect success')
  533. } catch (e) {
  534. if (s.reconnectGeneration !== gen) return
  535. logger.error('reconnect fail', e)
  536. this._attemptReconnect(device, reason)
  537. }
  538. }, delay)
  539. },
  540. _clearReconnect() {
  541. const s = _S()
  542. if (s.reconnectTimer) { clearTimeout(s.reconnectTimer); s.reconnectTimer = null }
  543. s.reconnectCount = 0
  544. s.reconnectGeneration++ // 递增代数,使正在执行的僵尸回调自动失效
  545. this.reconnectCount = 0
  546. this.reconnectDrawer = false
  547. },
  548. /**
  549. * 蓝牙适配器从关闭恢复为开启时调用
  550. * 如果之前有连接过的设备且当前处于断连状态,自动扫描并重新连接
  551. */
  552. _onAdapterRestored() {
  553. const device = this.device
  554. if (!device || !device.deviceId) return
  555. if (this.bleState !== BLE_STATE.DISCONNECTED && this.bleState !== BLE_STATE.IDLE) return
  556. logger.info('adapter restored, auto reconnecting to', device.name || device.deviceId)
  557. // 重置重连计数,发起新一轮重连
  558. this._clearReconnect()
  559. this._setState(BLE_STATE.IDLE)
  560. // 延迟 1.5s 等待适配器完全就绪(Android 蓝牙状态延迟)
  561. const s = _S()
  562. const gen = s.reconnectGeneration
  563. this.reconnectDrawer = true
  564. this.reconnectCount = 1
  565. s.reconnectTimer = setTimeout(async () => {
  566. if (s.reconnectGeneration !== gen) return
  567. try {
  568. // 关闭旧适配器,确保重新打开时状态干净
  569. s.intentionalDisconnect = true
  570. try { await _invoke(uni.closeBluetoothAdapter, {}) } catch (_) {}
  571. s.intentionalDisconnect = false
  572. if (s.reconnectGeneration !== gen) return
  573. // 优先直连,避免扫描触发限流
  574. const scanOpt = { timeout: 8000 }
  575. if (device.deviceId) scanOpt.deviceId = device.deviceId
  576. if (device.name) scanOpt.deviceName = device.name
  577. await this.scanAndConnect(scanOpt)
  578. if (s.reconnectGeneration !== gen) return
  579. this.reconnectDrawer = false
  580. this.reconnectCount = 0
  581. logger.info('adapter restore reconnect success')
  582. } catch (e) {
  583. if (s.reconnectGeneration !== gen) return
  584. logger.error('adapter restore reconnect fail', e)
  585. // 失败后进入常规重连流程(还有2次机会)
  586. s.reconnectCount = 1
  587. this._attemptReconnect(device, BLE_ERROR.ADAPTER_OFF)
  588. }
  589. }, 1500)
  590. },
  591. // ============== 收包处理 ==============
  592. _onFrame(decoded, frame) {
  593. logger.info('frame received', decoded.funcCode)
  594. if (decoded.parsed) {
  595. if (decoded.parsed.type === 'GROUP_1') {
  596. this._handleGroup1(decoded.parsed)
  597. } else if (decoded.parsed.type === 'GROUP_2') {
  598. this._handleGroup2(decoded.parsed)
  599. }
  600. }
  601. },
  602. /** 解析参数组1 */
  603. _handleGroup1(data) {
  604. // 设备运行状态
  605. switch (data.runtimeState) {
  606. case 0x00: this.deviceStatus = 0; break
  607. case 0x01:
  608. case 0x02: this.deviceStatus = 1; break
  609. case 0x03: this.deviceStatus = 3; break
  610. case 0x04: this.deviceStatus = 4; break
  611. case 0x05: this.deviceStatus = 5; break
  612. }
  613. // 模式
  614. switch (data.mode) {
  615. case MODE.LEISURE: this.modeType = 0; break
  616. case MODE.PROFESSIONAL: this.modeType = 1; break
  617. case MODE.PERSONAL: this.modeType = 2; break
  618. case MODE.EXPERT: this.modeType = 3; break
  619. }
  620. // 剩余时间
  621. const m = data.remainMinute || 0
  622. const s = data.remainSecond || 0
  623. const h = Math.floor(m / 60)
  624. const m1 = m % 60
  625. this.subTime = `${h.toString().padStart(2, '0')}:${m1.toString().padStart(2, '0')}:${s.toString().padStart(2, '0')}`
  626. // 异常检测
  627. if (data.foreignDetect === 0x02) {
  628. this.excepDrawer = true
  629. this.exceTxt = 1
  630. }
  631. // 耗材状态
  632. this.otherSetting.aijiuNum = String(data.consumable || 0)
  633. this.otherSetting.lvxinNum = String(data.filterPercent || 0)
  634. this.otherSetting.huishouNum = String(data.recycleBinPct || 0)
  635. },
  636. /** 解析参数组2 */
  637. _handleGroup2(data) {
  638. if (data.preheatPercent < 100) {
  639. this.ispreHot = false
  640. this.hotPercentage = data.preheatPercent + '%'
  641. } else {
  642. this.ispreHot = true
  643. this.hotPercentage = data.ignitePercent + '%'
  644. }
  645. // 椅子角度
  646. if (data.chairAngle) {
  647. const angleMap = {
  648. 1: 90, 2: 105, 3: 120, 4: 135, 5: 150
  649. }
  650. if (angleMap[data.chairAngle]) {
  651. this.chairAngle = angleMap[data.chairAngle]
  652. }
  653. }
  654. },
  655. // ============== 发送指令 ==============
  656. async writeRaw(u8) {
  657. if (!this.linked) throw _err(BLE_ERROR.DISCONNECTED)
  658. const s = _S()
  659. const payload = bufferToArrayBuffer(u8)
  660. s.writeLock = s.writeLock.then(async () => {
  661. logger.log('=>', bytesToHex(u8))
  662. logger.log('write params:', {
  663. deviceId: this.device.deviceId,
  664. serviceId: s.serviceId,
  665. characteristicId: s.writeCharId,
  666. valueByteLength: payload.byteLength
  667. })
  668. try {
  669. await _invoke(uni.writeBLECharacteristicValue, {
  670. deviceId: this.device.deviceId,
  671. serviceId: s.serviceId,
  672. characteristicId: s.writeCharId,
  673. value: payload
  674. })
  675. } catch (e) {
  676. logger.error('writeBLE origin error:', JSON.stringify(e))
  677. throw _err(BLE_ERROR.WRITE_FAIL, e)
  678. }
  679. })
  680. return s.writeLock
  681. },
  682. /** 下发基本功能指令 (0x01) */
  683. sendBasic(opt) { return this.writeRaw(encodeBasic(opt)) },
  684. /** 下发模式参数 1 (步骤 1-7) */
  685. sendModeParam1(opt) { return this.writeRaw(encodeModeParam1(opt)) },
  686. /** 下发模式参数 2 (步骤 8-14) */
  687. sendModeParam2(opt) { return this.writeRaw(encodeModeParam2(opt)) },
  688. /** 下发穴位坐标 */
  689. async sendAcupoints(points = []) {
  690. for (let i = 0; i < points.length; i += 2) {
  691. const pair = points.slice(i, i + 2)
  692. await this.writeRaw(encodeAcupoints(pair))
  693. }
  694. },
  695. // ---- 常用快捷方法 ----
  696. powerOn() { return this.sendBasic({ power: POWER.ON }) },
  697. powerOff() { return this.sendBasic({ power: POWER.OFF }) },
  698. startMoxi(opt = {}) { return this.sendBasic({ power: POWER.ON, moxiState: MOXI_STATE.START, ...opt }) },
  699. pauseMoxi() { return this.sendBasic({ moxiState: MOXI_STATE.PAUSE }) },
  700. stopMoxi() { return this.sendBasic({ moxiState: MOXI_STATE.DONE }) },
  701. setMute(on) { return this.sendBasic({ mute: on ? MUTE.ON : MUTE.OFF }) },
  702. setTemperature(v) { return this.sendBasic({ temperature: v }) },
  703. setChairAngle(v) { return this.sendBasic({ angle: v }) },
  704. // ============== 蓝牙关闭提示 ==============
  705. /**
  706. * 弹窗提示用户蓝牙未开启,引导用户前往设置开启
  707. * 内部做防抖,避免短时间内重复弹窗
  708. */
  709. _showBleOffPrompt(message) {
  710. const s = _S()
  711. // 弹窗正在显示中,不重复弹出
  712. if (s._bleOffPromptShowing) return
  713. s._bleOffPromptShowing = true
  714. uni.showModal({
  715. title: '蓝牙未开启',
  716. content: message || '请开启手机蓝牙后重试',
  717. confirmText: '去设置',
  718. cancelText: '取消',
  719. success: (res) => {
  720. s._bleOffPromptShowing = false
  721. if (res.confirm) {
  722. // #ifdef APP-PLUS
  723. const platform = uni.getSystemInfoSync().platform
  724. if (platform === 'android') {
  725. try {
  726. const main = plus.android.runtimeMainActivity()
  727. const Intent = plus.android.importClass('android.content.Intent')
  728. const Settings = plus.android.importClass('android.provider.Settings')
  729. const intent = new Intent(Settings.ACTION_BLUETOOTH_SETTINGS)
  730. main.startActivity(intent)
  731. } catch (e) {
  732. logger.error('跳转蓝牙设置失败', e)
  733. }
  734. } else if (platform === 'ios') {
  735. // iOS 可以打开 App 设置页
  736. plus.runtime.openURL('App-Prefs:root=Bluetooth')
  737. }
  738. // #endif
  739. }
  740. }
  741. })
  742. }
  743. }
  744. })