[uniapp]APP端低功耗蓝牙打印

需求

连接低功耗蓝牙设备,打印已有的记录内容

思路

Part1:通过uniapp自带的API连接上蓝牙设备,获取到设备的各种信息。
Part2:通过uniapp的API写入字符串与指令

Part1

蓝牙连接代码参考

	 data() {
	 return {
	 		//* 设备数组
		     deviceList: [],
		     //* 定义一个对象存储设备信息
     		 deviceInfo: {},
     		 //* 默认蓝牙连接状态
      		blueConnFlag: false,
		}
	 }
	 //* 蓝牙连接方法
	    //* 蓝牙初始化
    onBlue() {
      uni.openBluetoothAdapter({
        success: (res) => {
          //监听寻找到新设备的事件
          this.findDevice();
          //监听本机蓝牙适配器状态变化事件
          this.onStatus();
        },
        fail: (err) => {
          uni.$u.toast("蓝牙开启失败");
        },
      });
    },
    //* 找寻蓝牙设备
    findDevice() {
      console.log("监听寻找到新设备的事件---------------");
      //监听寻找到新设备的事件
      uni.onBluetoothDeviceFound((devices) => {
        const { name, deviceId } = devices.devices[0];
        if (name == "") return;
        this.deviceList.push({
          name,
          deviceId,
          services: [],
        });
        //* 去重
        this.deviceList = this.deviceList.filter((item) => item);
      });
    },
    //* 监听蓝牙状态
    onStatus() {
      uni.getBluetoothAdapterState({
        success: function (res) {
          console.log(res, "蓝牙搜索状态为");
          //本机蓝牙开启时
          if (res.available) {
            //如在正在搜索设备,则停止搜索
            if (res.discovering) {
              uni.stopBluetoothDevicesDiscovery();
            }
            //搜索蓝牙
            //开始搜寻附近的蓝牙外围设备
            uni.startBluetoothDevicesDiscovery();
          } else {
            console.log("本机蓝牙不可用");
          }
        },
      });
    },

    //* 连接蓝牙
    onLink(item) {
      if (this.deviceInfo.name && this.deviceInfo.deviceId) {
        const { deviceId } = item;
        console.log("连接蓝牙---------------" + deviceId);
        //连接低功耗蓝牙设备。
        uni.createBLEConnection({
          deviceId: deviceId,
          complete: (res) => {
            console.log("创建连接的回调", res);
            if (res.errMsg != "createBLEConnection:ok") return;
            //连接设备时,需断开本机连接设备
            // uni.closeBLEConnection({
            //   deviceId,
            // });
            // this.connId = deviceId;
            // this.currDev = item;
            setTimeout(() => {
              //获取蓝牙设备所有服务(service)
              this.getBLEServices(deviceId);
            }, 2000);
          },
        });

        //连接成功 关闭搜索
        uni.stopBluetoothDevicesDiscovery();
        setTimeout(() => {
          this.blueConnFlag = true;
        }, 1000);
      } else {
        uni.$u.toast("请选择蓝牙设备进行连接!");
      }
    },
    //* 断开蓝牙
    outLink(item) {
      const { deviceId } = item;
      uni.closeBLEConnection({
        deviceId,
        success: (res) => {
          uni.$u.toast("蓝牙设备已关闭!");
          this.deviceInfo = {};
          this.blueConnFlag = false;
        },
        fail: (err) => {
          uni.$u.toast("关闭设备失败,请重新尝试!");
        },
      });
    },
    //* 连接设备
    getBLEServices(deviceId) {
      uni.getBLEDeviceServices({
        // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
        deviceId: deviceId,
        complete: (res) => {
          // console.log(res, "连接设备获取到的res");
          const { services } = res;
          if (services) {
            services.forEach((item) => {
              const { uuid } = item;
              uni.getBLEDeviceCharacteristics({
                // 这里的 deviceId 需要已经通过 createBLEConnection 与对应设备建立链接
                deviceId: deviceId,
                // 这里的 serviceId 需要在 getBLEDeviceServices 接口中获取
                serviceId: uuid,
                success: (res) => {
                  // console.log("获取的特征值为:", res);
                  const { characteristics } = res;
                  for (let block of characteristics) {
                    if (!block.properties.write) return;

                    for (let i = 0; i < this.deviceList.length; i++) {
                      if (
                        this.deviceList[i].deviceId === this.deviceInfo.deviceId
                      ) {
                        this.deviceList[i].services.push({
                          serviceId: uuid,
                          characteristicId: block.uuid,
                        });
                        break;
                      }
                    }
                  }
                  //* 更新deviceInfo数据
                  this.deviceInfo = this.deviceList.find(
                    (item) => item.deviceId === this.deviceInfo.deviceId
                  );
                  uni.setStorage({
                    key: "currDev",
                    data: this.devicesList,
                  });
                },
              });
            });
          } else {
            setTimeout(() => {
              this.getBLEServices(deviceId);
            }, 2000);
          }
        },
      });
    },

