home.vue 9.0 KB

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