微信小程序实现蓝牙开锁、开门、开关、指令发送成功,但蓝牙设备毫无反应、坑

这篇具有很好参考价值的文章主要介绍了微信小程序实现蓝牙开锁、开门、开关、指令发送成功,但蓝牙设备毫无反应、坑。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。


开源

wx联系本人获取源码(开源): MJ682517


html

<view>
	<view class="p_l_36 p_r_36">
		<input class="w_100_ h_80 lh_80 ta_c b_2s_eee radius_20" value="{{instructVal}}" type="text" placeholder="请输入开门指令" bindinput="bindinput" />
	</view>
	
	<view class="m_t_36 w_50_ h_90 lh_90 m_l_a m_r_a bc_409eff radius_10 color_fff ta_c" catchtap="openBluetoothAdapter">蓝牙开锁</view>
</view>

JavaScript

需要从下往上阅读,使用函数自调的方式解决API不能及时获取数据的问题,替换方案是使用定时器,但是个人觉得定时器不好,所以使用了函数自调的方式实现获取不到数据的问题。

getBluetoothDevices方法中获取deviceIdgetBLEDeviceServices方法中获取到serviceId,获取到的是数组,取数组中的uuid作为serviceId值,具体用哪个值,需要与蓝牙设备文档比对;getBLEDeviceCharacteristics方法中获取characteristicId,获取到的是数组,取数组中的uuid作为characteristicId值。

一般情况的对应的值如下
serviceId: 0000FFB0-0000-1000-8000-00805F9B34FB
notifyId: 0000FFB2-0000-1000-8000-00805F9B34FB
writeId: 0000FFB1-0000-1000-8000-00805F9B34FB
注意观察第一个横杠前面最后两位的值,不难发现规律。
写入的指令一般是以十六进制(EE03E30100)字符串的方式,最后转为二进制发送给蓝牙。

坑: 在不确定蓝牙文档是否正确的情况下,写入成功,但是蓝牙设备毫无反应,那么大概率就是写入的指令有问题,所以需要校对一下指令是否正确。

蓝牙文档需要与厂商获取。

获取蓝牙服务值方法getBLEDeviceServices
获取蓝牙特征值方法getBLEDeviceCharacteristics。特征值一般包括两个,一个代表写入值,一个代表读取值,意思是说写入的是需要把写入的特征值带上,读取的时候把读取的特征值带上。

notifyBLECharacteristicValueChange方法启用蓝牙低功耗设备特征值变化时的notify功能,订阅特征。此时传入的是读取的特征值。文章来源地址https://www.toymoban.com/news/detail-611592.html

// index.js
let timeout = undefined;

