index.vue 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. <template>
  2. <view class="bg">
  3. <view class="bgimg">
  4. <u-image width="622rpx" height="953rpx" src="/static/ldbg.png"></u-image>
  5. </view>
  6. <!-- 称重 -->
  7. <view class="content">
  8. <view @click="toHelp" class="tdrecord">蓝牙使用帮助</view>
  9. <view class="cz-box" @click="toWork">
  10. <view :class="loading?'turn':''">
  11. <u-image width="100rpx" height="100rpx" src="/static/chengzhong.png"></u-image>
  12. <view class="tits">投放称重</view>
  13. </view>
  14. </view>
  15. <view class="bindDev" @click="toInit">
  16. {{statusStr}}
  17. </view>
  18. <view class="devList">
  19. <view v-for="item in deviceList" :key="item.deviceId">
  20. <view class="names">
  21. <view>设备名称:{{item.name}}</view>
  22. <view class="texts">MAC:{{item.deviceId}}</view>
  23. </view>
  24. <view class="btns" @click="connectBlue(item)" v-if="!connectStatus">点击连接</view>
  25. <view class="btns" @click="closeBlue" v-else>断开连接</view>
  26. </view>
  27. </view>
  28. </view>
  29. </view>
  30. </template>
  31. <script>
  32. import {getLookUpDatas} from '@/api/data.js'
  33. import { getUserInfo } from '@/api/user.js'
  34. export default {
  35. data() {
  36. return {
  37. deviceList:[], // 设备列表
  38. deviceId: null,
  39. iosMac: null,
  40. connectedDeviceId: '',
  41. services: [],
  42. readsId:'',
  43. writeId:'',
  44. notifyServicweId: '',
  45. writeDatas: '',
  46. balanceData: '',
  47. hexstr: '',
  48. statusStr: '绑定电子秤',
  49. connectStatus: false ,// 设备连接状态
  50. loading: false ,// 正在连接
  51. }
  52. },
  53. onLoad() {
  54. let _this = this
  55. uni.$on('blueReConnect',function(){
  56. uni.showLoading({
  57. mask: true,
  58. title: '正在重连中...'
  59. })
  60. _this.connectBlue()
  61. })
  62. // 系统信息
  63. const sysinfo = uni.getSystemInfoSync();
  64. this.platform = sysinfo.platform
  65. console.log(sysinfo,'sysinfo')
  66. },
  67. onShow() {
  68. // 获取订单状态数据字典
  69. // this.getCodeList('RUBBISH_TYPE','vuex_rubbishType')
  70. this.getUserInfo()
  71. uni.getSetting({
  72. success(res) {
  73. if(!res.authSetting['scope.userLocation']){
  74. uni.authorize({
  75. scope: 'scope.userLocation',
  76. success() {
  77. console.log('scope.userLocation success')
  78. },
  79. fail(res) {
  80. console.log('scope.userLocation fail')
  81. }
  82. })
  83. }
  84. }
  85. })
  86. },
  87. onUnload() {
  88. uni.$off('blueReConnect')
  89. },
  90. methods: {
  91. // 获取用户信息
  92. getUserInfo(){
  93. getUserInfo().then(res => {
  94. if(res.status == 200){
  95. this.$u.vuex('vuex_userData', res.data);
  96. }
  97. })
  98. },
  99. // 获取数据字典
  100. getCodeList(code,key) {
  101. getLookUpDatas({
  102. type: code
  103. }).then(res => {
  104. if (res.status == 200) {
  105. this.$u.vuex(key, res.data)
  106. }
  107. })
  108. },
  109. // 使用帮助
  110. toHelp(){
  111. uni.navigateTo({
  112. url: '/pages/help/help'
  113. })
  114. },
  115. // 去认证用户并开始称重
  116. toWork(){
  117. let _this = this
  118. // 连接成功
  119. if(this.connectStatus){
  120. // ios 设备无法获取mac地址,请手动扫描电子秤的MAC条形码
  121. if(this.platform == 'ios'&&this.iosMac==null){
  122. uni.showModal({
  123. title:'提示',
  124. content: '苹果手机无法获取mac地址,请手动扫描电子秤的MAC条形码',
  125. confirmText: '去扫描',
  126. complete(e) {
  127. if(e.confirm){
  128. uni.scanCode({
  129. success(res) {
  130. console.log(res)
  131. _this.iosMac = res.result
  132. uni.navigateTo({
  133. url: '/pages/userAuth/userAuth?macAddress=' + _this.iosMac + '&id=' + _this.deviceId
  134. })
  135. }
  136. })
  137. }
  138. }
  139. })
  140. }else{
  141. // 安卓系统直接跳转
  142. uni.navigateTo({
  143. url: '/pages/userAuth/userAuth?macAddress=' + (this.platform == 'ios' ? _this.iosMac : _this.deviceId) + '&id=' + _this.deviceId
  144. })
  145. }
  146. }else{
  147. let hasDev = this.deviceList.length
  148. if(!this.loading){
  149. uni.showModal({
  150. title:'提示',
  151. content:hasDev ? '请先连接设备':'请先绑定设备',
  152. confirmText: hasDev ? '确定':'去绑定',
  153. complete(e) {
  154. console.log(e)
  155. if(e.confirm){
  156. if(hasDev == 1){
  157. _this.connectBlue(_this.deviceList[0])
  158. }
  159. if(hasDev == 0){
  160. _this.toInit()
  161. }
  162. }
  163. }
  164. })
  165. }
  166. uni.getBluetoothDevices({
  167. success(res) {
  168. console.log(res,'getBluetoothDevices')
  169. }
  170. })
  171. }
  172. },
  173. // 初始化蓝牙
  174. toInit(){
  175. let _this = this
  176. if(this.connectStatus || this.deviceList.length > 0 || this.loading){
  177. return
  178. }
  179. uni.openBluetoothAdapter({
  180. success(res) {
  181. console.log(res, 'openBluetoothAdapter success')
  182. _this.onBluetoothAdapterStateChange()
  183. _this.loading = true
  184. setTimeout(()=>{
  185. _this.toFindDev()
  186. },500)
  187. },
  188. fail(err){
  189. console.log(err,'openBluetoothAdapter error')
  190. _this.loading = false
  191. uni.showModal({
  192. title:'提示',
  193. content: _this.platform == 'ios' ? '请开启蓝牙(如果已开启,还是无法使用,请打开系统设置->微信->蓝牙开关再试)' : '请开启手机蓝牙',
  194. showCancel: false,
  195. complete(e) {
  196. console.log(e)
  197. _this.statusStr = '请开启手机蓝牙'
  198. }
  199. })
  200. }
  201. })
  202. },
  203. toFindDev(){
  204. let _this = this
  205. _this.statusStr = '开始搜寻附近的电子秤,请确认设备已开启'
  206. uni.getBluetoothAdapterState({
  207. success(res) {
  208. console.log(res)
  209. if(res.available){
  210. // 开始搜寻附近的蓝牙外围设备
  211. _this.startBluetoothDevicesDiscovery()
  212. }else{
  213. _this.statusStr = '请开启手机蓝牙'
  214. }
  215. },
  216. fail(err) {
  217. console.log(err)
  218. }
  219. })
  220. },
  221. // 监听蓝牙状态
  222. onBluetoothAdapterStateChange(){
  223. let _this = this
  224. // 监听蓝牙适配器状态变化事件
  225. uni.onBluetoothAdapterStateChange(function (res) {
  226. console.log(res,'适配器变化')
  227. if(!res.available){
  228. // 关闭连接
  229. _this.statusStr = '蓝牙已关闭,请开启手机蓝牙'
  230. _this.loading = false
  231. if(_this.connectedDeviceId){
  232. uni.closeBLEConnection({
  233. deviceId: _this.connectedDeviceId,
  234. success: function(res) {
  235. console.log(res)
  236. _this.connectedDeviceId = null
  237. },
  238. fail(res) {
  239. console.log(res)
  240. }
  241. })
  242. }
  243. }else{
  244. if(!res.discovering && !_this.loading){
  245. _this.statusStr = '蓝牙已启用,请绑定设备'
  246. }
  247. }
  248. })
  249. },
  250. startBluetoothDevicesDiscovery(){
  251. let _this = this
  252. uni.startBluetoothDevicesDiscovery({
  253. services: [],
  254. success(res) {
  255. console.log(res,'startBluetoothDevicesDiscovery')
  256. },
  257. fail(res){
  258. console.log(res,'startBluetoothDevicesDiscovery error')
  259. }
  260. })
  261. // 监听寻找到新设备的事件
  262. uni.onBluetoothDeviceFound(function (res) {
  263. console.log(res,'onBluetoothDeviceFound')
  264. let devices = res.devices.filter(item => item.name == 'FAYA')
  265. const hasDev = _this.deviceList.find(item => item.deviceId == res.devices[0].deviceId)
  266. console.log(devices,hasDev,'devices list')
  267. if(devices.length&&!hasDev){
  268. _this.statusStr = '已发现设备'
  269. _this.deviceList = _this.deviceList.concat(res.devices)
  270. _this.loading = false
  271. }
  272. })
  273. },
  274. // 连接蓝牙设备
  275. connectBlue(item){
  276. if(this.connectStatus){
  277. return
  278. }
  279. // ios 的deviceid 不是真正的mac 地址
  280. if(item){
  281. this.deviceId = item.deviceId
  282. }
  283. this.statusStr = '正在连接设备...'
  284. this.loading = true
  285. this.createBLEConnection()
  286. },
  287. // 断开蓝牙设备
  288. closeBlue(){
  289. this.statusStr = '连接已断开,请重新绑定设备'
  290. this.closeConnect()
  291. },
  292. // 开始连接指定设备
  293. createBLEConnection(){
  294. let _this = this
  295. uni.createBLEConnection({
  296. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  297. deviceId:this.deviceId,
  298. success(res) {
  299. console.log(res)
  300. _this.connectedDeviceId = _this.deviceId
  301. // 获取连接设备的service服务
  302. setTimeout(()=>{
  303. _this.getBLEDeviceServices()
  304. },1000)
  305. },
  306. fail(err) {
  307. console.log(err,'createBLEConnection error')
  308. _this.statusStr = '设备连接失败,请检查蓝牙是否开启后重试'
  309. _this.connectStatus = false
  310. _this.loading = false
  311. uni.$emit('blueConnectCallback',0)
  312. uni.hideLoading()
  313. }
  314. })
  315. },
  316. // 获取连接设备的service服务
  317. getBLEDeviceServices(){
  318. let _this = this
  319. uni.getBLEDeviceServices({
  320. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  321. deviceId: _this.deviceId,
  322. success(res) {
  323. console.log('device services:', res.services)
  324. // _this.statusStr = '获取连接设备的service服务成功'
  325. _this.services = res.services
  326. /* 获取连接设备的所有特征值 */
  327. setTimeout(()=>{
  328. _this.getBLEDeviceCharacteristics()
  329. },500)
  330. // 停止搜索
  331. uni.stopBluetoothDevicesDiscovery({
  332. success: function(res) {
  333. console.log(res, '停止搜索')
  334. }
  335. })
  336. }
  337. })
  338. },
  339. // 获取连接设备的所有特征值
  340. getBLEDeviceCharacteristics(){
  341. let _this = this
  342. this.notifyServicweId = this.services[1].uuid
  343. uni.getBLEDeviceCharacteristics({
  344. deviceId: this.connectedDeviceId,
  345. serviceId: this.notifyServicweId,
  346. success: function(res) {
  347. console.log(res)
  348. // _this.statusStr = '获取连接设备的所有特征值成功'
  349. for (let i = 0; i < res.characteristics.length; i++) {
  350. let properties = res.characteristics[i].properties
  351. // 读id
  352. if(properties.notify&&!properties.read&&!properties.write){
  353. _this.readsId = res.characteristics[i].uuid
  354. }
  355. // 写id
  356. if(!properties.notify&&!properties.read&&properties.write){
  357. _this.writeId = res.characteristics[i].uuid
  358. }
  359. console.log(_this.readsId,_this.writeId, '蓝牙特征值 ==========')
  360. // 启用低功耗蓝牙设备特征值变化时的 notify 功能
  361. setTimeout(()=>{
  362. _this.notifyBLECharacteristicValueChange()
  363. },500)
  364. }
  365. },
  366. fail: function(res) {
  367. console.log(res)
  368. }
  369. })
  370. },
  371. // 启用低功耗蓝牙设备特征值变化时的 notify 功能
  372. notifyBLECharacteristicValueChange() {
  373. let that = this;
  374. uni.notifyBLECharacteristicValueChange({
  375. state: true,
  376. deviceId: that.connectedDeviceId,
  377. serviceId: that.notifyServicweId,
  378. characteristicId: that.readsId,
  379. success(res) {
  380. console.log(res,'notifyBLECharacteristicValueChange')
  381. that.statusStr = '连接成功,请投放称重'
  382. if(!that.connectStatus){
  383. uni.$emit('blueConnectCallback',1)
  384. that.connectStatus = true
  385. uni.hideLoading()
  386. }
  387. that.loading = false
  388. /*用来监听手机蓝牙设备的数据变化*/
  389. uni.onBLECharacteristicValueChange(function(res) {
  390. // console.log(res,'read data')
  391. that.balanceData = that.buf2string(res.value)
  392. that.$u.vuex('vuex_balanceData',that.balanceData)
  393. })
  394. // 该方法回调中可以用于处理连接意外断开等异常情况
  395. uni.onBLEConnectionStateChange(function (res) {
  396. console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
  397. if(!res.connected){
  398. uni.$emit('blueConnectClose',res)
  399. that.statusStr = '设备连接已断开,请重新连接'
  400. that.connectStatus = false
  401. that.loading = false
  402. }
  403. })
  404. },
  405. fail(res) {
  406. console.log(res, '启用低功耗蓝牙设备监听失败')
  407. that.statusStr = '设备连接失败,请点击重试'
  408. that.closeConnect()
  409. }
  410. })
  411. },
  412. /*转换成需要的格式*/
  413. buf2string(buffer) {
  414. let arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
  415. return arr.map((char, i) => {
  416. return String.fromCharCode(char);
  417. }).join('');
  418. },
  419. receiveData(buf) {
  420. return this.hexCharCodeToStr(this.ab2hex(buf))
  421. },
  422. /*转成二进制*/
  423. ab2hex (buffer) {
  424. let hexArr = Array.prototype.map.call(
  425. new Uint8Array(buffer), function (bit) {
  426. return ('00' + bit.toString(16)).slice(-2)
  427. }
  428. )
  429. return hexArr.join('')
  430. },
  431. /*转成可展会的文字*/
  432. hexCharCodeToStr(hexCharCodeStr) {
  433. let trimedStr = hexCharCodeStr.trim();
  434. let rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
  435. let len = rawStr.length;
  436. let curCharCode;
  437. let resultStr = [];
  438. for (let i = 0; i < len; i = i + 2) {
  439. curCharCode = parseInt(rawStr.substr(i, 2), 16);
  440. resultStr.push(String.fromCharCode(curCharCode));
  441. }
  442. return resultStr.join('');
  443. },
  444. // 发送数据
  445. sendData(str) {
  446. let that = this;
  447. let dataBuffer = new ArrayBuffer(3)
  448. let dataView = new DataView(dataBuffer)
  449. dataView.setUint8(0, 0x02)
  450. dataView.setUint8(1, 0x41)
  451. dataView.setUint8(2, 0x03)
  452. let dataHex = that.ab2hex(dataBuffer);
  453. this.writeDatas = that.hexCharCodeToStr(dataHex);
  454. uni.writeBLECharacteristicValue({
  455. deviceId: that.connectedDeviceId,
  456. serviceId: that.notifyServicweId,
  457. characteristicId: that.writeId,
  458. value: dataBuffer,
  459. success: function (res) {
  460. console.log('发送数据成功:' + that.writeDatas)
  461. },
  462. fail: function (res) {
  463. console.log('发送失败:' + res)
  464. },
  465. complete: function (res) {
  466. }
  467. })
  468. },
  469. // 断开设备连接
  470. closeConnect() {
  471. let that = this;
  472. if (that.connectedDeviceId) {
  473. uni.closeBLEConnection({
  474. deviceId: that.connectedDeviceId,
  475. success: function(res) {
  476. console.log(res)
  477. that.deviceId = null
  478. that.iosMac = null
  479. that.closeBluetoothAdapter()
  480. },
  481. fail(res) {
  482. console.log(res)
  483. }
  484. })
  485. } else {
  486. that.closeBluetoothAdapter()
  487. }
  488. },
  489. // 关闭蓝牙模块
  490. closeBluetoothAdapter() {
  491. let that = this;
  492. uni.closeBluetoothAdapter({
  493. success: function(res) {
  494. console.log(res,'closeBluetoothAdapter')
  495. that.connectStatus = false
  496. that.loading = false
  497. that.balanceData = ''
  498. that.deviceList = []
  499. that.deviceId = null
  500. that.iosMac = null
  501. },
  502. fail: function(err) {
  503. }
  504. })
  505. },
  506. },
  507. onUnload() {
  508. this.closeConnect()
  509. }
  510. }
  511. </script>
  512. <style lang="less">
  513. // @import url("bg.less");
  514. .bg{
  515. height: 100vh;
  516. width: 100%;
  517. position: relative;
  518. background-color: #015a50;
  519. }
  520. .bgimg{
  521. position: absolute;
  522. z-index: 100;
  523. width: 100%;
  524. height: 100vh;
  525. top: 0;
  526. left: 0;
  527. display: flex;
  528. justify-content: center;
  529. align-items: center;
  530. }
  531. .content{
  532. display: flex;
  533. align-items: center;
  534. justify-content: center;
  535. flex-direction: column;
  536. height: 100vh;
  537. width: 100%;
  538. position: absolute;
  539. z-index: 1000;
  540. }
  541. .tdrecord{
  542. position: absolute;
  543. right: 0;
  544. top: 5%;
  545. background: rgba(255,255,255,0.8);
  546. border-radius: 150rpx 0 0 150rpx;
  547. box-shadow: 2rpx 2rpx 6rpx rgba(0,0,0,0.4);
  548. padding: 15rpx 20rpx 15rpx 30rpx;
  549. font-size: 26rpx;
  550. }
  551. .cz-box{
  552. text-align: center;
  553. background: #01c9b2;
  554. border-radius: 300rpx;
  555. box-shadow: 3rpx 3rpx 10rpx rgba(0,0,0,0.4);
  556. }
  557. .cz-box > view{
  558. width: 250rpx;
  559. height: 250rpx;
  560. padding: 50rpx 50rpx 30rpx;
  561. display: flex;
  562. align-items: center;
  563. justify-content: center;
  564. flex-direction: column;
  565. }
  566. .tits{
  567. padding: 20rpx 0;
  568. color: #FFFFFF;
  569. }
  570. .devList{
  571. width: 80%;
  572. padding:10rpx 30rpx;
  573. max-height: 50vh;
  574. overflow: auto;
  575. }
  576. .bindDev{
  577. margin: 20rpx 0;
  578. padding: 15rpx 40rpx;
  579. background: rgba(19,22,30,0.8);
  580. box-shadow: 2rpx 2rpx 8rpx rgba(0,0,0,0.2);
  581. border-radius: 100rpx;
  582. color: #FFFFFF;
  583. }
  584. .devList > view{
  585. display: flex;
  586. align-items: center;
  587. color: #666666;
  588. border-radius: 20rpx;
  589. background: rgba(255,255,255,0.8);
  590. box-shadow: 2rpx 2rpx 5rpx rgba(0,0,0,0.2);
  591. margin-bottom: 20rpx;
  592. }
  593. .devList > view .names{
  594. flex-grow: 1;
  595. padding: 15rpx 40rpx;
  596. }
  597. .devList > view .texts{
  598. font-size: 24rpx;
  599. }
  600. .devList > view .btns{
  601. text-align: center;
  602. padding: 15rpx 20rpx;
  603. color: #ff5500;
  604. }
  605. .turn{
  606. animation:turn 1s linear infinite;
  607. }
  608. @keyframes turn{
  609. 0%{-webkit-transform:rotate(0deg);}
  610. 25%{-webkit-transform:rotate(90deg);}
  611. 50%{-webkit-transform:rotate(180deg);}
  612. 75%{-webkit-transform:rotate(270deg);}
  613. 100%{-webkit-transform:rotate(360deg);}
  614. }
  615. </style>