收藏
回答

调用BLEPeripheralServer.addService一直报错

框架类型 问题类型 API/组件名称 终端类型 微信版本 基础库版本
小程序 Bug BLEPeripheralServer.addService 微信iOS客户端 7.10.11 2.10.3

https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth-peripheral/BLEPeripheralServer.addService.html

下面是addService的代码:

回答关注问题邀请回答
收藏

4 个回答

  • simonla
    simonla
    2020-03-23

    可以参考这份示例代码

    const uuid1 = '000018F0-0000-1000-8000-00805F9BAAFB'
    const uuid2 = '00002AF0-0000-1000-8000-00805F9BBBFB'
    const uuid3 = '00002AF1-0000-1000-8000-00805F9BCCFB'
    
    
    // ArrayBuffer转16进制字符串示例
    function ab2hex(buffer) {
      let hexArr = Array.prototype.map.call(
        new Uint8Array(buffer),
        function (bit) {
          return ('00' + bit.toString(16)).slice(-2)
        }
      )
      return hexArr.join('');
    }
    
    
    function inArray(arr, key, val) {
      for (let i = 0; i < arr.length; i++) {
        if (arr[i][key] === val) {
          return i;
        }
      }
      return -1;
    }
    
    
    // slave/slave.js
    Page({
    
    
      /**
       * 页面的初始数据
       */
      data: {
        connects: [],
        servers: []
      },
    
    
      /**
       * 生命周期函数--监听页面加载
       */
      onLoad: function (options) {
        wx.onBLEPeripheralConnectionStateChanged(res => {
          console.log('ConnectionStateChanged', res)
          const connects = this.data.connects
          const idx = inArray(connects, 'deviceId', res.deviceId)
          if (idx >= 0) {
            connects[idx] = res
          } else {
            connects.push(res)
          }
          this.setData({ connects })
        })
      },
    
    
      openBluetoothAdapter() {
        wx.openBluetoothAdapter({
          success: (res) => {
            console.log('openBluetoothAdapter success', res)
            this.createBLEPeripheralServer()
            wx.onBluetoothAdapterStateChange(function (res) {
              console.log('onBluetoothAdapterStateChange', res.available)
            })
          },
          fail: (res) => {
            if (res.errCode === 10001) {
             console.log("ble unavailable!")
            }
          }
        })
      },
    
    
      createBLEPeripheralServer() {
        wx.createBLEPeripheralServer().then(res => {
          console.log('createBLEPeripheralServer', res)
          this.data.servers.push(res.server)
          this.server = res.server
          this.setData({ serverId: this.server.serverId })
          this.server.onCharacteristicReadRequest(res => {
            const { serviceId, characteristicId, callbackId } = res
            const buffer = new ArrayBuffer(1)
            const dataView = new DataView(buffer)
            const newValue = Math.ceil(Math.random() * 10)
            dataView.setUint8(0, newValue)
            console.log('onCharacteristicReadRequest', res, newValue)
    
    
            this.server.writeCharacteristicValue({
              serviceId,
              characteristicId,
              value: buffer,
              needNotify: true,
              callbackId
            })
          })
          this.server.onCharacteristicWriteRequest(res => {
            console.log('onCharacteristicWriteRequest', res)
            const { serviceId, characteristicId, value, callbackId } = res
            this.server.writeCharacteristicValue({
              serviceId,
              characteristicId,
              value,
              needNotify: true,
              callbackId
            })
          })
        })
      },
      closeServer() {
        this.server.close()
      },
      onConfirm(e) {
        const n = e.detail.value * 1
        const buffer = new ArrayBuffer(1)
        const dataView = new DataView(buffer)
        dataView.setUint8(0, n)
        this.server.writeCharacteristicValue({
          serviceId: uuid1,
          characteristicId: uuid2,
          value: buffer,
          needNotify: true
        })
      },
      showInput() {
        this.setData({
          input: !this.data.input
        })
      },
      addService() {
        const buffer = new ArrayBuffer(2)
        const dataView = new DataView(buffer)
        dataView.setUint8(0, 9)
        dataView.setUint8(1, 11)
        const descriptorBuffer = new ArrayBuffer(2)
        const dataView2 = new DataView(descriptorBuffer)
        dataView2.setInt8(0, 1)
        dataView2.setInt8(1, 0)
    
    
        const service = {
          uuid: uuid1,
          characteristics: [{
            uuid: uuid2,
            properties: {
              write: false,
              read: true,
              notify: true,
              indicate: false
            },
            permission: {
              readable: true,
              writeable: false,
              readEncryptionRequired: false,
              writeEncryptionRequired: false
            },
            value: buffer,
            descriptors: [{
              uuid: uuid2,
              permission: {
                write: false,
                read: true
              },
              value: descriptorBuffer
            }]
          },
          {
              uuid: uuid3,
              properties: {
                write: true,
                read: false,
                notify: false,
                indicate: false
              },
              permission: {
                readable: false,
                writeable: true,
                readEncryptionRequired: false,
                writeEncryptionRequired: false
              },
              value: buffer,
              descriptors: [{
                uuid: uuid3,
                permission: {
                  write: true,
                  read: false
                },
                value: descriptorBuffer
              }]
            }]
        }
        this.server.addService({
          service
        }).then(res => {
          console.log('add Service', res)
        })
      },
      removeService() {
        this.server.removeService({
          serviceId: uuid1
        }).then(res => {
          console.log('removeService', res)
        })
      },
      startAdvertising() {
        const buffer = new ArrayBuffer(1)
        const dataView = new DataView(buffer)
        var hex = "7E9"
        var typedArray = new Uint8Array(hex.match(/[\da-f]{2}/gi).map(function (h) {
          return parseInt(h, 16)
        }))
    
    
        this.server.startAdvertising({
          advertiseRequest: {
            connectable: true,
            deviceName: '',
            serviceUuids: [uuid1],
            manufacturerData: [{
              manufacturerId: '0x004c',
              manufacturerSpecificData: typedArray.buffer
            }]
          },
          powerLevel: 'higt'
        }).then(res => {
          console.log('startAdvertising', res)
        }, res => {
          console.log("fail: ", res)
        })
      },
      stopAdvertising() {
        this.server.stopAdvertising()
      },
    
    
      closeBluetoothAdapter() {
        wx.closeBluetoothAdapter()
      },
    
    
      /**
       * 生命周期函数--监听页面初次渲染完成
       */
      onReady: function () {
    
    
      },
    
    
      /**
       * 生命周期函数--监听页面显示
       */
      onShow: function () {
    
    
      },
    
    
      /**
       * 生命周期函数--监听页面隐藏
       */
      onHide: function () {
    
    
      },
    
    
      /**
       * 生命周期函数--监听页面卸载
       */
      onUnload: function () {
        this.data.servers.forEach(server => {
          // server.close()
        })
      },
    
    
      /**
       * 页面相关事件处理函数--监听用户下拉动作
       */
      onPullDownRefresh: function () {
    
    
      },
    
    
      /**
       * 页面上拉触底事件的处理函数
       */
      onReachBottom: function () {
    
    
      },
    
    
      /**
       * 用户点击右上角分享
       */
      onShareAppMessage: function () {
    
    
      }
    })
    
    2020-03-23
    有用
    回复 4
    • 伟鹏
      伟鹏
      2020-05-18
      有完整的demo吗,我清楚我的调用顺序有没有问题
      2020-05-18
      回复
    • 雪花的天空
      雪花的天空
      2020-12-24
      您好,楼主,我想请问写入数据怎么搞成功,我搞报错了10000  但是在初始化 添加服务 广播 然后点击按钮触发写入
      2020-12-24
      回复
    • 铭
      2023-05-27
      博主你好,安卓手机添加服务没有问题,但是苹果手机报错,就是这个错误
      2023-05-27
      回复
    • tan
      tan
      2023-08-30回复
      我也遇到了这个问题,请问解决了吗
      2023-08-30
      回复
  • Wu,Lei
    Wu,Lei
    2020-05-14

    使用示例代码 安卓没问题,ios报错:{errCode: 10000, errMsg: "addBLEPeripheralService:fail ble adapter hans't been opened or ble is unavailable."}

    2020-05-14
    有用
    回复
  • 涂耀辉
    涂耀辉
    2020-03-17
    wx.createBLEPeripheralServer({
          success (res) {
            console.log('createBLEPeripheralServer success:',res);
            res.server.addService({
              service: {
                uuid: '0000FE3C-0000-1000-8000-00805F9B34FB',
                characteristics: [{
                  uuid: '0000FE3C-0000-1000-8000-00805F9B34FC',
                  value: buffer1
                }]
              },
              success (res) {
                console.log('addService success:',res);
              },
              fail (err) {
                console.log('addService error:',err)
              }
            });
          },
          fail (err) {
            console.log('createBLEPeripheralServer error:',err)
          }
        })
    
    
    2020-03-17
    有用
    回复
  • 疯狂的小辣椒
    疯狂的小辣椒
    2020-03-17

    请具体描述问题出现的流程,并提供能复现问题的简单代码片段https://developers.weixin.qq.com/miniprogram/dev/devtools/minicode.html,另外,扫下面的小程序码,提供下扫码结果截图

    2020-03-17
    有用
    回复 2
登录 后发表内容
问题标签