index.vue 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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="toTdRecord" 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. toTdRecord(){
  111. uni.navigateTo({
  112. url: '/pages/tdRecord/tdRecord'
  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?deviceId=' + _this.iosMac
  134. })
  135. }
  136. })
  137. }
  138. }
  139. })
  140. }else{
  141. // 安卓系统直接跳转
  142. uni.navigateTo({
  143. url: '/pages/userAuth/userAuth?deviceId=' + (this.platform == 'ios' ? _this.iosMac : _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. // _this.connectedDeviceId = null
  232. // _this.closeConnect()
  233. }else{
  234. if(!res.discovering && !_this.loading){
  235. _this.statusStr = '蓝牙已启用,请绑定设备'
  236. }
  237. }
  238. })
  239. },
  240. startBluetoothDevicesDiscovery(){
  241. let _this = this
  242. uni.startBluetoothDevicesDiscovery({
  243. services: [],
  244. success(res) {
  245. console.log(res,'startBluetoothDevicesDiscovery')
  246. },
  247. fail(res){
  248. console.log(res,'startBluetoothDevicesDiscovery error')
  249. }
  250. })
  251. // 监听寻找到新设备的事件
  252. uni.onBluetoothDeviceFound(function (res) {
  253. console.log(res,'onBluetoothDeviceFound')
  254. let devices = res.devices.filter(item => item.name == 'FAYA')
  255. const hasDev = _this.deviceList.find(item => item.deviceId == res.devices[0].deviceId)
  256. console.log(devices,hasDev,'devices list')
  257. if(devices.length&&!hasDev){
  258. _this.statusStr = '已发现设备'
  259. _this.deviceList = _this.deviceList.concat(res.devices)
  260. _this.loading = false
  261. }
  262. })
  263. },
  264. // 连接蓝牙设备
  265. connectBlue(item){
  266. if(this.connectStatus){
  267. return
  268. }
  269. // ios 的deviceid 不是真正的mac 地址
  270. if(item){
  271. this.deviceId = item.deviceId
  272. }
  273. this.statusStr = '正在连接设备...'
  274. this.loading = true
  275. this.createBLEConnection()
  276. },
  277. // 断开蓝牙设备
  278. closeBlue(){
  279. this.statusStr = '连接已断开,请重新绑定设备'
  280. this.closeConnect()
  281. },
  282. // 开始连接指定设备
  283. createBLEConnection(){
  284. let _this = this
  285. uni.createBLEConnection({
  286. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  287. deviceId:this.deviceId,
  288. success(res) {
  289. console.log(res)
  290. _this.connectedDeviceId = _this.deviceId
  291. // 获取连接设备的service服务
  292. setTimeout(()=>{
  293. _this.getBLEDeviceServices()
  294. },1000)
  295. },
  296. fail(err) {
  297. console.log(err,'createBLEConnection error')
  298. _this.statusStr = '设备连接失败,请检查后重试'
  299. _this.connectStatus = false
  300. _this.loading = false
  301. uni.$emit('blueConnectCallback',0)
  302. uni.hideLoading()
  303. }
  304. })
  305. },
  306. // 获取连接设备的service服务
  307. getBLEDeviceServices(){
  308. let _this = this
  309. uni.getBLEDeviceServices({
  310. // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
  311. deviceId: _this.deviceId,
  312. success(res) {
  313. console.log('device services:', res.services)
  314. // _this.statusStr = '获取连接设备的service服务成功'
  315. _this.services = res.services
  316. /* 获取连接设备的所有特征值 */
  317. setTimeout(()=>{
  318. _this.getBLEDeviceCharacteristics()
  319. },500)
  320. // 停止搜索
  321. uni.stopBluetoothDevicesDiscovery({
  322. success: function(res) {
  323. console.log(res, '停止搜索')
  324. }
  325. })
  326. }
  327. })
  328. },
  329. // 获取连接设备的所有特征值
  330. getBLEDeviceCharacteristics(){
  331. let _this = this
  332. this.notifyServicweId = this.services[1].uuid
  333. uni.getBLEDeviceCharacteristics({
  334. deviceId: this.connectedDeviceId,
  335. serviceId: this.notifyServicweId,
  336. success: function(res) {
  337. console.log(res)
  338. // _this.statusStr = '获取连接设备的所有特征值成功'
  339. for (let i = 0; i < res.characteristics.length; i++) {
  340. let properties = res.characteristics[i].properties
  341. // 读id
  342. if(properties.notify&&!properties.read&&!properties.write){
  343. _this.readsId = res.characteristics[i].uuid
  344. }
  345. // 写id
  346. if(!properties.notify&&!properties.read&&properties.write){
  347. _this.writeId = res.characteristics[i].uuid
  348. }
  349. console.log(_this.readsId,_this.writeId, '蓝牙特征值 ==========')
  350. // 启用低功耗蓝牙设备特征值变化时的 notify 功能
  351. setTimeout(()=>{
  352. _this.notifyBLECharacteristicValueChange()
  353. },500)
  354. }
  355. },
  356. fail: function(res) {
  357. console.log(res)
  358. }
  359. })
  360. },
  361. // 启用低功耗蓝牙设备特征值变化时的 notify 功能
  362. notifyBLECharacteristicValueChange() {
  363. let that = this;
  364. uni.notifyBLECharacteristicValueChange({
  365. state: true,
  366. deviceId: that.connectedDeviceId,
  367. serviceId: that.notifyServicweId,
  368. characteristicId: that.readsId,
  369. success(res) {
  370. console.log(res,'notifyBLECharacteristicValueChange')
  371. that.statusStr = '连接成功,请投放称重'
  372. if(!that.connectStatus){
  373. uni.$emit('blueConnectCallback',1)
  374. that.connectStatus = true
  375. uni.hideLoading()
  376. }
  377. that.loading = false
  378. /*用来监听手机蓝牙设备的数据变化*/
  379. uni.onBLECharacteristicValueChange(function(res) {
  380. console.log(res,'read data')
  381. that.balanceData = that.buf2string(res.value)
  382. that.$u.vuex('vuex_balanceData',that.balanceData)
  383. })
  384. // 该方法回调中可以用于处理连接意外断开等异常情况
  385. uni.onBLEConnectionStateChange(function (res) {
  386. console.log(`device ${res.deviceId} state has changed, connected: ${res.connected}`)
  387. if(!res.connected){
  388. uni.$emit('blueConnectClose',res)
  389. that.statusStr = '设备连接已断开,请重新连接'
  390. that.connectStatus = false
  391. that.loading = false
  392. }
  393. })
  394. },
  395. fail(res) {
  396. console.log(res, '启用低功耗蓝牙设备监听失败')
  397. that.statusStr = '设备连接失败,请点击重试'
  398. that.closeConnect()
  399. }
  400. })
  401. },
  402. /*转换成需要的格式*/
  403. buf2string(buffer) {
  404. let arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
  405. return arr.map((char, i) => {
  406. return String.fromCharCode(char);
  407. }).join('');
  408. },
  409. receiveData(buf) {
  410. return this.hexCharCodeToStr(this.ab2hex(buf))
  411. },
  412. /*转成二进制*/
  413. ab2hex (buffer) {
  414. let hexArr = Array.prototype.map.call(
  415. new Uint8Array(buffer), function (bit) {
  416. return ('00' + bit.toString(16)).slice(-2)
  417. }
  418. )
  419. return hexArr.join('')
  420. },
  421. /*转成可展会的文字*/
  422. hexCharCodeToStr(hexCharCodeStr) {
  423. let trimedStr = hexCharCodeStr.trim();
  424. let rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr;
  425. let len = rawStr.length;
  426. let curCharCode;
  427. let resultStr = [];
  428. for (let i = 0; i < len; i = i + 2) {
  429. curCharCode = parseInt(rawStr.substr(i, 2), 16);
  430. resultStr.push(String.fromCharCode(curCharCode));
  431. }
  432. return resultStr.join('');
  433. },
  434. // 发送数据
  435. sendData(str) {
  436. let that = this;
  437. let dataBuffer = new ArrayBuffer(3)
  438. let dataView = new DataView(dataBuffer)
  439. dataView.setUint8(0, 0x02)
  440. dataView.setUint8(1, 0x41)
  441. dataView.setUint8(2, 0x03)
  442. let dataHex = that.ab2hex(dataBuffer);
  443. this.writeDatas = that.hexCharCodeToStr(dataHex);
  444. uni.writeBLECharacteristicValue({
  445. deviceId: that.connectedDeviceId,
  446. serviceId: that.notifyServicweId,
  447. characteristicId: that.writeId,
  448. value: dataBuffer,
  449. success: function (res) {
  450. console.log('发送数据成功:' + that.writeDatas)
  451. },
  452. fail: function (res) {
  453. console.log('发送失败:' + res)
  454. },
  455. complete: function (res) {
  456. }
  457. })
  458. },
  459. // 断开设备连接
  460. closeConnect() {
  461. let that = this;
  462. if (that.connectedDeviceId) {
  463. uni.closeBLEConnection({
  464. deviceId: that.connectedDeviceId,
  465. success: function(res) {
  466. console.log(res)
  467. that.deviceId = null
  468. that.iosMac = null
  469. that.closeBluetoothAdapter()
  470. },
  471. fail(res) {
  472. console.log(res)
  473. }
  474. })
  475. } else {
  476. that.closeBluetoothAdapter()
  477. }
  478. },
  479. // 关闭蓝牙模块
  480. closeBluetoothAdapter() {
  481. let that = this;
  482. uni.closeBluetoothAdapter({
  483. success: function(res) {
  484. console.log(res,'closeBluetoothAdapter')
  485. that.connectStatus = false
  486. that.loading = false
  487. that.balanceData = ''
  488. that.deviceList = []
  489. that.deviceId = null
  490. that.iosMac = null
  491. },
  492. fail: function(err) {
  493. }
  494. })
  495. },
  496. },
  497. onUnload() {
  498. this.closeConnect()
  499. }
  500. }
  501. </script>
  502. <style lang="less">
  503. // @import url("bg.less");
  504. .bg{
  505. height: 100vh;
  506. width: 100%;
  507. position: relative;
  508. background-color: #015a50;
  509. }
  510. .bgimg{
  511. position: absolute;
  512. z-index: 100;
  513. width: 100%;
  514. height: 100vh;
  515. top: 0;
  516. left: 0;
  517. display: flex;
  518. justify-content: center;
  519. align-items: center;
  520. }
  521. .content{
  522. display: flex;
  523. align-items: center;
  524. justify-content: center;
  525. flex-direction: column;
  526. height: 100vh;
  527. width: 100%;
  528. position: absolute;
  529. z-index: 1000;
  530. }
  531. .tdrecord{
  532. position: absolute;
  533. right: 0;
  534. top: 5%;
  535. background: rgba(255,255,255,0.8);
  536. border-radius: 150rpx 0 0 150rpx;
  537. box-shadow: 2rpx 2rpx 6rpx rgba(0,0,0,0.4);
  538. padding: 15rpx 20rpx 15rpx 30rpx;
  539. font-size: 26rpx;
  540. }
  541. .cz-box{
  542. text-align: center;
  543. background: #01c9b2;
  544. border-radius: 300rpx;
  545. box-shadow: 3rpx 3rpx 10rpx rgba(0,0,0,0.4);
  546. }
  547. .cz-box > view{
  548. width: 250rpx;
  549. height: 250rpx;
  550. padding: 50rpx 50rpx 30rpx;
  551. display: flex;
  552. align-items: center;
  553. justify-content: center;
  554. flex-direction: column;
  555. }
  556. .tits{
  557. padding: 20rpx 0;
  558. color: #FFFFFF;
  559. }
  560. .devList{
  561. width: 80%;
  562. padding:10rpx 30rpx;
  563. max-height: 50vh;
  564. overflow: auto;
  565. }
  566. .bindDev{
  567. margin: 20rpx 0;
  568. padding: 15rpx 40rpx;
  569. background: rgba(19,22,30,0.8);
  570. box-shadow: 2rpx 2rpx 8rpx rgba(0,0,0,0.2);
  571. border-radius: 100rpx;
  572. color: #FFFFFF;
  573. }
  574. .devList > view{
  575. display: flex;
  576. align-items: center;
  577. color: #666666;
  578. border-radius: 20rpx;
  579. background: rgba(255,255,255,0.8);
  580. box-shadow: 2rpx 2rpx 5rpx rgba(0,0,0,0.2);
  581. margin-bottom: 20rpx;
  582. }
  583. .devList > view .names{
  584. flex-grow: 1;
  585. padding: 15rpx 40rpx;
  586. }
  587. .devList > view .texts{
  588. font-size: 24rpx;
  589. }
  590. .devList > view .btns{
  591. text-align: center;
  592. padding: 15rpx 20rpx;
  593. color: #ff5500;
  594. }
  595. .turn{
  596. animation:turn 1s linear infinite;
  597. }
  598. @keyframes turn{
  599. 0%{-webkit-transform:rotate(0deg);}
  600. 25%{-webkit-transform:rotate(90deg);}
  601. 50%{-webkit-transform:rotate(180deg);}
  602. 75%{-webkit-transform:rotate(270deg);}
  603. 100%{-webkit-transform:rotate(360deg);}
  604. }
  605. </style>