Page({
  data: {
    devices: [],
    deviceId: '',
    services: [],
    serviceId: '',
    characteristics: [],
    characteristicId: '',
    instructVal: 'EE03E30100'
  },
  // 指令输入
  bindinput({
    detail: {
      value
    }
  }) {
    this.setData({
      instructVal: value
    });
  },

  // 失败时的统一提示
  failShowToast(title = '开锁失败') {
    clearTimeout(timeout);
    timeout = undefined;
    wx.hideLoading();
    wx.showToast({
      icon: 'none',
      title
    });
  },

  /**
   * 根据不同方法名调用方法,统一定时器的触发判断,
   * 当定时器触发时,无法确定当前调用的方法是哪个
   * @param {String} fnName 
   */
  methodExecution(fnName = '') {
    if (timeout) this[fnName]();
  },

  // 关闭蓝牙模块
  closeBluetoothAdapter() {
    let that = this;

    // 关闭蓝牙模块
    wx.closeBluetoothAdapter({
      success() {},
      fail() {
        that.methodExecution('closeBluetoothAdapter');
      }
    });
  },

  // 断开与蓝牙低功耗设备的连接
  closeBLEConnection() {
    let that = this;

    // 断开与蓝牙低功耗设备的连接
    wx.closeBLEConnection({
      deviceId: that.data.deviceId,
      success() {
        that.closeBluetoothAdapter();
      },
      fail() {
        that.methodExecution('closeBLEConnection');
      }
    });
  },

  // 向蓝牙低功耗设备特征值中写入二进制数据
  writeBLECharacteristicValue() {
    let that = this;

    let str = that.data.instructVal;

    if (!str) return wx.showToast({
      title: '请输入指令',
      icon: 'none'
    });

    /* 将数值转为ArrayBuffer类型数据 */
    let typedArray = new Uint8Array(str.match(/[\da-f]{2}/gi).map((h) => parseInt(h, 16))),
      buffer = typedArray.buffer;

    // 向蓝牙低功耗设备特征值中写入二进制数据
    wx.writeBLECharacteristicValue({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: '0000FFB1-0000-1000-8000-00805F9B34FB',
      value: buffer,
      success() {
        clearTimeout(timeout);
        timeout = undefined;
        wx.hideLoading();
        wx.showToast({
          icon: 'none',
          title: '开锁成功'
        });
        // that.closeBLEConnection();
      },
      fail() {
        that.methodExecution('writeBLECharacteristicValue');
      }
    });
  },

  // 监听蓝牙低功耗设备的特征值变化事件
  onBLECharacteristicValueChange() {
    let that = this;

    // 监听蓝牙低功耗设备的特征值变化事件
    wx.onBLECharacteristicValueChange((res) => {
      if (res.value) {
        that.writeBLECharacteristicValue();
      } else {
        that.methodExecution('onBLECharacteristicValueChange');
      }
    });
  },

  // 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征
  notifyBLECharacteristicValueChange() {
    let that = this;

    // 启用蓝牙低功耗设备特征值变化时的 notify 功能,订阅特征
    wx.notifyBLECharacteristicValueChange({
      state: true,
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      characteristicId: that.data.characteristicId,
      success() {
        that.onBLECharacteristicValueChange();
      },
      fail() {
        that.methodExecution('notifyBLECharacteristicValueChange');
      }
    });
  },

  // 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)
  getBLEDeviceCharacteristics() {
    let that = this;

    // 获取蓝牙低功耗设备某个服务中所有特征 (characteristic)
    wx.getBLEDeviceCharacteristics({
      deviceId: that.data.deviceId,
      serviceId: that.data.serviceId,
      success({
        characteristics
      }) {
        that.setData({
          characteristics,
          characteristicId: '0000FFB2-0000-1000-8000-00805F9B34FB'
        }, () => that.notifyBLECharacteristicValueChange());
      },
      fail() {
        that.methodExecution('getBLEDeviceCharacteristics');
      }
    });
  },

  // 获取蓝牙低功耗设备所有服务 (service)
  getBLEDeviceServices() {
    let that = this;

    // 获取蓝牙低功耗设备所有服务 (service)
    wx.getBLEDeviceServices({
      deviceId: that.data.deviceId,
      success({
        services
      }) {
        that.setData({
          services,
          serviceId: '0000FFB0-0000-1000-8000-00805F9B34FB'
        }, () => that.getBLEDeviceCharacteristics());
      },
      fail() {
        that.methodExecution('getBLEDeviceServices');
      }
    });
  },

  // 停止搜寻附近的蓝牙外围设备
  stopBluetoothDevicesDiscovery() {
    let that = this;

    // 停止搜寻附近的蓝牙外围设备
    wx.stopBluetoothDevicesDiscovery({
      success() {
        that.getBLEDeviceServices();
      },
      fail() {
        that.methodExecution('stopBluetoothDevicesDiscovery');
      }
    });
  },

  // 连接蓝牙低功耗设备
  createBLEConnection() {
    let that = this;

    // 连接蓝牙低功耗设备
    wx.createBLEConnection({
      deviceId: that.data.deviceId,
      success() {
        that.stopBluetoothDevicesDiscovery();
      },
      fail() {
        that.methodExecution('createBLEConnection');
      }
    });
  },

  // 获取在蓝牙模块生效期间所有搜索到的蓝牙设备
  getBluetoothDevices() {
    let that = this;

    // 获取在蓝牙模块生效期间所有搜索到的蓝牙设备
    wx.getBluetoothDevices({
      success({
        devices
      }) {
        for (let i = 0; i < devices.length; i++) {
          const item = devices[i];
          if (item.name === 'YX_0A45320C78C6') {
            item.ASUUID = item.advertisServiceUUIDs[0];

            that.setData({
              devices: item,
              deviceId: item.deviceId
            }, () => that.createBLEConnection());

            break;
          }
        }

        that.methodExecution('getBluetoothDevices');
      },
      fail() {
        that.methodExecution('getBluetoothDevices');
      }
    });
  },

  // 开始搜寻附近的蓝牙外围设备
  startBluetoothDevicesDiscovery() {
    let that = this;

    // 开始搜寻附近的蓝牙外围设备
    wx.startBluetoothDevicesDiscovery({
      // 此字段会导致startBluetoothDevicesDiscovery不执行
      // services: ['YX'],
      success() {
        that.getBluetoothDevices();
      },
      fail() {
        that.methodExecution('startBluetoothDevicesDiscovery');
      }
    });
  },

  // 蓝牙开锁
  openBluetoothAdapter() {
    let that = this,
      thatData = that.data;

    if (!that.data.instructVal) return wx.showToast({
      title: '请输入指令',
      icon: 'none'
    });

    if (timeout) return wx.showToast({
      title: '加载中',
      icon: 'none'
    });

    wx.showLoading({
      title: '加载中',
      mask: true
    });

    timeout = setTimeout(() => {
      that.failShowToast('开锁失败');
    }, 1000 * 26);

    if (thatData.deviceId && thatData.serviceId && thatData.characteristicId) return that.writeBLECharacteristicValue();

    // 初始化蓝牙模块
    wx.openBluetoothAdapter({
      success() {
        that.setData({
          devices: [],
          deviceId: '',
          services: [],
          serviceId: '',
          characteristics: [],
          characteristicId: ''
        }, () => that.startBluetoothDevicesDiscovery());
      },
      fail() {
        that.failShowToast('查看手机蓝牙是否打开');
      }
    });
  },
  
  onLoad() {
  
  }
})

