I’m trying to connect my beacon with android tablet using typescript, and react-native-ble-plx lib, but it’s not working when i gave specific valid UUID in startDeviceScan() as prop.
It works when the UUID prop is null…
should I change the default txPower of beacon? when i check the txPower using beacon app, it was 40.
import React, { useEffect, useRef, useState } from 'react';
import { PermissionsAndroid, Platform, Text, View } from 'react-native';
import { BleManager, Device } from 'react-native-ble-plx';
const BeaconDistanceTracker = () => {
const [beaconDistance, setBeaconDistance] = useState<number | null>(null);
const [connected, setConnected] = useState<boolean>(false); // 연결 상태 관리
const manager = useRef(new BleManager()).current; //블루투스 객체 생성 및 현재 상태 추적
useEffect(() => {
//블루투스 관련 권한 요청
const requestPermissions = async () => {
const fineLocationGranted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
const coarseLocationGranted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_COARSE_LOCATION);
console.log('FineLocationGranted:', fineLocationGranted);
console.log('CoarseLocationGranted:', coarseLocationGranted);
if (Platform.OS === 'android' && Platform.Version >= 31) {
const bluetoothScanGranted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN);
console.log('BluetoothScanGranted:', bluetoothScanGranted);
const bluetoothConnectGranted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT);
console.log('BluetoothConnectGranted:', bluetoothConnectGranted);
}
};
//RSSI 기반 거리 계산
const calculateDistance = (rssi: number, txPower: number): number => {
if (rssi === 0) return -1.0;
const ratio = rssi / txPower;
if (ratio < 1.0) return Math.pow(10, (txPower - rssi) / (10 * 1));
return (0.89976) * Math.pow(10, (txPower - rssi) / (10 * 2));
};
//RSSI값 실시간 업데이트
const handleUpdateRSSI = async (device: Device) => {
const { rssi } = device;
if (rssi !== null) {
const txPower = 0;
const distance = calculateDistance(rssi, txPower);
setBeaconDistance(distance);
console.log('RSSI:', rssi, '거리:', distance.toFixed(2), '미터');
// 연결 상태가 false인 경우에만 연결 시도
if (!connected) {
try {
console.log('디바이스 연결 시도 중...'); // 연결 시도 로그
// 디바이스 연결 시도
await device.connect();
await new Promise(resolve => setTimeout(resolve, 3000)); // 3초 대기
const isConnected = await device.isConnected(); // 연결 상태 확인
setConnected(isConnected); //연결 상태 업데이트
//연결 상태 로그 출력
if (isConnected) {
console.log('디바이스가 연결되었습니다.');
} else {
console.log('디바이스 연결에 실패했습니다.');
}
} catch (error) {
console.log('디바이스 연결 중 오류 발생:', error);
}
}
} else {
console.log('RSSI 값이 null입니다.');
}
};
//비콘 추적 시작
const startScanning = () => {
const beaconUUID = 'e2c56db5-dffb-48d2-b060-d0f5a71096e0'; // 비콘의 UUID로 변경하세요.
manager.startDeviceScan(
//UUIDs: UUID[] | null
[beaconUUID],
// options: ScanOptions | null,
null,
// listener: (error: BleError | null, scannedDevice: Device | null) => void
(error, device) => {
if (error) {
console.error(error);
return;
}
if (device) {
console.log('Device Detected:', device);
handleUpdateRSSI(device);
}else{
console.log('Failed to find Device while scanning');
}
}
)};
requestPermissions().then(() => {
startScanning();
});
return () => {
manager.stopDeviceScan();
};
}, [manager, connected]); // connected 상태를 의존성 배열에 추가
useEffect(() => {
console.log('현재 비콘과의 거리:', beaconDistance);
}, [beaconDistance]);
useEffect(() => {
const subscription = manager.onStateChange((state) => {
console.log('bleManger State:',state);
})
return () => {
subscription.remove();
}
},[])
return (
<View>
<Text style={{ color: 'white' }}>
비콘과의 거리: {beaconDistance !== null ? `${beaconDistance.toFixed(2)} 미터` : '측정 중...'}
</Text>
<Text style={{ color: 'white' }}>
연결 상태: {connected ? '연결됨' : '연결되지 않음'}
</Text>
</View>
);
};
export default BeaconDistanceTracker;
I want to detect the device, and keep watching the RSSI, so I can calculate the distance using RSSI.
지민이 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
The react-native-ble-plx module used in the code will not work. It is not designed to detect Minew E7 or other iBeacon compatible BLE beacons. It is designed to work with more generalized Bluetooth peripherals which use a lower-level scheme for scanning and detecting their advertisements. The UUID you are scanning for using this module is not the iBeacon UUID, but a lower-level Bluetooth GATT Service UUID, a completely different concept.
Instead, try using this module, following the instructions to start ranging for iBeacon. It will be much easier to set up and you can look for your beacon using the UUID you show in your code.
Note: while it is in theory possible to write code to detect your beacon using react-native-ble-plx, this will be difficult and require a lot of code, as you will essentially be writing your own beacon detection module from scratch.