ble-mixin.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. /**
  2. * BLE 蓝牙连接与设备控制 mixin
  3. * 基于 Pinia Store 管理蓝牙单例状态
  4. * 负责:权限检查、连接/断连/重连、指令收发、设备状态管理
  5. */
  6. import { useBleStore } from '@/stores/ble'
  7. import { MODE, MOXI_STATE, POWER, MUTE, TEMPERATURE, CHAIR_ANGLE } from '@/utils/ble/constants.js'
  8. import { ensureBlePrerequisite } from '@/utils/ble/permission.js'
  9. export default {
  10. data() {
  11. return {
  12. isShowConfirm: false
  13. }
  14. },
  15. computed: {
  16. bleStore() {
  17. return useBleStore()
  18. },
  19. linked() {
  20. return this.bleStore.linked
  21. },
  22. deviceStatus: {
  23. get() { return this.bleStore.deviceStatus },
  24. set(val) { this.bleStore.deviceStatus = val }
  25. },
  26. hotPercentage() {
  27. return this.bleStore.hotPercentage
  28. },
  29. ispreHot: {
  30. get() { return this.bleStore.ispreHot },
  31. set(val) { this.bleStore.ispreHot = val }
  32. },
  33. reconnectDrawer() {
  34. return this.bleStore.reconnectDrawer
  35. },
  36. reconnectCount() {
  37. return this.bleStore.reconnectCount
  38. },
  39. excepDrawer: {
  40. get() { return this.bleStore.excepDrawer },
  41. set(val) { this.bleStore.excepDrawer = val }
  42. },
  43. exceTxt: {
  44. get() { return this.bleStore.exceTxt },
  45. set(val) { this.bleStore.exceTxt = val }
  46. }
  47. },
  48. methods: {
  49. // ========== BLE 初始化 ==========
  50. async initBle() {
  51. // 1. Android权限检查
  52. try {
  53. await ensureBlePrerequisite()
  54. } catch (e) {
  55. if (e.message === 'BLE_PERMISSION_DENIED') {
  56. this.$refs.ayToast.error('请授予蓝牙权限后重试')
  57. return
  58. }
  59. if (e.message === 'BLE_LOCATION_OFF') {
  60. this.$refs.ayToast.error('请开启位置服务后重试')
  61. return
  62. }
  63. }
  64. // 2. 断开旧连接并关闭适配器(不解绑全局监听器)
  65. try { await this.bleStore.disconnect() } catch (_) {}
  66. try { await this.bleStore.resetAdapter() } catch (_) {}
  67. // 3. 扫描并连接设备(优先直连,跳过扫描避免 Android 限流)
  68. try {
  69. const scanOpt = { timeout: 8000 }
  70. // 已有 deviceId 时优先直连,不需要扫描
  71. if (this.deviceId) {
  72. scanOpt.deviceId = this.deviceId
  73. }
  74. if (this.deviceName) {
  75. scanOpt.deviceName = this.deviceName
  76. }
  77. await this.bleStore.scanAndConnect(scanOpt)
  78. // BLE连接建立后需短暂等待设备就绪再发首条指令
  79. await new Promise(r => setTimeout(r, 1500))
  80. this._sendCurrentState()
  81. } catch (e) {
  82. console.error('BLE连接失败', e)
  83. this.$refs.ayToast.error(this._bleFriendlyMsg(e))
  84. }
  85. },
  86. // ========== 发送指令 ==========
  87. _sendCurrentState() {
  88. const modeMap = [MODE.LEISURE, MODE.PROFESSIONAL, MODE.PERSONAL, MODE.EXPERT]
  89. this.bleStore.sendBasic({
  90. power: POWER.ON,
  91. moxiState: MOXI_STATE.DONE,
  92. preheatState: MOXI_STATE.DONE,
  93. mute: MUTE.OFF,
  94. mode: modeMap[this.modeType] || MODE.LEISURE,
  95. subMode: 0x01,
  96. temperature: TEMPERATURE.MID,
  97. angle: CHAIR_ANGLE.OFF,
  98. duration: 0
  99. }).catch(e => console.error('sendBasic fail', e))
  100. },
  101. // ========== 开始艾灸 ==========
  102. startDeviceEvt() {
  103. this.bleStore.deviceStatus = 1
  104. this.bleStore.ispreHot = false
  105. let totalDuration = 0
  106. this.curCase.forEach(item => {
  107. totalDuration += item.time
  108. })
  109. const modeMap = [MODE.LEISURE, MODE.PROFESSIONAL, MODE.PERSONAL, MODE.EXPERT]
  110. this.bleStore.sendBasic({
  111. power: POWER.ON,
  112. moxiState: MOXI_STATE.START,
  113. preheatState: MOXI_STATE.START,
  114. mute: MUTE.OFF,
  115. mode: modeMap[this.modeType] || MODE.LEISURE,
  116. subMode: 0x01,
  117. temperature: TEMPERATURE.MID,
  118. angle: CHAIR_ANGLE.OFF,
  119. duration: totalDuration || 30
  120. }).catch(e => console.error('startDevice fail', e))
  121. if (this.curCase.length > 0) {
  122. const points = this.curCase.map(item => ({
  123. point: item.id,
  124. x: item._x,
  125. y: item._y
  126. }))
  127. this.bleStore.sendAcupoints(points).catch(e => console.error('sendAcupoints fail', e))
  128. }
  129. },
  130. // ========== 暂停/继续 ==========
  131. stopAijiu() {
  132. if (this.deviceStatus == 5) {
  133. this.bleStore.deviceStatus = 3
  134. this.bleStore.sendBasic({ moxiState: MOXI_STATE.START }).catch(() => {})
  135. } else if (this.deviceStatus == 3) {
  136. this.bleStore.deviceStatus = 5
  137. this.bleStore.sendBasic({ moxiState: MOXI_STATE.PAUSE }).catch(() => {})
  138. }
  139. },
  140. // ========== 停止 ==========
  141. stopPreHot() {
  142. this.isShowConfirm = true
  143. },
  144. confirmStop() {
  145. this.bleStore.deviceStatus = 0
  146. this.isShowConfirm = false
  147. this.bleStore.sendBasic({ moxiState: MOXI_STATE.DONE }).catch(() => {})
  148. },
  149. // ========== 模式切换 ==========
  150. changeMode(num) {
  151. uni.showModal({
  152. title: '提示',
  153. content: '切换模式会停止当前的艾灸,是否继续',
  154. cancelText: '取消',
  155. confirmText: '继续',
  156. success: (res) => {
  157. if (res.confirm) {
  158. this.bleStore.modeType = num
  159. this.bleStore.deviceStatus = 0
  160. this.isShowDrawer2 = false
  161. if (this._stopAudioOnModeChange) {
  162. this._stopAudioOnModeChange()
  163. }
  164. const modeMap = [MODE.LEISURE, MODE.PROFESSIONAL, MODE.PERSONAL, MODE.EXPERT]
  165. this.bleStore.sendBasic({
  166. power: POWER.ON,
  167. moxiState: MOXI_STATE.DONE,
  168. preheatState: MOXI_STATE.DONE,
  169. mute: MUTE.OFF,
  170. mode: modeMap[num] || MODE.LEISURE,
  171. subMode: 0x01,
  172. temperature: TEMPERATURE.MID,
  173. angle: CHAIR_ANGLE.OFF,
  174. duration: 0
  175. }).catch(e => console.error('changeMode fail', e))
  176. }
  177. }
  178. })
  179. },
  180. // ========== 断开BLE ==========
  181. disconnectBle() {
  182. // 先停止扫描(防止页面销毁后 onBluetoothDeviceFound 回调找不到 taskCenter)
  183. this.bleStore.stopScan()
  184. this.bleStore.disconnect().catch(() => {})
  185. },
  186. // ========== BLE错误码转用户友好提示 ==========
  187. _bleFriendlyMsg(e) {
  188. const code = e && (e.code || e.message || '')
  189. const originMsg = e && e.origin && e.origin.msg
  190. const map = {
  191. BLE_SCAN_FAIL: this.bleStore.scanThrottled
  192. ? '扫描过于频繁,请等待30秒后再试'
  193. : (originMsg || '未搜索到设备,请确保设备已开机并靠近手机'),
  194. BLE_CONNECT_FAIL: '连接设备失败,请确保设备在范围内并重试',
  195. BLE_CONNECT_TIMEOUT: '连接超时,请靠近设备后重试',
  196. BLE_ADAPTER_OFF: '蓝牙未开启,请先开启蓝牙',
  197. BLE_PERMISSION_DENIED: '蓝牙权限未授予,请在设置中开启',
  198. BLE_LOCATION_OFF: '位置服务未开启,请开启后重试',
  199. BLE_DISCONNECTED: '设备已断开连接',
  200. BLE_SERVICE_NOT_FOUND: '设备服务异常,请重启设备后重试',
  201. BLE_WRITE_FAIL: '指令发送失败,请重试',
  202. BLE_BUSY: '设备正忙,请稍后再试'
  203. }
  204. return map[code] || ('连接失败,请重试 (' + code + ')')
  205. }
  206. }
  207. }