ble-mixin.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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, openBluetoothSettings, openLocationSettings } 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. if (e.message === 'BLE_ADAPTER_OFF') {
  64. uni.showModal({
  65. title: '提示',
  66. content: '蓝牙未开启,请先开启蓝牙',
  67. cancelText: '取消',
  68. confirmText: '去开启',
  69. success: (res) => {
  70. if (res.confirm) {
  71. openBluetoothSettings()
  72. }
  73. }
  74. })
  75. return
  76. }
  77. }
  78. // 2. 判断当前是否已连接同一设备,如果是则跳过重连
  79. const currentDevice = this.bleStore.device
  80. console.log('[BLE] 当前设备', currentDevice,this.bleStore.linked,this.deviceId)
  81. if (this.bleStore.linked && currentDevice && currentDevice.deviceId === this.deviceId) {
  82. console.log('[BLE] 已连接相同设备,跳过重连', this.deviceId)
  83. return
  84. }
  85. // 3. 不同设备或未连接:断开旧连接并关闭适配器(不解绑全局监听器)
  86. try { await this.bleStore.disconnect() } catch (_) {}
  87. try { await this.bleStore.resetAdapter() } catch (_) {}
  88. // 4. 扫描并连接设备(优先直连,跳过扫描避免 Android 限流)
  89. try {
  90. const scanOpt = { timeout: 8000 }
  91. // 已有 deviceId 时优先直连,不需要扫描
  92. if (this.deviceId) {
  93. scanOpt.deviceId = this.deviceId
  94. }
  95. if (this.deviceName) {
  96. scanOpt.deviceName = this.deviceName
  97. }
  98. await this.bleStore.scanAndConnect(scanOpt)
  99. // BLE连接建立后需短暂等待设备就绪再发首条指令
  100. await new Promise(r => setTimeout(r, 1500))
  101. this._sendCurrentState()
  102. } catch (e) {
  103. console.error('BLE连接失败', e)
  104. this.$refs.ayToast.error(this._bleFriendlyMsg(e))
  105. }
  106. },
  107. // ========== 发送指令 ==========
  108. _sendCurrentState() {
  109. const modeMap = [MODE.LEISURE, MODE.PROFESSIONAL, MODE.PERSONAL, MODE.EXPERT]
  110. this.bleStore.sendBasic({
  111. power: POWER.ON,
  112. moxiState: MOXI_STATE.DONE,
  113. preheatState: MOXI_STATE.DONE,
  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: 0
  120. }).catch(e => console.error('sendBasic fail', e))
  121. },
  122. // ========== 开始艾灸 ==========
  123. startDeviceEvt() {
  124. this.bleStore.deviceStatus = 1
  125. this.bleStore.ispreHot = false
  126. let totalDuration = 0
  127. this.curCase.forEach(item => {
  128. totalDuration += item.time
  129. })
  130. const modeMap = [MODE.LEISURE, MODE.PROFESSIONAL, MODE.PERSONAL, MODE.EXPERT]
  131. this.bleStore.sendBasic({
  132. power: POWER.ON,
  133. moxiState: MOXI_STATE.START,
  134. preheatState: MOXI_STATE.START,
  135. mute: MUTE.OFF,
  136. mode: modeMap[this.modeType] || MODE.LEISURE,
  137. subMode: 0x01,
  138. temperature: TEMPERATURE.MID,
  139. angle: CHAIR_ANGLE.OFF,
  140. duration: totalDuration || 30
  141. }).catch(e => console.error('startDevice fail', e))
  142. if (this.curCase.length > 0) {
  143. const points = this.curCase.map(item => ({
  144. point: item.id,
  145. x: item._x,
  146. y: item._y
  147. }))
  148. this.bleStore.sendAcupoints(points).catch(e => console.error('sendAcupoints fail', e))
  149. }
  150. },
  151. // ========== 暂停/继续 ==========
  152. stopAijiu() {
  153. if (this.deviceStatus == 5) {
  154. this.bleStore.deviceStatus = 3
  155. this.bleStore.sendBasic({ moxiState: MOXI_STATE.START }).catch(() => {})
  156. } else if (this.deviceStatus == 3) {
  157. this.bleStore.deviceStatus = 5
  158. this.bleStore.sendBasic({ moxiState: MOXI_STATE.PAUSE }).catch(() => {})
  159. }
  160. },
  161. // ========== 停止 ==========
  162. stopPreHot() {
  163. this.isShowConfirm = true
  164. },
  165. confirmStop() {
  166. this.bleStore.deviceStatus = 0
  167. this.isShowConfirm = false
  168. this.bleStore.sendBasic({ moxiState: MOXI_STATE.DONE }).catch(() => {})
  169. },
  170. // ========== 模式切换 ==========
  171. changeMode(num) {
  172. uni.showModal({
  173. title: '提示',
  174. content: '切换模式会停止当前的艾灸,是否继续',
  175. cancelText: '取消',
  176. confirmText: '继续',
  177. success: (res) => {
  178. if (res.confirm) {
  179. this.bleStore.modeType = num
  180. this.bleStore.deviceStatus = 0
  181. this.isShowDrawer2 = false
  182. if (this._stopAudioOnModeChange) {
  183. this._stopAudioOnModeChange()
  184. }
  185. const modeMap = [MODE.LEISURE, MODE.PROFESSIONAL, MODE.PERSONAL, MODE.EXPERT]
  186. this.bleStore.sendBasic({
  187. power: POWER.ON,
  188. moxiState: MOXI_STATE.DONE,
  189. preheatState: MOXI_STATE.DONE,
  190. mute: MUTE.OFF,
  191. mode: modeMap[num] || MODE.LEISURE,
  192. subMode: 0x01,
  193. temperature: TEMPERATURE.MID,
  194. angle: CHAIR_ANGLE.OFF,
  195. duration: 0
  196. }).catch(e => console.error('changeMode fail', e))
  197. }
  198. }
  199. })
  200. },
  201. // ========== 断开BLE ==========
  202. disconnectBle() {
  203. // 先停止扫描(防止页面销毁后 onBluetoothDeviceFound 回调找不到 taskCenter)
  204. this.bleStore.stopScan()
  205. this.bleStore.disconnect().catch(() => {})
  206. },
  207. /**
  208. * 页面离开时的轻量清理:只停止扫描,不断开BLE连接
  209. * 保持蓝牙连接状态,下次进入相同设备页面可复用
  210. */
  211. cleanupOnLeave() {
  212. this.bleStore.stopScan()
  213. },
  214. // ========== BLE错误码转用户友好提示 ==========
  215. _bleFriendlyMsg(e) {
  216. const code = e && (e.code || e.message || '')
  217. const originMsg = e && e.origin && e.origin.msg
  218. const map = {
  219. BLE_SCAN_FAIL: this.bleStore.scanThrottled
  220. ? '扫描过于频繁,请等待30秒后再试'
  221. : (originMsg || '未搜索到设备,请确保设备已开机并靠近手机'),
  222. BLE_CONNECT_FAIL: '连接设备失败,请确保设备在范围内并重试',
  223. BLE_CONNECT_TIMEOUT: '连接超时,请靠近设备后重试',
  224. BLE_ADAPTER_OFF: '蓝牙未开启,请先开启蓝牙',
  225. BLE_PERMISSION_DENIED: '蓝牙权限未授予,请在设置中开启',
  226. BLE_LOCATION_OFF: '位置服务未开启,请开启后重试',
  227. BLE_DISCONNECTED: '设备已断开连接',
  228. BLE_SERVICE_NOT_FOUND: '设备服务异常,请重启设备后重试',
  229. BLE_WRITE_FAIL: '指令发送失败,请重试',
  230. BLE_BUSY: '设备正忙,请稍后再试'
  231. }
  232. return map[code] || ('连接失败,请重试 (' + code + ')')
  233. }
  234. }
  235. }