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;
  };

你可能感兴趣的:(uniapp,uniapp蓝牙模块,uniapp蓝牙搜索,uniapp接收蓝牙广播,uniapp接收蓝牙数据)