index.vue 14 KB

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