home.vue 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433
  1. <template>
  2. <view>
  3. <h2 class='hTitle'>匹配蓝牙设备</h2>
  4. <view class="bottomBox">
  5. <button @click="refreshBlue" class="refreshBlueTooth">刷新蓝牙设备</button>
  6. <view class="equipmentTitle">
  7. 设备名称
  8. </view>
  9. <!-- 连接蓝牙列表 -->
  10. <view class="blueListBox">
  11. <scroll-view scroll-y class="box">
  12. <view class="item" v-for="item in blueDeviceList" @click="connect(item)">
  13. <view>
  14. <text>id: {{ item.deviceId }}</text>
  15. </view>
  16. <view>
  17. <text>name: {{ item.name }}</text>
  18. </view>
  19. </view>
  20. </scroll-view>
  21. </view>
  22. <view class="equipmentTitle">
  23. 已配对的设备
  24. </view>
  25. <view class="alreadyBlue">
  26. {{deviceId}}
  27. </view>
  28. <view class="bottom-btn">
  29. <button :loading='characteristicId==""' @click="confirmEdit" class="refreshBlueToothNot"
  30. :class="{refreshBlueTooth:characteristicId?true:false}">{{characteristicId?'确定编辑设备':'获取服务中'}}</button>
  31. </view>
  32. </view>
  33. </view>
  34. </template>
  35. <script>
  36. export default {
  37. data() {
  38. return {
  39. blueDeviceList: [], //蓝牙设备
  40. deviceId: '', //蓝牙设备ID
  41. serviceId: '', //服务UUID
  42. characteristicId: '', //特征值
  43. connected: false, //是否连接
  44. isUpdateData:false,//是否是返回蓝牙匹配
  45. };
  46. },
  47. created() {
  48. // 初始化蓝牙
  49. this.openBlue()
  50. // 获取蓝牙监听
  51. this.stateChange()
  52. },
  53. onShow() {
  54. let that = this
  55. uni.$on('updateData', function(data) {
  56. if (data) {
  57. this.isUpdateData = true
  58. // console.log('触发了');
  59. // 断开蓝牙
  60. if (that.deviceId) {
  61. that.closeBLEConnection(that.deviceId)
  62. }
  63. that.deviceId = ''
  64. that.serviceId = ''
  65. that.characteristicId = ''
  66. }
  67. })
  68. },
  69. onHide() {
  70. // 移除监听事件
  71. uni.$on('updateData', function(data) {
  72. uni.$off('updateData');
  73. this.isUpdateData = false
  74. })
  75. },
  76. methods: {
  77. // 蓝牙报错提示
  78. blueError(code) {
  79. switch (code) {
  80. case 10000:
  81. this.errorToast('未初始化蓝牙适配器')
  82. break
  83. case 10001:
  84. this.errorToast('当前蓝牙适配器不可用')
  85. break
  86. case 10002:
  87. this.errorToast('没有找到指定设备')
  88. break
  89. case 10003:
  90. this.errorToast('连接失败')
  91. break
  92. case 10004:
  93. this.errorToast('没有找到指定服务')
  94. break
  95. case 10005:
  96. this.errorToast('没有找到指定特征值')
  97. break
  98. case 10006:
  99. this.errorToast('当前连接已断开')
  100. break
  101. case 10007:
  102. this.errorToast('当前特征值不支持此操作')
  103. break
  104. case 10008:
  105. this.errorToast('其余所有系统上报的异常')
  106. break
  107. case 10009:
  108. this.errorToast('Android 系统特有,系统版本低于 4.3 不支持 BLE')
  109. break
  110. case 10010:
  111. this.errorToast('已连接')
  112. break
  113. case 10011:
  114. this.errorToast('配对设备需要配对码')
  115. break
  116. case 10012:
  117. this.errorToast('连接超时')
  118. break
  119. case 10013:
  120. this.errorToast('连接 deviceld 为空或者是格式不正确')
  121. break
  122. }
  123. },
  124. // 统一错误封装
  125. errorToast(err) {
  126. uni.showToast({
  127. title: `${err}`,
  128. icon: 'none',
  129. duration: 2500
  130. })
  131. },
  132. // 刷新蓝牙设备列表
  133. refreshBlue() {
  134. uni.showLoading({
  135. title: '正在刷新',
  136. mask: true
  137. })
  138. this.discovery('refresh')
  139. },
  140. // 确定编辑
  141. confirmEdit() {
  142. if (!this.characteristicId) {
  143. return
  144. }
  145. uni.navigateTo({
  146. url: `/pages/edit/edit?deviceId=${this.deviceId}&serviceId=${this.serviceId}&characteristicId=${this.characteristicId}`
  147. })
  148. },
  149. // 初始化蓝牙
  150. openBlue() {
  151. let that = this
  152. uni.showLoading({
  153. title: '初始化中',
  154. mask: true
  155. })
  156. uni.openBluetoothAdapter({
  157. success(res) {
  158. uni.hideLoading()
  159. uni.showToast({
  160. title: '初始化成功',
  161. duration: 2500
  162. })
  163. that.discovery()
  164. },
  165. fail(err) {
  166. uni.hideLoading()
  167. that.blueError(err.errCode)
  168. console.log('初始化蓝牙失败')
  169. console.error(err)
  170. }
  171. })
  172. },
  173. // 搜索蓝牙设备
  174. discovery(msg) {
  175. let that = this
  176. that.blueDeviceList = []
  177. uni.startBluetoothDevicesDiscovery({
  178. success(res) {
  179. if (msg = 'refresh') {
  180. uni.hideLoading()
  181. }
  182. // 开启监听回调
  183. uni.onBluetoothDeviceFound((res) => {
  184. if (res.devices[0].name) {
  185. that.found(res)
  186. }
  187. })
  188. },
  189. fail(err) {
  190. console.log('搜索失败')
  191. console.error(err)
  192. }
  193. })
  194. },
  195. // 找到新设备就触发该方法
  196. found(res) {
  197. if (res.devices[0].name.includes('BT24')) {
  198. this.blueDeviceList.push(res.devices[0])
  199. }
  200. // 判断是否连接
  201. if (this.connected) {
  202. return
  203. }
  204. // 检查本地是否有id
  205. let deviceId = uni.getStorageSync('deviceId')
  206. if (deviceId) {
  207. let list = []
  208. this.blueDeviceList.forEach(item => {
  209. list.push(item.deviceId)
  210. })
  211. if (list.includes(deviceId)) {
  212. // 重置deviceId
  213. this.deviceId = ''
  214. let data = {
  215. deviceId
  216. }
  217. this.connect(data)
  218. }
  219. }
  220. },
  221. //监听蓝牙状态
  222. stateChange() {
  223. uni.onBLEConnectionStateChange(function(res) {
  224. // 该方法回调中可以用于处理连接意外断开等异常情况
  225. let connected = res.connected
  226. console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`,
  227. '监听到蓝牙设备变化')
  228. if (!res.connected&&!this.isUpdateData) {
  229. console.log(111111, '断开重连操作');
  230. let data = {
  231. deviceId: this.deviceId
  232. }
  233. // 重置deviceId
  234. this.deviceId = ''
  235. this.connect(data)
  236. }
  237. })
  238. },
  239. // 断开蓝牙设备
  240. closeBLEConnection(deviceId) {
  241. console.log(deviceId, '断开蓝牙设备ID');
  242. uni.closeBLEConnection({
  243. deviceId,
  244. success(res) {
  245. console.log('断开蓝牙成功', res)
  246. },
  247. fail(err) {
  248. console.log('断开蓝牙失败', err);
  249. }
  250. })
  251. },
  252. // 连接设备
  253. connect(data) {
  254. // 判断是否是连接当前的蓝牙
  255. if (data.deviceId == this.deviceId) {
  256. uni.showToast({
  257. title: '您已经连接该蓝牙',
  258. duration: 2500,
  259. icon: 'none'
  260. })
  261. return
  262. } else if (this.deviceId) {
  263. this.closeBLEConnection(this.deviceId)
  264. }
  265. wx.showLoading({
  266. title: '正在连接',
  267. mask: true
  268. })
  269. let that = this
  270. that.deviceId = data.deviceId
  271. uni.createBLEConnection({
  272. deviceId: that.deviceId,
  273. timeout: 20000,
  274. success(res) {
  275. wx.hideLoading()
  276. uni.showToast({
  277. title: '连接成功',
  278. duration: 2500
  279. })
  280. console.log('连接成功');
  281. // 把deviceId保存到本地
  282. uni.setStorageSync('deviceId', that.deviceId);
  283. // 停止搜索
  284. that.stopDiscovery()
  285. //获取蓝牙服务
  286. setTimeout(() => {
  287. //需要延迟获取
  288. that.getLyService(that.deviceId)
  289. }, 1000)
  290. },
  291. fail(err) {
  292. wx.hideLoading()
  293. switch (err.errMsg) {
  294. default:
  295. that.blueError(err.errCode)
  296. that.deviceId = ''
  297. }
  298. console.log('连接失败')
  299. console.error(err)
  300. }
  301. })
  302. },
  303. // 停止搜索
  304. stopDiscovery() {
  305. uni.stopBluetoothDevicesDiscovery({
  306. success(res) {
  307. console.log('停止成功')
  308. console.log(res)
  309. },
  310. fail(err) {
  311. console.log('停止失败')
  312. console.error(err)
  313. }
  314. })
  315. },
  316. //获取蓝牙可用服务
  317. getLyService(deviceId) {
  318. uni.getBLEDeviceServices({
  319. deviceId: deviceId,
  320. success: async (res) => {
  321. console.log('蓝牙服务', JSON.stringify(res))
  322. if (res.services.length < 1) {
  323. setTimeout(() => {
  324. this.getLyService(deviceId)
  325. }, 1000)
  326. return;
  327. }
  328. for (var i = 0; i < res.services.length; i++) {
  329. //获取蓝牙特征值
  330. var characteristic = await this.getLyCharacteristic(deviceId, res.services[i].uuid)
  331. if (!characteristic) continue;
  332. this.serviceId = res.services[i].uuid
  333. this.characteristicId = characteristic
  334. console.log('ok:', this.serviceId + ',' + this.characteristicId)
  335. this.notifyLy();
  336. break;
  337. }
  338. },
  339. fail: (err) => {
  340. console.error(JSON.stringify(err))
  341. }
  342. })
  343. },
  344. //获取蓝牙可用特征值
  345. getLyCharacteristic(deviceId, serviceId) {
  346. return new Promise((resolve, reject) => {
  347. uni.getBLEDeviceCharacteristics({
  348. deviceId: deviceId,
  349. serviceId: serviceId,
  350. success: (res) => {
  351. var result = '';
  352. for (var i = 0; i < res.characteristics.length; i++) {
  353. var properties = res.characteristics[i].properties;
  354. if (properties.read && properties.write && properties.notify) {
  355. console.log('可用特征值', JSON.stringify(res.characteristics[i].uuid))
  356. result = res.characteristics[i].uuid;
  357. break;
  358. }
  359. }
  360. resolve(result)
  361. },
  362. fail: (err) => {
  363. console.log('特征值', JSON.stringify(err))
  364. reject('')
  365. }
  366. })
  367. })
  368. },
  369. }
  370. }
  371. </script>
  372. <style lang="less" scoped>
  373. .hTitle {
  374. margin-left: 10px;
  375. }
  376. .bottomBox {
  377. margin-left: 40px;
  378. margin-top: 50px;
  379. // 蓝牙按钮
  380. .refreshBlueTooth {
  381. width: 140px;
  382. background-color: #1e98d7;
  383. color: #fff;
  384. margin: 0;
  385. }
  386. .refreshBlueToothNot {
  387. width: 140px;
  388. margin: 0;
  389. }
  390. .equipmentTitle {
  391. font-size: 18px;
  392. margin-top: 20px;
  393. }
  394. .blueListBox {
  395. margin-top: 20px;
  396. width: 90%;
  397. height: 300px;
  398. border: 1px solid #1e98d7;
  399. border-radius: 12px;
  400. padding: 8px;
  401. background-color: #eee;
  402. .box {
  403. margin-bottom: 20px;
  404. height: 100%;
  405. width: 100%;
  406. }
  407. .item:nth-child(2n) {
  408. background-color: #1e98d7;
  409. }
  410. }
  411. .alreadyBlue {
  412. margin-top: 16px;
  413. font-size: 16px;
  414. }
  415. .bottom-btn {
  416. width: 90%;
  417. margin-top: 20px;
  418. display: flex;
  419. justify-content: flex-end;
  420. }
  421. }
  422. </style>