uniapp 低功耗蓝牙BLE分包

ble.js

javascript 复制代码
  // 分包写入蓝牙
  async sendWriteBLECharacteristicValue(
    deviceId,
    serviceId,
    writeCharacteristicId,
    readCharacteristicId,
    buffer,
    success, // 成功回调
    failure, // 失败回调
  ) {
    const offset = 500; // 偏移量
    let pos = 0; // 位置
    let bytes = buffer.byteLength; // 总字节
    let that = this;
    while (bytes > 0) {
      let endPos = bytes > offset ? pos + offset : pos + bytes;
      const tempBuffer = buffer.slice(pos, endPos);
      pos += offset;
      bytes -= offset;
      // 延迟发送
      await that.sendDelay(150, tempBuffer).then((buffer) => {
        that.writeBLECharacteristicValue(
          deviceId,
          serviceId,
          writeCharacteristicId,
          buffer,
          (res) => {
            if (buffer.byteLength < offset) {
              success(res);
            }
          },
          (err) => {
            failure(err);
          }
        );
      });
      if (readCharacteristicId) {
        console.log(readCharacteristicId, "读文件");
        uni.readBLECharacteristicValue({
          deviceId: deviceId,
          serviceId: serviceId,
          characteristicId: readCharacteristicId,
        });
      }
    }
  }

  sendDelay(delay, buffer) {
    return new Promise((resolve, reject) => {
      setTimeout(() => resolve(buffer), delay);
    });
  }

  writeBLECharacteristicValue(
    deviceId,
    serviceId,
    characteristicId,
    buffer,
    success,
    failure
  ) {
    plus.bluetooth.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: characteristicId,
      value: buffer,
      success(res) {
        success(res);
      },
      fail(err) {
        if (res.errCode == "10006") {
          //当前连接已断开,清空连接数据
        }
        console.log("发送失败", res);
        failure(err);
      },
    });
  }

index.vue使用分包

javascript 复制代码
this.$ble.sendWriteBLECharacteristicValue(
        deviceId, // 蓝牙地址ID
        serveiceId, // ABF0
        writeCharId, // 写入蓝牙通道 此处用ABF3
        readCharId,// 读取蓝牙返回数据通道 此处用ABF4
        buffer, // 要写入蓝牙的数据 Uint8Array
        (res) => {
          console.log("打印完成: " + JSON.stringify(res));},
        (err) => {
          console.log("打印失败: " + JSON.stringify(err));
        }
    );
相关推荐
拉不动的猪11 分钟前
# 移动端与PC端全屏的处理
前端·javascript·面试
局外人LZ25 分钟前
WXT+Vue3+sass+antd+vite搭建项目开发chrome插件
前端·chrome·vue·sass
excel30 分钟前
招幕技术人员
前端·javascript·后端
专注VB编程开发20年1 小时前
jss html5-node.nodeType 属性用于表示节点的类型
前端·js
烛阴2 小时前
Promise无法中断?教你三招优雅实现异步任务取消
前端·javascript
GUIQU.2 小时前
【Vue】单元测试(Jest/Vue Test Utils)
前端·vue.js
暮乘白帝过重山2 小时前
Ollama 在本地分析文件夹中的文件
前端·chrome·ollama
一只小风华~2 小时前
Web前端开发:CSS Float(浮动)与 Positioning(定位)
前端·css·html·html5·web
前端张三2 小时前
vue3中ref在js中为什么需要.value才能获取/修改值?
前端·javascript·vue.js
moyu842 小时前
前端从后端获取数据的流程与指南
前端