Part2 -——由于不同类型打印机的命令不同,我这边大致说一下我的思路,我将发送的的命令与字符串合并成一个二维数组,循环将数组传入,但是需要注意打印的字节数不能超过20字节,如果超过20字节需要分包发送。我这边大致写了一个方法,但是最近打印机故障了还未测试。可自行修改代码适配。||2023.12.21 经测试拆分字节会出现乱码 请使用以下代码,通过拆分数组循环将每个字节数组再进行拆分发送。代码已测 可以使用 , 使用是 直接将二维数组传入send方法就行

蓝牙打印代码参考

  async Send(buff) {
      let that = this;
      //* 循环遍历写入
      for (let buffSlice of buff) {
        let buffLen = buffSlice.length;
        let arrSize = 21;
        while (buffLen > 0) {
          if (buffLen > arrSize) {
            let writeBuf = buffSlice.slice(0, arrSize);
            await that.writItByArr(writeBuf);
            buffSlice = buffSlice.slice(arrSize);
            buffLen = buffSlice.length;
          } else {
            await that.writItByArr(buffSlice);
            break;
          }
        }
      }
    },
    writItByArr(buff) {
      let that = this;
      let buf = new ArrayBuffer(buff.length);
      let dataView = new DataView(buf);
      for (var i = 0; i < buff.length; ++i) {
        dataView.setUint8(i, buff[i]);
      }
      // console.log(this.deviceInfo.deviceId);
      return new Promise((resolve, reject) => {
        setTimeout(() => {
        uni.writeBLECharacteristicValue({
          deviceId: that.deviceInfo.deviceId,
          serviceId: that.deviceInfo.services[0].serviceId,
          characteristicId: that.deviceInfo.services[0].characteristicId,
          value: buf,
          success: function (res) {
            console.log("写入成功", res);
            resolve(true);
            // uni.$u.toast("打印成功");
          },
          fail: function (e) {
            console.log("写入失败", e);
            that.writItByArr(buff);
          },
          complete: function (res) {
            // console.log("发送数", res);
          },
        });
          }, 100);
      });
    },
  • 8
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
以下是基于uni-app低功耗蓝牙接收数据的步骤: 1.打开蓝牙连接设备并扩大传输MTU。 2.获取蓝牙服务并获取蓝牙设备某个服务中所有特征值(characteristic)。 3.当找到同时有读、写、订阅权限的特征值时,启用低功耗蓝牙设备特征值变化时的notify功能。 4.订阅特征值并开启成功后,写入指令。 5.写入成功后,读取二进制数据值(此时开启的notify功能就会监听并返回设备响应数据)。 6.接收设备响应数据。 以下是一个基于uni-app低功耗蓝牙接收数据的代码示例: ```javascript // 连接蓝牙设备 uni.createBLEConnection({ deviceId: '设备ID', success: function (res) { console.log('连接成功') // 扩大传输MTU uni.requestMTU({ deviceId: '设备ID', mtu: 512, success: function (res) { console.log('MTU扩大成功') // 获取蓝牙服务 uni.getBLEDeviceServices({ deviceId: '设备ID', success: function (res) { console.log('获取蓝牙服务成功') // 获取蓝牙设备某个服务中所有特征值(characteristic) uni.getBLEDeviceCharacteristics({ deviceId: '设备ID', serviceId: '服务ID', success: function (res) { console.log('获取特征值成功') // 遍历特征值,找到同时有读、写、订阅权限的特征值 for (var i = 0; i < res.characteristics.length; i++) { var item = res.characteristics[i] if (item.properties.read && item.properties.write && item.properties.notify) { console.log('找到特征值') // 启用低功耗蓝牙设备特征值变化时的notify功能 uni.notifyBLECharacteristicValueChange({ deviceId: '设备ID', serviceId: '服务ID', characteristicId: item.uuid, state: true, success: function (res) { console.log('notify功能启用成功') // 订阅特征值 uni.onBLECharacteristicValueChange(function (res) { console.log('接收到数据') // 接收设备响应数据 var value = new Uint8Array(res.value) console.log('接收到的数据为:' + value) }) // 写入指令 uni.writeBLECharacteristicValue({ deviceId: '设备ID', serviceId: '服务ID', characteristicId: item.uuid, value: '指令', success: function (res) { console.log('指令写入成功') // 读取二进制数据值 uni.readBLECharacteristicValue({ deviceId: '设备ID', serviceId: '服务ID', characteristicId: item.uuid, success: function (res) { console.log('读取数据成功') } }) } }) } }) break } } } }) } }) } }) } }) ```

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值