| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614 | const util = require("../../utils/util");
const plugin = requirePlugin("sdkPlugin").AiLink;
function inArray(arr, key, val) {
  
  if (!arr || !arr.length || typeof arr != 'object' || !Array.isArray(arr)) {
    return -1
  }
  for (let i = 0; i < arr.length; i++) {
    if (!key) {
      if (arr[i] == val) {
        return i
      }
    } else if (arr[i][key] === val) {
        return i
    }
  }
  return -1;
}
// ArrayBuffer转16进度字符串示例
function ab2hex(buffer, split) {
  
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join(split);
}
Page({
  data: {
    showWriteInput: false,
    devices: [
      // {
      //   deviceId: "02:03:04:05:06:07",
      //   name: "elink",
      //   localName: "elink",
      //   mac: "02:03:04:05:06:07",
      //   RSSI: -69,
      //   advertisServiceUUIDs:[
      //     "FFE0","FFC0"
      //   ],
      //   analyzeDataText:"0102003241123413"
      // }
    ],
    connected: false,
    chs: [],
    cmd: '',
    name: '',
    deviceId: null,
    historyList: [],
    state:'',
    electricity:'',
    model:'',
    skipNumber:'',
    skipTime:'',
    cumulativeNumber:'',
    finishArr:{},
    stumbleRope:[
   
  ],
    isStumbleRope:1,
    historicalRecord:'',
    isSupport:'',
    record:'',
    // isHistoricalRecord:false
  },
  onLoad: function () {
    let historyList = []
    historyList = wx.getStorageSync('historyList')
    this.setData({
      historyList,
    })
  },
  // 初始化蓝牙模块
  openBluetoothAdapter() {
   
    wx.openBluetoothAdapter({
      
      success: (res) => {
        ;
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        ;
        if (res.errCode === 10001) {
          wx.showToast({
            title: '请打开蓝牙',
            icon: "none"
          })
          wx.onBluetoothAdapterStateChange(function (res) {
            console.log('onBluetoothAdapterStateChange', res)
            if (res.available) {
              this.startBluetoothDevicesDiscovery()
            }
          })
        }
      }
    })
  },
  // 获取本机蓝牙适配器状态
  getBluetoothAdapterState() {
    
    wx.getBluetoothAdapterState({
      success: (res) => {
        ;
        console.log('getBluetoothAdapterState', res)
        if (res.discovering) {
          this.onBluetoothDeviceFound()
        } else if (res.available) {
          this.startBluetoothDevicesDiscovery()
        }
      }
    })
  },
  // 开始搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery() {
    
    if (this._discoveryStarted) {
      return
    }
    this._discoveryStarted = true
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      services: [
        "FFE0",
        // "F0A0", // BM30广播模块需加上,如使用连接模块可忽略
      ],
      success: (res) => {
        ;
        console.log('startBluetoothDevicesDiscovery success', res)
        this.onBluetoothDeviceFound()
      },
    })
  },
  // 停止搜寻附近的蓝牙外围设备
  stopBluetoothDevicesDiscovery() {
    
    wx.stopBluetoothDevicesDiscovery()
  },
  // 监听寻找到新设备的事件
  onBluetoothDeviceFound() {
   
    wx.onBluetoothDeviceFound((res) => {
      res.devices.forEach(device => {
        ;
        if (!device.name && !device.localName) {
          return
        }
        const foundDevices = this.data.devices
        const idx = inArray(foundDevices, 'deviceId', device.deviceId)
        const data = {}
        // console.log(device)
        // console.log(ab2hex(device.advertisData))
        // 此处判断是否BM30广播模块,如使用连接模块请删除此 if ,只保留 else 内容
        if (device.advertisServiceUUIDs[0].indexOf("F0A0") !== -1) {
          let parseDataRes = plugin.parseBroadcastData(device.advertisData)
          console.log(parseDataRes)
          if (parseDataRes.status == 1) {
            let analyzeData = plugin.analyzeBroadcastScaleData(parseDataRes)
            console.log(analyzeData)
            device.analyzeDataText = analyzeData.text
          }
        } else {
          let buff = device.advertisData.slice(-6)
          device.mac = new Uint8Array(buff) // 保存广播数据中的mac地址,这是由于iOS不直接返回mac地址
          let tempMac = Array.from(device.mac)
          tempMac.reverse()
          device.macAddr = ab2hex(tempMac, ':').toUpperCase()
        }
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  // 连接低功耗蓝牙设备
  createBLEConnection(e) {
   
    this._connLoading = true
    wx.showLoading({
      title: '连接中',
    })
    setTimeout(() => {
      ;
      if (this._connLoading) {
        this._connLoading = false
        wx.hideLoading()
      }
    }, 6000)
    const ds = e.currentTarget.dataset
    const index = ds.index
    // 保存当前连接的设备,注意不能从wxml的dataset中直接返回该对象,因为ArrarBuffer类型的数据无法保留
    this._device = this.data.devices[index]
    console.log(this._device)
    const deviceId = ds.deviceId
    const name = ds.name
    this.mac = ds.mac
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        ;
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        console.log("createBLEConnection:success")
        wx.stopBluetoothDevicesDiscovery()
        this.onBLEConnectionStateChange()
        this.getBLEDeviceServices(deviceId)
      },
      fail: res => {
        ;
        this._connLoading = false
        wx.hideLoading()
        wx.showToast({
          title: '连接失败',
          icon: 'none'
        })
      }
    })
    // 连接上设备就可以停止蓝牙搜索,减少功耗。
    this.stopBluetoothDevicesDiscovery()
  },
  onBLEConnectionStateChange() {
    
    wx.onBLEConnectionStateChange((res) => {
      console.log('wx.onBLEConnectionStateChange() ', res.deviceId, res.connected, res.errorCode, res.errorMsg)
      // 该方法回调中可以用于处理连接意外断开等异常情况
      // console.log(`%c device ${res.deviceId} state has changed, connected: ${res.connected}`, 'color: #F26363')
      if (!res.connected) {
        ;
        wx.showToast({
          title: '连接已断开',
          icon: 'none'
        })
        this.setData({
          connected: false,
          showWriteInput: false,
        })
      }
    })
  },
  // 断开与低功耗蓝牙设备的连接
  closeBLEConnection() {
    
    wx.closeBLEConnection({
      deviceId: this._deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      showWriteInput: false,
    })
  },
  // 获取蓝牙设备的 serviceId
  getBLEDeviceServices(deviceId) {
    
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        ;
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary && res.services[i].uuid.indexOf('FFE0') > -1) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  // 获取蓝牙设备某个服务中所有特征值(characteristic)
  getBLEDeviceCharacteristics(deviceId, serviceId) {
   
    this._deviceId = deviceId
    this._serviceId = serviceId
    this._device.serviceId = serviceId
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        ;
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        // 这部分功能在插件的 initPlugin 中已实现,如需用到其中的 uuid 也可取消注释
        // // let uuid1, uuid2, uuid3;
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.uuid.indexOf('0000FFE1') != -1) {
            this.uuid1 = item.uuid  //下发数据
          } else if (item.uuid.indexOf('0000FFE2') != -1) {
            this.uuid2 = item.uuid  //监听数据
          } else if (item.uuid.indexOf('0000FFE3') != -1) {
            this.uuid3 = item.uuid  //写入设置
          }
        }
        // 打开监听
        wx.notifyBLECharacteristicValueChange({
          deviceId,
          serviceId,
          characteristicId: this.uuid2,
          state: true,
        })
        wx.notifyBLECharacteristicValueChange({
          deviceId,
          serviceId,
          characteristicId: this.uuid3,
          state: true,
        })
        // 初始化插件
        plugin.initPlugin(res.characteristics, this._device)
        wx.onBLECharacteristicValueChange((characteristic) => {
          // 解析特征值,返回解密后的数据
          let bleData = plugin.parseBleData(characteristic.value)
          console.log('蓝牙返回',bleData)
          
         
          if (bleData.status == 0) {
            console.log("握手成功")
            this._connLoading = false
            wx.hideLoading()
            wx.showToast({
              title: '连接成功',
            })
            this.setData({
             showWriteInput : true
            })
          } else if (bleData.status == 1) {
            let payload = bleData.data //对应协议中的payload数据,可以自行解析该数据
            if (payload[0] === 0x10) {
              this.setData({
                isStumbleRope:1
              })
              let skipNumber = payload[4] * 256 + payload[3]
              let skipTime = payload[6] * 256 + payload[5]
              let cumulativeNumber = payload[8] * 256 + payload[7]
                this.setData({
                  state:(payload[1]),//状态
                  model:(payload[2]),//模式
                  electricity:(payload[9]),//电量
                  skipNumber:skipNumber,//跳绳数量
                  skipTime:skipTime,//跳绳时间
                  cumulativeNumber:cumulativeNumber//累计个数
              })
            }else if(payload[0] === 0x20){
              let str = payload[1].toString(16)
              let laststring = str.substring(str.length-1)
              if (laststring == 0) {
                var timeStamp = payload[2]+payload[3]*256+payload[4]*65536+payload[5]*16777216//时间戳
                var model = (payload[6]).toString(16)//模式
                var skipNumber = payload[8] * 256 + payload[7]//跳绳数量
                this.setData({
                  ['finishArr.timeStamp']:timeStamp,
                  ['finishArr.model']:model,
                  ['finishArr.skipNumber']:skipNumber,
                })
              }else if(laststring == 1){
                var skipTime = payload[3] * 256 + payload[2]//跳绳时间
                var cumulativeNumber = payload[5] * 256 + payload[4]//累计个数
                var averageVelocity = payload[7] * 256 + payload[6]//平均速度
                var prestissimo = payload[9] * 256 + payload[8]//最快速度
                this.setData({
                  ['finishArr.skipTime']:skipTime,
                  ['finishArr.cumulativeNumber']:cumulativeNumber,
                  ['finishArr.averageVelocity']:averageVelocity,
                  ['finishArr.prestissimo']:prestissimo,
                })
              }else{
                if (payload[2] != 65535 && payload[4] != 65535) {
                  var stumbleRopeZeroTime = payload[3] * 256 + payload[2]
                  var stumbleRopeZeroNum = payload[5] * 256 + payload[4]
                }
                if (payload[6] != 65535 && payload[8] != 65535) {
                  var stumbleRopeOneTime = payload[7] * 256 + payload[6]
                  var stumbleRopeOneNum = payload[9] * 256 + payload[8]
                }
                if (payload[10] != 65535 && payload[12] != 65535) {
                  var stumbleRopeTwoTime = payload[11] * 256 + payload[10]
                  var stumbleRopeTwoNum = payload[13] * 256 + payload[12]
                }
                let stumbleRopeOjeckt = {
                  stumbleRopeZeroTime:stumbleRopeZeroTime,
                  stumbleRopeZeroNum:stumbleRopeZeroNum,
                  stumbleRopeOneTime:stumbleRopeOneTime,
                  stumbleRopeOneNum:stumbleRopeOneNum,
                  stumbleRopeTwoTime:stumbleRopeTwoTime,
                  stumbleRopeTwoNum:stumbleRopeTwoNum,
                }
                var temp = []
                temp.push(stumbleRopeOjeckt)
                this.setData({
                  stumbleRope:temp
                })
              }
              this.setData({
                isStumbleRope:2
              })
              
            }
          }else if(bleData.status == 2){
            let payload = bleData.data
            if (payload[0].toString(16) == 'f1') {
              let historicalRecord = payload[1]//请求历史记录标识
             let isSupport = payload[2]//是否支持
             let record = payload[4] * 256 + payload[3]
             this.setData({
              historicalRecord:historicalRecord,
              isSupport:isSupport,
              record:record,
              isStumbleRope:3,
             })
            } 
          }
            const idx = inArray(this.data.chs, 'uuid', characteristic.characteristicId)
            const data = {}
            
            if (idx === -1) {
              data[`chs[${this.data.chs.length}]`] = {
                uuid: characteristic.characteristicId,
                value: ab2hex(bleData.completeData, ' ')
              }
            } else {
              data[`chs[${idx}]`] = {
                uuid: characteristic.characteristicId,
                value: ab2hex(bleData.completeData, ' ')
              }
            }
            this.setData(data)
        })
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
  },
  writeBLECharacteristicValue(buffer, uuid, deviceId, serviceId) {
    // 向蓝牙设备发送一个二进制流数据
    wx.writeBLECharacteristicValue({
      deviceId,
      serviceId,
      characteristicId: uuid,
      value: buffer,
      success(res) {
        ;
        console.log('writeBLECharacteristicValue success', res)
        console.log('下发指令==> ' + ab2hex(buffer))
      }
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()   
    this._discoveryStarted = false
  },
  //发送指令给设备
  SendInstructions(e){
    let key = e.currentTarget.dataset.index
    let cmd = ''
    switch (key) {
      case '1':
        cmd = 'a7,00,2f,05,00,67,28,9f,61,c3,7a'
        this.submitCmd(null,cmd)
        break;
      case '2':
        cmd = 'a7,00,2f,02,01,01,33,7a'
        this.submitCmd(null,cmd)
        this.setData({
          isStumbleRope:1
        })
        break;
      case '3':
        cmd = 'a7,00,2f,02,01,00,32,7a'
        this.submitCmd(null,cmd)
        break;
      case '4':
        cmd = 'a7,00,2f,02,02,01,34,7a'
        this.submitCmd(null,cmd)
        this.setData({
          isStumbleRope:1
        })
        break;
      case '5':
        cmd = 'a7,00,2f,02,02,00,33,7a'
        this.submitCmd(null,cmd)
        break;
      case '6':
        cmd = 'a7,00,2f,02,03,01,35,7a'
        this.submitCmd(null,cmd)
        this.setData({
          isStumbleRope:1
        })
        break;
      case '7':
        cmd = 'a7,00,2f,02,03,00,34,7a'
        this.submitCmd(null,cmd)
        break;
      case '8':
        cmd = 'a7,00,2f,03,04,78,00,ae,7a'
        this.submitCmd(null,cmd)
        break;
      case '9':
        cmd = 'a7,00,2f,03,05,32,00,69,7a'
        this.submitCmd(null,cmd)
        break;
      case '10':
        cmd = 'a6,02,f1,01,f4,6a'
        this.submitCmd(null,cmd)
        break;
      case '11':
        cmd = 'a7,00,2f,02,b0,01,e2,7a'
        this.submitCmd(null,cmd)
        break;
    }
    
  },
  // 指令下发
  submitCmd(e, cmd) {
    let arr = []
    let temp = []
    if (!cmd) {
      cmd = this.data.cmd
    }
    console.log(cmd)
    if(!cmd || !this.data.connected){
      return
    }
    if(cmd.indexOf(",") == -1){
      temp = cmd.split(" ")
    } else {
      temp = cmd.split(",")
    }
    let tempCmd = temp.join(' ')
    for(let i = 0; i < temp.length; i++){
      arr[i] = parseInt(temp[i],16)
    }
    // let arr = [
    //   0xA6,
    //   0x01,
    //   0x28,
    //   0x29,
    //   0x6A,
    //   //A6 01 28 29 6A
    // ]
    if(arr[0] == 0xA6){
      let len = arr[1]
      let payload = arr.slice(2, 2 + len)
      plugin.sendDataOfA6(payload)
      // let buff = new Uint8Array(arr).buffer
      // this.writeBLECharacteristicValue(buff, this.uuid3, this._deviceId, this._serviceId)
    } else if(arr[0] == 0xA7) {
      let len = arr[3]
      let payload = arr.slice(4, 4 + len)
      plugin.sendDataOfA7(payload)
    }
    let historyList = wx.getStorageSync('historyList') || []
    let idx = historyList.findIndex(item => item.cmd == tempCmd)
    if (idx < 0) {
      historyList.push({cmd: tempCmd})
    }
    this.setData({
      historyList
    })
    wx.setStorage({
      data: historyList,
      key: 'historyList',
    })
    wx.showToast({
      title: '已发送',
      icon: 'none'
    })
  },
  history_delete(e) {
    ;
    let index = e.currentTarget.dataset.index
    this.data.historyList.splice(index, 1)
    this.setData({
      historyList: this.data.historyList
    })
    wx.setStorage({
      data: this.data.historyList,
      key: 'historyList',
    })
  },
  history_copy(e) {
    ;
    let index = e.currentTarget.dataset.index
    wx.setClipboardData({
      data: this.data.historyList[index].cmd
    })
  },
  history_send(e) {
    let index = e.currentTarget.dataset.index
    let cmd = this.data.historyList[index].cmd
    this.submitCmd(null, cmd)
  },
});
 |