admin管理员组

文章数量:1202352

I am developing a React Native app that allows two phones to send and receive data using Bluetooth. I have explored react-native-ble-plx for Bluetooth Low Energy (BLE) communication. The problem I faced using ble-plx that it doesn't detect phone normally until you have a nrf connect app it get connected but I am confused how to send data.

I also used Bluetooth classic for the connection but the problem I faced here is that I am unable to connect to another discoverable phone device. Can you find reason?

this is my code using Bluetooth-classic

`
import React, { useState, useEffect } from 'react';
import {
  View,
  Button,
  TextInput,
  Text,
  PermissionsAndroid,
  Platform,
  FlatList,
  KeyboardAvoidingView,
  ScrollView,
  Alert,
} from 'react-native';
import BluetoothClassic, { BluetoothDevice } from 'react-native-bluetooth-classic';

const Client: React.FC = () => {
  const [devices, setDevices] = useState<BluetoothDevice[]>([]);
  const [connection, setConnection] = useState<BluetoothDevice | null>(null);
  const [message, setMessage] = useState<string>('');
  const [status, setStatus] = useState<string>('');

  useEffect(() => {
    requestPermissions();
    checkBluetoothStatus();
  }, []);

  const requestPermissions = async () => {
    if (Platform.OS === 'android') {
      try {
        const granted = await PermissionsAndroid.requestMultiple([
          PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN,
          PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT,
          PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        ]);

        if (
          granted[PermissionsAndroid.PERMISSIONS.BLUETOOTH_SCAN] === PermissionsAndroid.RESULTS.GRANTED &&
          granted[PermissionsAndroid.PERMISSIONS.BLUETOOTH_CONNECT] === PermissionsAndroid.RESULTS.GRANTED
        ) {
          console.log('Bluetooth permissions granted');
        } else {
          setStatus('Bluetooth permissions denied');
        }
      } catch (error) {
        console.error('Error requesting permissions:', error);
      }
    }
  };

  const checkBluetoothStatus = async () => {
    try {
      const isAvailable = await BluetoothClassic.isBluetoothAvailable();
      if (!isAvailable) {
        Alert.alert('Bluetooth not available', 'Please enable Bluetooth to use this app.');
      }
    } catch (error) {
      console.error('Error checking Bluetooth status:', error);
    }
  };

  const scanDevices = async () => {
    setStatus('Scanning for devices...');
    setDevices([]); // Clear the previous device list
  
    try {
      // Start discovering devices
      const discoveredDevices = await BluetoothClassic.startDiscovery();
      console.log('Discovered devices:', discoveredDevices);
  
      // Combine bonded and discovered devices for better usability
      const bondedDevices = await BluetoothClassic.getBondedDevices();
      console.log('Paired devices:', bondedDevices);
  
      const uniqueDevices = [
        ...new Map(
          [...bondedDevices, ...discoveredDevices].map((device) => [device.address, device])
        ).values(),
      ]; // Remove duplicate devices based on their address
  
      setDevices(uniqueDevices); // Update the device list
      setStatus('Scan complete');
    } catch (error) {
      console.error('Error scanning devices:', error);
      setStatus('Error scanning devices');
    }
  };
  

  const connectToServer = async (device: BluetoothDevice) => {
    setStatus(`Connecting to ${device.name}...`);
    try {
      const isConnected = await device.connect();
      if (isConnected) {
        console.log('Connected to server:', device);
        setConnection(device);
        setStatus(`Connected to ${device.name}`);
      } else {
        console.error('Failed to connect to server');
        setConnection(null);
        setStatus('Failed to connect');
      }
    } catch (error) {
      console.error('Error connecting to server:', error);
      setConnection(null);
      setStatus('Connection error');
    }
  };

  const disconnect = async () => {
    if (connection) {
      try {
        await connection.disconnect();
        setConnection(null);
        setStatus('Disconnected');
      } catch (error) {
        console.error('Error disconnecting:', error);
        setStatus('Error disconnecting');
      }
    } else {
      setStatus('No device to disconnect');
    }
  };

  const sendMessage = async () => {
    if (connection && message) {
      try {
        await connection.write(message);
        console.log('Message sent:', message);
        setMessage('');
        setStatus('Message sent');
      } catch (error) {
        console.error('Error sending message:', error);
        setStatus('Error sending message');
      }
    } else {
      setStatus('No connection or message to send');
    }
  };

  return (
    <KeyboardAvoidingView style={{ flex: 1, padding: 20 }}>
      <Button title="Scan for Devices" onPress={scanDevices} />
      <FlatList
        data={devices}
        keyExtractor={(device) => device.address}
        renderItem={({ item: device }) => (
          <Button
            title={`Connect to ${device.name || device.address}`}
            onPress={() => connectToServer(device)}
          />
        )}
        ListEmptyComponent={<Text>No devices found</Text>}
        style={{ marginVertical: 10 }}
      />
      {connection && (
        <Button title="Disconnect" onPress={disconnect} color="red" />
      )}
      <TextInput
        placeholder="Type a message"
        value={message}
        onChangeText={setMessage}
        style={{
          borderWidth: 1,
          borderColor: 'gray',
          marginVertical: 10,
          padding: 5,
        }}
      />
      <Button title="Send Message" onPress={sendMessage} />
      <Text style={{ marginVertical: 10, color: 'blue' }}>{status}</Text>
    </KeyboardAvoidingView>
  );
};

export default Client;`

Can anybody clear my doubts?

  1. Is it possible to transfer data btw two phones using react native app via Bluetooth and if yes then how?

  2. what I should use ble-plx or Bluetooth classic for data transfer?

  3. Is react native peripheral modules is working?

I tried everything what available on GitHub, YouTube, medium and etc.

本文标签: