微信小程序蓝牙发送数据给设备,支持发送字符串

效果图:

wsml

<view>{{shuju}}</view>
<wxs module="utils">
module.exports.max = function(n1, n2) {
  return Math.max(n1, n2)
}
module.exports.len = function(arr) {
  arr = arr || []
  return arr.length
}
</wxs>
<button bindtap="openBluetoothAdapter">开始扫描</button>
<button bindtap="stopBluetoothDevicesDiscovery">停止扫描</button>
<!-- <button bindtap="closeBluetoothAdapter">结束流程</button> -->
<button bindtap="nav_map">进入地图</button>

<view class="devices_summary">已发现 {{devices.length}} 个外围设备:</view>
<scroll-view class="device_list" scroll-y scroll-with-animation>
  <view wx:for="{{devices}}" wx:key="index"
   data-device-id="{{item.deviceId}}"
   data-name="{{item.name || item.localName}}"
   bindtap="createBLEConnection" 
   class="device_item"
   hover-class="device_item_hover">
    <view style="font-size: 16px; color: #333;">{{item.name}}</view>
    <view style="font-size: 10px">信号强度: {{item.RSSI}}dBm ({{utils.max(0, item.RSSI + 100)}}%)</view>
    <view style="font-size: 10px">UUID: {{item.deviceId}}</view>
    <view style="font-size: 10px">Service数量: {{utils.len(item.advertisServiceUUIDs)}}</view>
  </view>
</scroll-view>

<view class="connected_info" wx:if="{{connected}}">
  <view>
    <text>已连接到 {{name}}</text>
    <view class="operation">
    <button wx:if="{{canWrite}}" size="mini" bindtap="writeBLECharacteristicValue">写数据</button>
    <button size="mini" bindtap="closeBLEConnection">断开连接</button>
    </view>
  </view>
  <view wx:for="{{chs}}" wx:key="index" style="font-size: 12px; margin-top: 10px;">
    <view>特性UUID: {{item.uuid}}</view>
    <view>特性值: {{item.value}}</view>
  </view>
</view>

js

const app = getApp()

function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}

// ArrayBuffer转16进度字符串示例
function ab2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}

Page({
  data: {
    devices: [],
    connected: false,
    chs: [],
  },
  onLoad(){
  },
  openBluetoothAdapter() {
    wx.openBluetoothAdapter({
      success: (res) => {
        console.log('openBluetoothAdapter success', res)
        this.startBluetoothDevicesDiscovery()
      },
      fail: (res) => {
        if (res.errCode === 10001) {
          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,
      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 = {}
        if (idx === -1) {
          data[`devices[${foundDevices.length}]`] = device
        } else {
          data[`devices[${idx}]`] = device
        }
        this.setData(data)
      })
    })
  },
  createBLEConnection(e) {
    const ds = e.currentTarget.dataset
    const deviceId = ds.deviceId
    const name = ds.name
    wx.createBLEConnection({
      deviceId,
      success: (res) => {
        this.setData({
          connected: true,
          name,
          deviceId,
        })
        this.getBLEDeviceServices(deviceId)
      }
    })
    this.stopBluetoothDevicesDiscovery()
  },
  closeBLEConnection() {
    wx.closeBLEConnection({
      deviceId: this.data.deviceId
    })
    this.setData({
      connected: false,
      chs: [],
      canWrite: false,
    })
  },
  getBLEDeviceServices(deviceId) {
    wx.getBLEDeviceServices({
      deviceId,
      success: (res) => {
        for (let i = 0; i < res.services.length; i++) {
          if (res.services[i].isPrimary) {
            this.getBLEDeviceCharacteristics(deviceId, res.services[i].uuid)
            return
          }
        }
      }
    })
  },
  getBLEDeviceCharacteristics(deviceId, serviceId) {
    wx.getBLEDeviceCharacteristics({
      deviceId,
      serviceId,
      success: (res) => {
        console.log('getBLEDeviceCharacteristics success', res.characteristics)
        for (let i = 0; i < res.characteristics.length; i++) {
          let item = res.characteristics[i]
          if (item.properties.read) {
            wx.readBLECharacteristicValue({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
            })
          }
          if (item.properties.write) {
            this.setData({
              canWrite: true
            })
            this._deviceId = deviceId
            this._serviceId = serviceId
            this._characteristicId = item.uuid
            this.writeBLECharacteristicValue()
          }
          if (item.properties.notify || item.properties.indicate) {
            wx.notifyBLECharacteristicValueChange({
              deviceId,
              serviceId,
              characteristicId: item.uuid,
              state: true,
            })
          }
        }
      },
      fail(res) {
        console.error('getBLEDeviceCharacteristics', res)
      }
    })
    // 操作之前先监听,保证第一时间获取数据
    wx.onBLECharacteristicValueChange((characteristic) => {
      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(characteristic.value)
        }
      } else {
        data[`chs[${idx}]`] = {
          uuid: characteristic.characteristicId,
          value: ab2hex(characteristic.value)
        }
      }
      // data[`chs[${this.data.chs.length}]`] = {
      //   uuid: characteristic.characteristicId,
      //   value: ab2hex(characteristic.value)
      // }
      this.setData(data)
    })
  },
  writeBLECharacteristicValue() {
    // 向蓝牙设备发送一个0x00的16进制数据
    // let buffer = new ArrayBuffer(1)     

    let data = {
      latitude: "22.761592",
      longitude: "112.978089"
    }
    var buffer = stringToBytes("23.13265,112.978089")

    console.log("发送数据:", buffer) 

    let dataView = new DataView(buffer)
    dataView.setUint8(0, Math.random() * 255 | 0)


    console.log("发送服务码:" + this._characteristicId)

    wx.writeBLECharacteristicValue({
      deviceId: this._deviceId,
      serviceId: this._serviceId,
      characteristicId: this._characteristicId,
      value: buffer,
      complete:res=>{
        this.setData({
          shuju:res
        })
      }
    })
  },
  nav_map(){
    wx.navigateTo({
      url: '../map/map',
    })
  },
  closeBluetoothAdapter() {
    wx.closeBluetoothAdapter()
    this._discoveryStarted = false
  },
})
// 字符串转byte
function stringToBytes(str) {
  var array = new Uint8Array(str.length);
  for (var i = 0, l = str.length; i < l; i++) {
    array[i] = str.charCodeAt(i);
  }
  console.log(array);
  return array.buffer;
}

css

page {
  color: #333;
}
.devices_summary {
  margin-top: 30px;
  padding: 10px;
  font-size: 16px;
}
.device_list {
  height: 300px;
  margin: 50px 5px;
  margin-top: 0;
  border: 1px solid #EEE;
  border-radius: 5px;
  width: auto;
}
.device_item {
  border-bottom: 1px solid #EEE;
  padding: 10px;
  color: #666;
}
.device_item_hover {
  background-color: rgba(0, 0, 0, .1);
}
.connected_info {
  position: fixed;
  bottom: 0;
  width: 100%;
  background-color: #F0F0F0;
  padding: 10px;
  padding-bottom: 20px;
  margin-bottom: env(safe-area-inset-bottom);
  font-size: 14px;
  min-height: 100px;
  box-shadow: 0px 0px 3px 0px;
}
.connected_info .operation {
  position: absolute;
  display: inline-block;
  right: 30px;
}

 

11

### 回答1: 要让ESP32通过蓝牙发送数据微信小程序,你可以使用ESP32内置的蓝牙模块,以及微信小程序提供的蓝牙API接口。 以下是一些基本步骤: 1. 使用Arduino IDE或其他编程工具,编写ESP32的蓝牙发送程序。例如,你可以使用Arduino蓝牙库,通过Serial通信接口将数据发送到ESP32内置的蓝牙模块。 2. 在微信小程序中,使用微信提供的蓝牙API接口,连接到ESP32的蓝牙模块,并接收来自ESP32的数据。例如,你可以使用wx.createBLEConnection()函数建立连接,使用wx.onBLECharacteristicValueChange()函数监听数据变化事件,以及使用wx.readBLECharacteristicValue()函数读取数据。 需要注意的是,蓝牙连接和数据传输的稳定性需要根据具体情况进行优化。同时,你需要确保ESP32和微信小程序之间的通信协议一致,例如数据格式、编码方式等。 ### 回答2: ESP32是一款功能强大的开发板,它支持蓝牙功能,并可以通过蓝牙将数据发送微信小程序进行接收。 在ESP32上,我们可以使用它内置的蓝牙模块来实现数据的发送。首先,我们需要在ESP32上启用蓝牙功能,并创建一个蓝牙服务,用于发送数据。可以使用ESP-IDF开发框架来实现这些功能。 接下来,在微信小程序中,我们需要使用wx.startBluetoothDevicesDiscovery函数来启用蓝牙设备的搜索功能。然后,使用wx.onBluetoothDeviceFound函数来监听蓝牙设备的发现事件,并获取到ESP32的蓝牙设备信息。 一旦微信小程序找到了ESP32的蓝牙设备,我们可以使用wx.createBLEConnection函数来建立与ESP32蓝牙设备的连接。 连接建立之后,可以使用wx.onBLEConnectionStateChange函数来监听蓝牙连接状态的变化,并在连接成功后发送数据请求到ESP32。 在ESP32上,当接收到来自微信小程序的数据请求时,可以通过蓝牙通信协议进行通信。ESP32可以将需要发送的数据打包成特定格式的数据包,并通过蓝牙发送微信小程序。 在微信小程序中,可以使用wx.onBLECharacteristicValueChange函数监听从ESP32接收到的数据,并进行处理。 总而言之,通过在ESP32上启用蓝牙功能,并在微信小程序中使用蓝牙接口进行连接和数据接收处理,我们可以实现ESP32向微信小程序发送数据的功能。这样,我们就可以利用ESP32和微信小程序相互通信,实现更多有趣的功能。 ### 回答3: ESP32是一种高集成度的蓝牙Wi-Fi芯片,可以用于无线传输数据。要在ESP32上发送数据微信小程序蓝牙接收端,需要经过以下几个步骤: 1. 配置ESP32的蓝牙模块:首先,需要在ESP32上配置蓝牙模块,使其能够与其他设备进行通信。可以使用Arduino编程语言来编写代码,在代码中引入ESP32的蓝牙库,并设置蓝牙的名称和特性。 2. 连接微信小程序蓝牙接收端:在微信小程序中,需要使用wx.getBLEDevice函数获取到ESP32的蓝牙设备对象。然后通过wx.createBLEConnection函数进行连接。 3. 发送数据:一旦连接建立,就可以使用ESP32的蓝牙发送函数发送数据。可以使用ESP32的蓝牙库提供的函数来发送字符串、数字或二进制数据。 4. 接收数据:在微信小程序中,可以通过wx.onBLECharacteristicValueChange事件监听接收到的数据。当ESP32蓝牙发送数据时,该事件将被触发,从而可以获取到接收到的数据。 需要注意的是,ESP32和微信小程序蓝牙接收端的通信需要使用相同的数据格式和通信协议。通常情况下,可以使用文本字符串作为通信格式,例如发送JSON格式的数据。 总之,要实现ESP32蓝牙发送数据微信小程序蓝牙接收端,需要先配置ESP32的蓝牙模块,然后在微信小程序中建立连接并监听接收到的数据。通过这种方式,可以实现两者之间的无线数据传输
评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

a_靖

对你有帮助吗?打赏鼓励一下?

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

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

打赏作者

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

抵扣说明:

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

余额充值