微信小程序搜索蓝牙设备

上一篇 微信小程序初始化蓝牙模块

本片介绍微信小程序怎么去搜索蓝牙设备。

一、data 里面定义三个参数:isStartBluetoothdeviceDiscovery是开已经开始搜索蓝牙设备,blueName是指定要搜索蓝牙设备名(可以指定多个)主要是过滤蓝牙设备,bluetoothDeviceList是搜索到的蓝牙设备的列表用于页面展示搜索到的蓝牙设备

isStartBluetoothdeviceDiscovery: false, //是否开始搜索蓝牙设备

blueName:['S5-4'], //指定搜索蓝牙名称

bluetoothDeviceList:[],  //搜索的蓝牙设备列表

deviceId:'', //连接的蓝牙设备id

二、onload 中自定义搜索到新设备的事件的全部监听 onBluetoothDeviceFoundCallback 代码,这里需要注意到一个问题:安卓和IOS的 搜索到的蓝牙设备ID不一样的问题,我的代码是做了特殊处理显示成一样的MAC地址

    //搜索到新设备的事件的全部监听
    Bluetooth.onBluetoothDeviceFoundCallback = function(res){
      console.log('监听搜索到新设备的事件', res);
      Bluetooth.getBluetoothDevices().then(
        function(res) {
          //console.log('获取蓝牙设备列表', res);
          // 获取设备MAC地址
          //获取设备基础信息
          let deviceInfo = wx.getDeviceInfo();
          let platform = deviceInfo.platform;
          let iosDevice = (platform=='ios');
          var bluetoothDeviceList = that.data.bluetoothDeviceList; //数据列表,可以自己定义
          for (var i = 0; i < res.devices.length; i++) {
            let device = res.devices[i];
            if (device) {
              let deviceName = device.name || device.localName;
              let isTrue = false;
              let blueName = that.data.blueName;
              if(blueName.length>0)
              {
                blueName.forEach(item=>{
                  if(deviceName.startsWith(item))
                  {
                    isTrue = true;
                  }
                })
              }
              else
              {
                isTrue = true;
              }
              if (isTrue)
              {
                // 获取设备MAC地址(这里保持IOS和安卓一致)
                let deviceMac = '';
                if(iosDevice)
                {
                  if(deviceName.startsWith('S5-4'))
                  {
                    deviceMac = util.ab2hex(device.advertisData.slice(2, 8), ':').toUpperCase();
                  }
                }
                else
                {
                  deviceMac = device.deviceId
                }
                const idx = util.inArray(bluetoothDeviceList, 'deviceId', device.deviceId)
                if (idx === -1) {
                  device.deviceMac = deviceMac;
                  bluetoothDeviceList.push(device);
                } 
                console.log('设备已搜索到', deviceName, deviceMac, device, util.ab2hex(device.advertisData, ':'));
                that.setData({ bluetoothDeviceList: bluetoothDeviceList });
              }
            }
          }
        }
      )
    };

 三、搜索设备和停止搜索按钮事件的代码

  //搜索设备
  startBluetoothdeviceDiscovery(){
    var that=this;
    that.seeConsole('开始搜索设备');
    Bluetooth.startBluetoothdeviceDiscovery().then(
      function(res){
        that.setData({
          isStartBluetoothdeviceDiscovery:true
        });
        //监听搜索到新设备的事件
        Bluetooth.onBluetoothDeviceFound();
      },
      function(err){
        
      }
    );
  },
  //搜索设备 按钮事件
  searchDeviceClick()
  {
    var that=this;
    Bluetooth.CheckSystemInfo().then(res=>{
      if(res)
      {
        that.setData({
          bluetoothDataList:[]
        })
        that.startBluetoothdeviceDiscovery();
      }
    });
  },
  //停止搜索
  stopBluetoothDevicesDiscovery()
  {
    var that=this;
    that.seeConsole('停止搜索设备')
    Bluetooth.stopBluetoothDevicesDiscovery().then(
      function(res){
        that.setData({
          isBluetoothDevicesDiscovery: false
        });
        //移除搜索到新设备的事件的全部监听函数
        Bluetooth.offBluetoothDeviceFound();
      },
      function(err){
        
      }
    );
  },
  //停止搜索 按钮事件
  stopSearchDeviceClick()
  {
    var that=this;
    let isStartBluetoothdeviceDiscovery = that.data.isStartBluetoothdeviceDiscovery;
    if(isStartBluetoothdeviceDiscovery)
    {
      Bluetooth.CheckSystemInfo().then(res=>{
        if(res)
        {
          that.stopBluetoothDevicesDiscovery();
        }
      });
    }
    else
    {
      wx.showModal({
        content: '请先点击搜索设备',
        showCancel:false,
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确定');
          } 
        }
      });
    }
  },
  //选择设备
  selectDevice(e){
    var deviceId = e.currentTarget.dataset.id;
    //console.log(deviceId);
    this.setData({deviceId:deviceId});
  },