到了这里,关于微信小程序实现蓝牙开锁、开门、开关、指令发送成功,但蓝牙设备毫无反应、坑的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 微信小程序——实现蓝牙设备搜索及连接功能

    ✅作者简介:2022年 博客新星 第八 。热爱国学的Java后端开发者,修心和技术同步精进。 🍎个人主页:Java Fans的博客 🍊个人信条:不迁怒,不贰过。小知识,大智慧。 💞当前专栏:微信小程序学习分享 ✨特色专栏:国学周更-心性养成之路 🥭本文内容:微信小程序——实

    2024年02月08日
    浏览(37)
  • 微信小程序switch开关组件修改样式(大小,颜色)

    以上尺寸根据你的具体情况来调整

    2024年02月11日
    浏览(42)
  • 微信小程序 - 蓝牙连接

    官网 蓝牙 (Bluetooth) | 微信开放文档        蓝牙低功耗是从蓝牙 4.0 起支持的协议,与经典蓝牙相比,功耗极低、传输速度更快,但传输数据量较小。常用在对续航要求较高且只需小数据量传输的各种智能电子产品中,比如智能穿戴设备、智能家电、传感器等,应用场景

    2024年02月05日
    浏览(45)
  • 微信小程序蓝牙连接 uniApp蓝牙连接设备

     蓝牙列表期待效果  代码  js里面注意getBLEDeviceCharacteristics获取特征值的时候,极个别设备参数write,read,notify是乱来的,需要自己打单独处理,通过对应write,read,notify 为true的时候拿到对应的uuid,

    2024年02月04日
    浏览(49)
  • 微信小程序获取蓝牙权限

    要获取微信小程序中的蓝牙权限,您可以按照以下步骤进行操作: 1. 在 app.json 文件中添加以下代码:    ```    \\\"permissions\\\": {      \\\"scope.userLocation\\\": {        \\\"desc\\\": \\\"需要获取您的地理位置授权以搜索附近的蓝牙设备。\\\"      },      \\\"scope.bluetooth\\\": {        \\\"desc\\\": \\\"需要获取您

    2024年02月11日
    浏览(24)
  • 微信小程序:BLE蓝牙开发

    一、添加蓝牙权限: 1.添加蓝牙权限(工程/app.json): 二、实现扫描/连接/接收BLE设备数据: 1.实现BLE蓝牙设备扫描: 2.实现连接设备/接收数据: 3.调用例子:

    2024年02月12日
    浏览(60)
  • 微信小程序蓝牙流程及代码

    2024年02月12日
    浏览(37)
  • 微信小程序蓝牙授权完整流程

            1.1 authorize:                 提前向用户发起授权请求。调用后会立刻弹窗询问用户是否同意授权小程序使用某项功能或获取用户的某些数据,但不会实际调用对应接口。如果用户之前已经同意授权,则不会出现弹窗,直接返回成功。更多用法详见 用户授权。

    2024年04月27日
    浏览(38)
  • 微信小程序扫描蓝牙及操作(低功耗)蓝牙数据(全套流程)

    扫描蓝牙首先需要打开手机上的蓝牙。iOS只需打开蓝牙即可开始扫描蓝牙;Android需要打开蓝牙及位置信息才可以开始扫描蓝牙。下面的代码可以在扫描之前使用,用来检查是否已经很打开蓝牙及位置信息 官方地址https://developers.weixin.qq.com/miniprogram/dev/api/device/bluetooth/wx.stopBl

    2024年02月09日
    浏览(38)
  • 微信小程序-MQTT-ESP8266操作SG90开关灯

    本例仅供参考,不进行更新完善。 困难:微信小程序域名限制; ESP8266连接MQTT可参考:HTML Echarts图形统计实时显示DHT11温度(四)_我也不清楚的博客-CSDN博客_vue echarts温度计动态显示温度 ESP8266控制SG90可参考:NodeMcu(ESP8266)控制SG90_我也不清楚的博客-CSDN博客 ESP8266 DNS WEB动态配

    2024年02月12日
    浏览(45)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包