ble-mixin.js 7.8 KB

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