uniapp:接收第三方蓝牙广播数据

// 打开蓝牙模块,页面show阶段开启
  const openBluetooth = () => {
    uni.openBluetoothAdapter({
      success: () => {
        openSearchBluetooth();
      },
      fail: (res) => {
        // 启动失败
        closeBluetooth();
        if (res.code === 10001) {
          openBluetoothModal();
        } else {
          uni.hideLoading();
          uni.showModal({
            title: '',
            content: '蓝牙搜索模块启动失败:' + res,
            showCancel: false,
            success: (res) => {}
          });
        }
      }
    });
  };

  // 打开蓝牙提示
  const openBluetoothModal = () => {
    uni.showModal({
      title: '',
      content: '该页面操作需要蓝牙支持!请打开蓝牙',
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          // #ifdef APP
          let main = plus.android.runtimeMainActivity();
          let Intent = plus.android.importClass('android.content.Intent');
          let mIntent = new Intent('android.settings.BLUETOOTH_SETTINGS');
          main.startActivity(mIntent);
          // #endif
        } else {
          navigateBack();
        }
      },
      complete: () => {}
    });
  };

  // 开启蓝牙搜索
  const openSearchBluetooth = () => {
    uni.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: true,
      success: (res) => {},
      fail: (res) => {
        searchError(res);
      }
    });
  };
  // search open error
  const searchError = (res: any) => {
    if (res.code === 10000) {
      closeBluetooth(() => {
        openBluetooth();
      });
    } else {
      closeBluetooth();
      uni.hideLoading();
      uni.showModal({
        title: '',
        content: '蓝牙搜索模块启动失败,请检查手机蓝牙是否开启:' + res.code,
        showCancel: false,
        success: (res) => {}
      });
    }
  };

  // check ios
  const checkIos = () => {
    restartBluetoothCompatibleIos(() => {
      app?.setTimeout(() => {
        getBluetoothData();
      });
    });
  };

  // 该死的ios兼容,重启蓝牙,一点也不像安卓那般666
  const restartBluetoothCompatibleIos = (cb?: any) => {
    if (isIos) {
      stopSearch(() => {
        uni.closeBluetoothAdapter({
          success: () => {
            app?.setTimeout(() => {
              uni.openBluetoothAdapter({
                success: () => {
                  uni.startBluetoothDevicesDiscovery({
                    allowDuplicatesKey: true,
                    success: () => {
                      cb && cb();
                    }
                  });
                }
              });
            }, 200);
          }
        });
      });
    } else {
      cb && cb();
    }
  };

  // 获取蓝牙设备数据
  const getBluetoothData = () => {
    if ([undefined, null, ''].includes(weightIndex)) {
      return;
    }
    uni.getBluetoothDevices({
      success: (res) => {
        // IFDvice:获取所有  IF_  开头的蓝牙数据并根据RSSI值重从大到小排序,越大越靠近,(RSSI值最大为0,基本为负数)
        console.log('res.devices', res.devices);
        const IFDvice =
          res.devices
            .filter((item) => item.name.startsWith('IF_'))
            .sort((a, b) => b.RSSI - a.RSSI)[0] || null;

        if (IFDvice) {
          // 找到称重的了
          const bytes = Array.prototype.map
            .call(new Uint8Array(IFDvice.advertisData), (bit) =>
              ('00' + bit.toString(16)).slice(-2)
            )
            .join('');
          bluetoothDataWrite(bytes);
        } else {
          uni.hideLoading();
          uni.showModal({
            title: '',
            content: '数据获取失败,请检查相关设备是否开启,或稍后再试 -2',
            showCancel: false,
            success: () => {
              weightTwice = [];
            }
          });
        }
      },
      fail: (res) => {
        weightIndex = null;
        console.log('getBluetoothDevices fail', res);
        uni.hideLoading();
        weightTwice = [];
        uni.showModal({
          title: '',
          content: '蓝牙数据获取失败,请重试:' + JSON.stringify(res),
          showCancel: false
        });
      }
    });
  };

  // 停止蓝牙搜索及关闭蓝牙
  const stopSearch = (cb?: any) => {
    uni.stopBluetoothDevicesDiscovery({
      success: () => {
        cb && cb();
      }
    }); //停止搜索蓝牙
  };
  const closeBluetooth = (cb?: any) => {
    stopSearch(() => {
      //关闭蓝牙模块
      uni.closeBluetoothAdapter({
        success: () => {
          cb && cb();
        }
      });
    });
  };
  onUnload(() => {
    closeBluetooth();
  });

  // 蓝牙数据写入
  let weightTwice: any[] = []; // 存储两次结果,称重时比对两次结果,不一致则无效
  const bluetoothDataWrite = (bytes: string) => {
    restartBluetoothCompatibleIos(() => {
      const isKg = bytes.substring(22, 24);
      const weight = parseInt(bytes.substring(24, 28), 16);
      if (isKg === '01') {
        // 公斤称
        weightTwice.push(weight); // 记录称重记录
        if (weightTwice.length >= 2) {
          // 两次结果已出
          uni.hideLoading();
          if (
            weightTwice[0] === weightTwice[1] &&
            !['', undefined, null].includes(weightTwice[0])
          ) {
            // 两次重量一样
            console.log('weightLogs.value', weightLogs.value, weightIndex, weight);
            weightLogs.value[weightIndex].weight = Number((weight / 100).toFixed(2));
            if (weightIndex === weightLogs.value.length - 1) {
              weightIndex = null;
              addLog();
            }
            totalWeightComputed();
          } else {
            uni.showModal({
              title: '',
              content: '称重结果无效,请在蓝牙秤“滴”声后录入',
              showCancel: false
            });
          }
          weightIndex = null;
          weightTwice = [];
        } else {
          checkIos();
        }
      } else {
        weightIndex = null;
        weightTwice = [];
        app?.showToast('请使用KG称');
      }
    });
  };
  // 计算总重量
  const totalWeightComputed = () => {
    const weightsList = weightLogs.value.filter((item) => item.weight).map((item) => item.weight);
    totalWeight.value = weightsList.length ? Number(eval(weightsList.join('+')).toFixed(2)) : 0;
  };
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

Mosowe

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

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

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

打赏作者

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

抵扣说明:

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

余额充值