You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

750 lines
21 KiB

1 year ago
  1. // pages/bindLock/bindLock.js
  2. var util = require('../../utils/util');
  3. var util1 = require('../../utils/util1');
  4. import {
  5. BLE
  6. } from "../../utils/btls/ble";
  7. const app = getApp();
  8. const WXAPI = require('../../utils/request')
  9. import ICINLocker from '../../utils/ICINPakage/ICINLocker'
  10. const emitter = app.globalData.emitter
  11. // ArrayBuffer转16进度字符串示例
  12. function ab2hex(buffer) {
  13. var hexArr = Array.prototype.map.call(
  14. new Uint8Array(buffer),
  15. function (bit) {
  16. return ('00' + bit.toString(16)).slice(-2)
  17. }
  18. )
  19. return hexArr.join(',');
  20. }
  21. function promisify(fn, args) {
  22. return new Promise((resolve, reject) => {
  23. fn({
  24. ...(args || {}),
  25. success: (res) => resolve(res),
  26. fail: (err) => reject(err),
  27. });
  28. });
  29. }
  30. Page({
  31. /**
  32. * 页面的初始数据
  33. */
  34. data: {
  35. deviceNum: '',
  36. radio: '1',
  37. zgBlueStatus: false,
  38. bluestatus: true,
  39. selectindex: 1,
  40. info: '',
  41. deviceList:[],
  42. searchClick:false,
  43. show:false,
  44. showSelect:false,
  45. searchValue:'',
  46. pageNum: 1,
  47. pageSize: 20,
  48. zNodes: [],
  49. selectRoomName:'选择房间',
  50. allDevice:[],
  51. list:[],
  52. setRoomArr:[],
  53. confirmSelectKey:'',
  54. stoppull:false
  55. },
  56. onChange1(event) {
  57. this.setData({
  58. deviceNum: event.detail,
  59. });
  60. },
  61. onChange2(event) {
  62. this.setData({
  63. radio: event.detail,
  64. });
  65. },
  66. // 关闭弹窗
  67. onClose() {
  68. this.setData({ show: false });
  69. },
  70. onClose1() {
  71. this.setData({ showSelect: false });
  72. },
  73. // 打开弹窗
  74. selectRoom(){
  75. this.setData({ show: true });
  76. },
  77. // 房源搜索
  78. onClick() {
  79. this.getRoom2()
  80. },
  81. /**
  82. * 生命周期函数--监听页面加载
  83. */
  84. onLoad: function (options) {
  85. // app.globalData.zgBlueStatus = false
  86. let _this=this
  87. this.setData({
  88. selectindex: options.id
  89. })
  90. ICINLocker.checkTheWechatVersion()
  91. this.getTree()
  92. },
  93. // 触底触发
  94. bottomingOut(){
  95. if (!this.data.stoppull) {
  96. var num = this.data.pageNum + 1
  97. this.setData({
  98. pageNum: num
  99. })
  100. this.getRoom()
  101. }
  102. },
  103. // 搜索值
  104. onChangeSearch(event){
  105. this.setData({
  106. searchValue: event.detail
  107. })
  108. },
  109. //选择房源弹窗
  110. bindroom() {
  111. this.setData({
  112. showSelect: true
  113. });
  114. },
  115. // 获取所有设备
  116. getAllDeviceSelect(ids,callback){
  117. var data = {
  118. q: JSON.stringify({
  119. roomIds: ids
  120. })
  121. }
  122. WXAPI.getDeviceItems(data).then(res => {
  123. if(res.data.list.length>0){
  124. callback(res.data.list)
  125. }else{
  126. callback([])
  127. }
  128. }).catch(err=>{
  129. callback([])
  130. })
  131. },
  132. getTree() {
  133. var _this = this
  134. WXAPI.getTree('').then(res => {
  135. var list=res.data.sort((pre, cur)=>pre.id - cur.id)
  136. var newArr = util.uniqueArray(list, "id");
  137. var setting = {
  138. data: {
  139. simpleData: {
  140. idKey: 'id',
  141. pIdKey: 'pid'
  142. },
  143. key: {
  144. children: 'children'
  145. }
  146. }
  147. }
  148. var dataList = this.transformTozTreeFormat(setting, newArr)
  149. var selectKey = wx.getStorageSync('selectKey') || ''
  150. var selectRoomName = wx.getStorageSync('selectRoomName') || ''
  151. var pid = wx.getStorageSync('pid') || dataList[0].pid
  152. this.setData({
  153. dataList: dataList,
  154. // pid:dataList[0].pid,
  155. treeList:newArr,
  156. // selectRoomName:dataList[0].name,
  157. selectKey,selectRoomName,pid
  158. })
  159. this.getRoom()
  160. })
  161. },
  162. // 确认选择房间
  163. selectRoomId(e){
  164. this.setData({
  165. confirmSelectKey:e.currentTarget.dataset.select.id,
  166. show:false,
  167. selectRoomName:e.currentTarget.dataset.select.path
  168. })
  169. },
  170. handleSelect(e) {
  171. console.log(e)
  172. wx.showToast({
  173. title: `已选择${e.detail.item.name}`,
  174. icon: 'none',
  175. duration: 1000
  176. })
  177. wx.setStorageSync('selectKey', e.detail.item.id)
  178. wx.setStorageSync('selectRoomName', e.detail.item.name)
  179. wx.setStorageSync('pid', e.detail.item.id)
  180. this.setData({
  181. selectKey: e.detail.item.id,
  182. selectRoomName: e.detail.item.name,
  183. pid:e.detail.item.id,
  184. showSelect: false
  185. })
  186. this.getRoom2()
  187. },
  188. // 获取房间
  189. getRoom2() {
  190. var that = this
  191. var q = {
  192. ancestor: this.data.selectKey,
  193. isRoom:1,
  194. name:this.data.searchValue
  195. };
  196. console.log(q)
  197. var data = {
  198. q: JSON.stringify(q),
  199. pageNum: 1,
  200. pageSize: 20
  201. };
  202. WXAPI.getSiteList(data).then(res => {
  203. var stoppull = false
  204. if (res.data.list.list.length < 20) {
  205. stoppull = true
  206. }
  207. let setArr = []
  208. var alllist = res.data.list.list
  209. alllist.map(lt=>{
  210. setArr.push(lt.id)
  211. })
  212. this.getAllDeviceSelect(setArr,function(data){
  213. alllist.map(li=>{
  214. var name = that.findIndexArray(that.data.dataList, li.id, [])
  215. var path = ''
  216. if (name) {
  217. path = name.reverse().join('/')
  218. }
  219. li['path'] = path
  220. var device=data.filter(item=>item.roomId==li.id)[0]
  221. if(device){
  222. li.deviceNum=device.deviceNum
  223. li['battery']=device.battery
  224. li['rssi']=device.rssi
  225. li['isOnline']=device.isOnline
  226. li['manufactureId']=device.manufactureId
  227. }else{
  228. li['battery']=''
  229. li['rssi']=''
  230. li['isOnline']=''
  231. li['manufactureId']=''
  232. }
  233. })
  234. that.setData({
  235. list: alllist,
  236. stoppull,
  237. pageNum: 1
  238. })
  239. })
  240. })
  241. },
  242. findIndexArray(data,id,indexArray){
  243. let arr = Array.from(indexArray);
  244. for(let i=0,len=data.length;i<len;i++){
  245. arr.push(data[i].name);
  246. if(data[i].id===id){
  247. return arr
  248. }
  249. let children=data[i].children;
  250. if(children&&children.length){
  251. let result=this.findIndexArray(children,id,arr);
  252. if(result) return result
  253. }
  254. arr.pop()
  255. }
  256. return false
  257. },
  258. transformTozTreeFormat(setting, sNodes) {
  259. var i, l,
  260. key = setting.data.simpleData.idKey,
  261. parentKey = setting.data.simpleData.pIdKey,
  262. childKey = setting.data.key.children
  263. if (!key || key == "" || !sNodes) return [];
  264. var r = [];
  265. var tmpMap = [];
  266. for (i = 0, l = sNodes.length; i < l; i++) {
  267. tmpMap[sNodes[i][key]] = sNodes[i];
  268. }
  269. for (i = 0, l = sNodes.length; i < l; i++) {
  270. if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) {
  271. if (!tmpMap[sNodes[i][parentKey]][childKey])
  272. tmpMap[sNodes[i][parentKey]][childKey] = [];
  273. tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]);
  274. } else {
  275. r.push(sNodes[i]);
  276. }
  277. }
  278. return r;
  279. },
  280. // 获取房间
  281. getRoom() {
  282. var that= this
  283. var q = {
  284. ancestor: this.data.pid,
  285. isRoom:1,
  286. name:this.data.searchValue
  287. };
  288. var data = {
  289. q: JSON.stringify(q),
  290. pageNum: this.data.pageNum,
  291. pageSize: this.data.pageSize
  292. };
  293. WXAPI.getSiteList(data).then(res => {
  294. var stoppull = false
  295. if (res.data.list.list.length < 20) {
  296. stoppull = true
  297. }
  298. let setArr = []
  299. var alllist = this.data.list.concat(res.data.list.list)
  300. alllist.map(lt=>{
  301. setArr.push(lt.id)
  302. })
  303. this.getAllDeviceSelect(setArr,function(data){
  304. alllist.map(li=>{
  305. var name = that.findIndexArray(that.data.dataList, li.id, [])
  306. var path = ''
  307. if (name) {
  308. path = name.reverse().join('/')
  309. }
  310. li['path'] = path
  311. var device=data.filter(item=>item.roomId==li.id)[0]
  312. if(device){
  313. li.deviceNum=device.deviceNum
  314. li['battery']=device.battery
  315. li['rssi']=device.rssi
  316. li['isOnline']=device.isOnline
  317. li['manufactureId']=device.manufactureId
  318. }else{
  319. li['battery']=''
  320. li['rssi']=''
  321. li['isOnline']=''
  322. li['manufactureId']=''
  323. }
  324. })
  325. that.setData({
  326. list: alllist,
  327. setRoomArr:setArr,
  328. stoppull
  329. })
  330. })
  331. })
  332. },
  333. getAllDevice(deviceNum,callback){
  334. var data = {
  335. q: JSON.stringify({
  336. deviceNum: deviceNum
  337. })
  338. }
  339. WXAPI.getDeviceItems(data).then(res => {
  340. if(res.data.list.length>0){
  341. callback(res.data.list)
  342. }else{
  343. callback([])
  344. }
  345. }).catch(err=>{
  346. callback([])
  347. })
  348. },
  349. searchDevicesMethods(){
  350. var that = this;
  351. wx.showLoading({
  352. title: '正在搜索',
  353. // mask: true
  354. })
  355. this.setData({
  356. searchClick:false
  357. })
  358. wx.openBluetoothAdapter({
  359. success: function (res) {
  360. wx.startBluetoothDevicesDiscovery({
  361. success: function (res) {
  362. wx.getBluetoothDevices({
  363. success: function (res) {
  364. wx.hideLoading()
  365. if(that.data.selectindex==1){
  366. var deviceList=[]
  367. res.devices.map(li=>{
  368. var status=li.name.indexOf('yxwl')
  369. if(status!=-1){
  370. that.getAllDevice(li.name,function(data){
  371. if(data.length>0){
  372. li.roomName = data[0].roomName
  373. deviceList.push(li)
  374. }else{
  375. li.roomName = ''
  376. deviceList.push(li)
  377. }
  378. })
  379. }
  380. })
  381. setTimeout(()=>{
  382. that.setData({
  383. deviceList
  384. })
  385. },1000)
  386. }else if(that.data.selectindex==2||that.data.selectindex==3){
  387. var deviceList=[]
  388. res.devices.map(li=>{
  389. var status=li.name.indexOf('ICIN_')
  390. if(status!=-1){
  391. that.getAllDevice(li.name,function(data){
  392. if(data.length>0){
  393. li.roomName = data[0].roomName
  394. deviceList.push(li)
  395. }else{
  396. li.roomName = ''
  397. deviceList.push(li)
  398. }
  399. })
  400. deviceList.push(li)
  401. }
  402. })
  403. setTimeout(()=>{
  404. that.setData({
  405. deviceList
  406. })
  407. },1000)
  408. }else if(that.data.selectindex==4){
  409. var deviceList=[]
  410. console.log(res);
  411. res.devices.map(it=>{
  412. console.log(it);
  413. var status=it.name.indexOf('WSL_')
  414. if(status!=-1){
  415. if (it.RSSI != 127) {
  416. if (it.advertisData != null) {
  417. it.adData = util1.ab2hex(it.advertisData)
  418. if (it.adData.length > 10) {
  419. var macStr = it.adData.substring(4, 16).toUpperCase()
  420. //console.log('macStr', macStr)
  421. it.mac = macStr.substr(10, 2) + ':' + macStr.substr(8, 2) + ':' + macStr.substr(6, 2) + ':' + macStr.substr(4, 2) + ':' + macStr.substr(2, 2) + ':' + macStr.substr(0, 2)
  422. if (it.adData.substring(1, 2) == '1') {
  423. it.isLightOn = true
  424. it.textColor = 'green'
  425. } else {
  426. it.isLightOn = false
  427. it.textColor = 'black'
  428. }
  429. if (it.adData.substring(3, 4) == '1') {
  430. it.textColor = 'pink'
  431. it.isBind = true
  432. } else {
  433. it.isBind = false
  434. }
  435. // deviceList.push(it)
  436. //console.log(it)
  437. }
  438. } else {
  439. it.textColor = 'black'
  440. }
  441. console.log(it)
  442. var lockModel = util1.getLockModel(it.name)
  443. it.lockType = util1.getLockType(lockModel)
  444. if(that.data.searchClick){
  445. wx.navigateTo({
  446. url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + it.name + '&selectindex=' + that.data.selectindex+'&connectedDeviceId='+ it.deviceId+'&name='+ it.name+'&mac=' + it.mac,
  447. })
  448. }else{
  449. deviceList.push(it)
  450. }
  451. app.addDeviceWithDevName(it.name, it)
  452. }
  453. }
  454. })
  455. that.setData({
  456. deviceList
  457. })
  458. }
  459. console.log(res)
  460. }
  461. })
  462. },
  463. fail:function(res){
  464. wx.hideLoading({
  465. success: (res) => {
  466. wx.showToast({
  467. title: '请重新搜索设备',
  468. duration:2000,
  469. icon:'none'
  470. })
  471. },
  472. })
  473. }
  474. })
  475. },
  476. fail: function (res) {
  477. console.log('请打开蓝牙和定位功能')
  478. wx.hideLoading({
  479. success: (res) => {
  480. wx.showToast({
  481. title: '请打开蓝牙和定位功能',
  482. duration:2000,
  483. icon:'none'
  484. })
  485. },
  486. })
  487. }
  488. })
  489. },
  490. searchBlueButton(e) {
  491. var deviceId=e.currentTarget.dataset.select.name
  492. this.setData({
  493. deviceNum:deviceId
  494. })
  495. this.linkBule()
  496. },
  497. // 扫描
  498. scanning() {
  499. var that = this
  500. wx.showLoading({
  501. title: '加载中',
  502. mask: true
  503. });
  504. wx.scanCode({
  505. success(res) {
  506. var deviceNum = ''
  507. if (res.result.indexOf('&') != -1) {
  508. deviceNum = res.result.split('&')[0]
  509. }else if(res.result.indexOf('WSL') != -1){
  510. deviceNum = res.result
  511. }else if (res.result.indexOf('_')) {
  512. deviceNum = "ICIN_" + res.result.split('_')[0]
  513. }
  514. that.setData({
  515. deviceNum: deviceNum,
  516. bluestatus: true
  517. })
  518. wx.hideLoading()
  519. },
  520. fail(res) {
  521. wx.hideLoading()
  522. }
  523. })
  524. },
  525. linkBule() {
  526. wx.stopBluetoothDevicesDiscovery()
  527. wx.closeBluetoothAdapter()
  528. if (this.data.deviceNum == '') {
  529. wx.hideLoading()
  530. wx.showToast({
  531. title: '请输入锁号',
  532. duration: 2000,
  533. icon: 'none'
  534. })
  535. } else {
  536. // wx.navigateTo({
  537. // url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
  538. // })
  539. // return
  540. if (this.data.selectindex == 1) {
  541. // wx.navigateTo({
  542. // url: '/pages/Bluetooth1/Bluetooth1?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
  543. // })
  544. // return
  545. this.startconnect()
  546. }else if( this.data.selectindex == 4){
  547. this.searchDevicesMethods()
  548. this.setData({
  549. searchClick:true
  550. })
  551. } else if (this.data.selectindex == 2||this.data.selectindex == 3) {
  552. // wx.navigateTo({
  553. // url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
  554. // })
  555. // return
  556. this.goBlue()
  557. }
  558. }
  559. },
  560. ConnectTo: function(e) {
  561. var that = this
  562. console.log('ConnectTo', e.currentTarget.dataset.select)
  563. var bleDevice = app.getDeviceByDevName(e.currentTarget.dataset.select)
  564. console.log('bleDevice', bleDevice)
  565. // wx.navigateTo({
  566. // url: '../lockFun/lockFun?connectedDeviceId=' + bleDevice.deviceId + '&name=' + bleDevice.name + '&mac=' + bleDevice.mac
  567. // })
  568. wx.navigateTo({
  569. url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + bleDevice.name + '&selectindex=' + this.data.selectindex+'&connectedDeviceId='+ bleDevice.deviceId+'&name='+ bleDevice.name+'&mac=' + bleDevice.mac,
  570. })
  571. return
  572. },
  573. startconnect() {
  574. wx.showLoading({
  575. title: "连接中",
  576. // mask: true
  577. })
  578. const ble = new BLE(this.data.deviceNum, emitter)
  579. app.globalData.ble = ble
  580. this.watchBLE()
  581. app.globalData.ble.init()
  582. },
  583. watchBLE() {
  584. var that = this
  585. if (app.globalData.ble) {
  586. app.globalData.ble.listen(res => {
  587. if (res.type == 'connect') {
  588. if (res.data == "未打开适配器") {
  589. wx.hideLoading()
  590. wx.showModal({
  591. title: "提示",
  592. content: "请检查手机蓝牙和定位功能是否打开?",
  593. showCancel: false,
  594. confirmText: "确定",
  595. success(res) {}
  596. });
  597. } else {
  598. if (res.data == '蓝牙已连接') {
  599. this.data.info = res.data
  600. app.globalData.bleStatus = res.data
  601. wx.navigateTo({
  602. url: '/pages/Bluetooth1/Bluetooth1?&deviceNum=' + this.data.deviceNum + '&selectindex=' + this.data.selectindex,
  603. })
  604. }
  605. }
  606. }
  607. })
  608. }
  609. },
  610. goBlue() {
  611. var that = this
  612. wx.showLoading({
  613. title: '连接中',
  614. // mask: true
  615. })
  616. wx.removeStorageSync("connectedDeviceId")
  617. ICINLocker.scanDevices(this.data.deviceNum)
  618. .then((res) => {
  619. console.log(res)
  620. if (res.status == 0) {
  621. //成功找到蓝牙情况下进行锁连接
  622. app.globalData.blueDeviceId = res.deviceId
  623. console.log(app.globalData.blueDeviceId, 'blueDeviceId')
  624. ICINLocker.connect(res.deviceId, false) // 此处 deviceId 存起来,当断开连接时使用
  625. .then((res) => {
  626. if (res.status === 0) {
  627. wx.hideLoading()
  628. if(this.data.confirmSelectKey){
  629. wx.navigateTo({
  630. url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&type=' + this.data.radio+'&selectindex=' + this.data.selectindex+'&selectKey='+this.data.confirmSelectKey+'&selectRoomName='+this.data.selectRoomName,
  631. })
  632. }else{
  633. wx.navigateTo({
  634. url: '/pages/Bluetooth/Bluetooth?&deviceNum=' + this.data.deviceNum + '&type=' + this.data.radio+'&selectindex=' + this.data.selectindex,
  635. })
  636. }
  637. //此处成功连接锁
  638. wx.showToast({
  639. title: res.statusReason,
  640. duration: 1000,
  641. icon: 'none'
  642. })
  643. } else {
  644. var msg = ''
  645. switch (res.errCode) {
  646. case 10001:
  647. msg = '调用失败,请打开蓝牙!';
  648. break;
  649. }
  650. wx.showToast({
  651. title: msg,
  652. duration: 2000,
  653. icon: 'none'
  654. })
  655. //此处处理返回值不为成功(0)的情况
  656. }
  657. }).catch((res) => {
  658. wx.hideLoading()
  659. wx.showToast({
  660. title: '连接错误',
  661. duration: 2000,
  662. icon: 'none'
  663. })
  664. console.log(res, '失败')
  665. })
  666. }
  667. })
  668. .catch((res) => {
  669. if (res.status == 1) {
  670. if (res.statusReason.errCode == 10001) {
  671. wx.hideLoading()
  672. wx.showModal({
  673. title: "提示",
  674. content: "请检查手机蓝牙和定位功能是否打开?",
  675. showCancel: false,
  676. confirmText: "确定",
  677. success(res) {}
  678. });
  679. } else {
  680. if (!app.globalData.zgBlueStatus && that.data.bluestatus) {
  681. that.goBlue()
  682. } else {
  683. wx.hideLoading()
  684. }
  685. }
  686. }
  687. })
  688. },
  689. onChange(event) {
  690. // event.detail 为当前输入的值
  691. this.setData({
  692. deviceNum: event.detail
  693. })
  694. },
  695. /**
  696. * 生命周期函数--监听页面初次渲染完成
  697. */
  698. onReady: function () {
  699. app.globalData.zgBlueStatus = false
  700. },
  701. /**
  702. * 生命周期函数--监听页面显示
  703. */
  704. onShow: function () {
  705. },
  706. /**
  707. * 生命周期函数--监听页面隐藏
  708. */
  709. onHide: function () {
  710. this.setData({
  711. bluestatus: false
  712. })
  713. },
  714. closeblue() {
  715. app.globalData.ble.close()
  716. app.globalData.bleStatus = false
  717. },
  718. /**
  719. * 生命周期函数--监听页面卸载
  720. */
  721. onUnload: function () {
  722. this.closeblue()
  723. },
  724. /**
  725. * 页面相关事件处理函数--监听用户下拉动作
  726. */
  727. onPullDownRefresh: function () {
  728. },
  729. /**
  730. * 页面上拉触底事件的处理函数
  731. */
  732. onReachBottom: function () {
  733. },
  734. /**
  735. * 用户点击右上角分享
  736. */
  737. onShareAppMessage: function () {
  738. }
  739. })