四、页面相关代码

 <view class="event-bar" list-item>
    <view class="view_left">
      <button class="btn_bg" bindtap="searchDeviceClick">搜索设备</button>
    </view>
    <view class="view_right">
      <button class="btn_bg" bindtap="stopSearchDeviceClick">停止搜索</button>
    </view>
  </view>
  <view class="scan-list" list-item>
    <view class="list_view {{item.deviceId==deviceId?'list_view_select':'list_view_no'}}" wx:for="{{bluetoothDeviceList}}" wx:for-item="item" wx:key="unique" data-id="{{item.deviceId}}" bindtap="selectDevice">
      <view class='list-group'>
        <view class='list-left'>
          <image src='../../images/bluetooth.png' class='img'></image>
        </view>
        <view class='list-right'>
          <view>
            <view class='title'>
              <view class="name">{{item.name? item.name : item.localname}}</view>
              <view class="rssi">信号强度: {{(item.RSSI + 100)>0?(item.RSSI + 100):0}}%</view>
            </view>
            <view class='title'>{{item.model}}</view>
          </view>
          <view class='desc'>{{item.deviceMac}}</view>
        </view>
      </view>
    </view>
  </view>

五、样式相关代码

.event-bar{
  display: flex;
  flex-flow: nowrap;
  justify-content: center;
}
.btn_bg {
  width: 100%!important;
  background-color: #f8f8f8;
  color: #000;
  text-align: center;
  padding: 10rpx;
  border:1rpx #ccc solid;
}
.view_left{
  flex-grow: 1;
  padding: 10rpx;
}
.view_right{
  flex-grow: 1;
  padding: 10rpx;
}
.scan-list {
  display: flex;
  flex-direction: column;
  width: 100%;
}

.list_view{
  border-radius: 20rpx;
  /* border: 1rpx solid #ccc; */
  margin: 5rpx 5rpx 0rpx 5rpx;
}

.list_view_no {
  background-color: white;
}
.list_view_select {
  background-color: rgb(235, 231, 231);
}

.list-group {
  display: flex;
  padding: 5px 5px;
  align-items: center;
}

.list-left {
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  font-size:12px;
}
.list-right {
  flex:1;
}

.radio_group{
  display: flex;
  flex-direction: column;
}
.radio-label{
  display: flex;
  padding: 5px 0px;
}
.radio-text{
  flex: 1;
  font-size: 12px;
  margin-top: 5px;
  color: #7a7a7a;
}
.img{
  width:70%;
  height:70%;
 }
.title {
  font-size: 14px;
  /* display: -webkit-box;
  overflow: hidden;
  -webkit-line-clamp: 2;
  text-overflow: ellipsis;
  -webkit-box-orient: vertical; */
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
}
.name {
  font-weight: bold;
}
.rssi {
  color: #999;
}
.desc {
  font-size: 12px;
  color: #7a7a7a;
  margin-top: 3px;
}

下一篇将继续介绍 微信小程序连接蓝牙设备

  • 11
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
微信小程序可以通过使用微信小程序蓝牙接口来读取蓝牙设备返回的数据。下面是一个简单的示例代码,演示了如何读取蓝牙设备的数据: ```javascript // 初始化蓝牙适配器 wx.openBluetoothAdapter({ success: function (res) { // 监听蓝牙适配器状态变化事件 wx.onBluetoothAdapterStateChange(function (res) { console.log('蓝牙适配器状态变化', res) }) // 开始搜索附近的蓝牙设备 wx.startBluetoothDevicesDiscovery({ success: function (res) { // 监听寻找到新设备的事件 wx.onBluetoothDeviceFound(function (devices) { console.log('新设备', devices) // 如果找到目标设备,停止搜索 if (devices.deviceId === '目标设备的deviceId') { wx.stopBluetoothDevicesDiscovery() } }) } }) } }) // 连接蓝牙设备 wx.createBLEConnection({ deviceId: '目标设备的deviceId', success: function (res) { // 监听蓝牙连接状态改变事件 wx.onBLEConnectionStateChange(function (res) { console.log('蓝牙连接状态改变', res) }) // 获取蓝牙设备的服务列表 wx.getBLEDeviceServices({ deviceId: '目标设备的deviceId', success: function (res) { // 遍历服务列表 for (let i = 0; i < res.services.length; i++) { let service = res.services[i] // 获取服务的特征值列表 wx.getBLEDeviceCharacteristics({ deviceId: '目标设备的deviceId', serviceId: service.uuid, success: function (res) { // 遍历特征值列表 for (let j = 0; j < res.characteristics.length; j++) { let characteristic = res.characteristics[j] // 监听特征值变化事件 wx.onBLECharacteristicValueChange(function (res) { console.log('特征值变化', res) // 获取特征值的数据 let data = new Uint8Array(res.value) console.log('接收到的数据', data) }) // 读取特征值的数据 wx.readBLECharacteristicValue({ deviceId: '目标设备的deviceId', serviceId: service.uuid, characteristicId: characteristic.uuid, success: function (res) { console.log('读取特征值数据成功', res) } }) } } }) } } }) } }) ``` 请注意,以上代码只是一个示例,实际情况可能会有所不同。具体实现需要根据蓝牙设备的特性和协议进行调整。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wsk198726

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值