index.vue 13 KB

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