Connect Bluetooth device using react native

To connect to a Bluetooth device using React Native, you can make use of the `react-native-ble-manager` library. This library provides a simple interface to communicate with Bluetooth Low Energy (BLE) devices. Here’s an example of how you can create a function to connect to a Bluetooth device using React Native:

First, make sure you have installed the required dependencies by running the following command in your project directory:

				
					npm install react-native-ble-manager

				
			

Then, create a file (e.g., `BluetoothManager.js`) and add the following code:

				
					import { BleManager } from 'react-native-ble-manager';

const BluetoothManager = {
  manager: new BleManager(),

  connectToDevice: (deviceUUID, onConnected, onError) => {
    // Connect to the device
    BluetoothManager.manager.connectToDevice(deviceUUID)
      .then(() => {
        // Retrieve connected device information
        return BluetoothManager.manager.discoverAllServicesAndCharacteristics(deviceUUID);
      })
      .then(() => {
        // Device connected successfully
        onConnected();
      })
      .catch(error => {
        // Error occurred during connection
        onError(error);
      });
  },

  disconnectDevice: (deviceUUID) => {
    // Disconnect from the device
    BluetoothManager.manager.cancelDeviceConnection(deviceUUID);
  },
};

export default BluetoothManager;

				
			

In this example, we create a `BluetoothManager` object that wraps the `BleManager` from `react-native-ble-manager`. The `connectToDevice` function takes a `deviceUUID` parameter, as well as callbacks for handling successful connection (`onConnected`) and error (`onError`) scenarios. It connects to the device, discovers all services and characteristics, and calls the appropriate callback based on the connection result.

You can now import and use this `BluetoothManager` object in your React Native components to establish a Bluetooth connection. For example:

				
					import React, { useState } from 'react';
import { View, Button } from 'react-native';
import BluetoothManager from './BluetoothManager';

const App = () => {
  const [connected, setConnected] = useState(false);

  const handleConnect = () => {
    const deviceUUID = 'YOUR_DEVICE_UUID';

    BluetoothManager.connectToDevice(deviceUUID,
      () => {
        // Device connected successfully
        setConnected(true);
      },
      error => {
        // Error occurred during connection
        console.log('Connection error:', error);
      }
    );
  };

  const handleDisconnect = () => {
    const deviceUUID = 'YOUR_DEVICE_UUID';

    BluetoothManager.disconnectDevice(deviceUUID);
    setConnected(false);
  };

  return (
    <View>
      <Button
        title="Connect"
        onPress={handleConnect}
        disabled={connected}
      />
      <Button
        title="Disconnect"
        onPress={handleDisconnect}
        disabled={!connected}
      />
    </View>
  );
};

export default App;

				
			

In this example, we use the `useState` hook to keep track of the connection status (`connected`). The `handleConnect` function triggers the connection to the device when the “Connect” button is pressed, and the `handleDisconnect` function disconnects from the device when the “Disconnect” button is pressed.

Remember to replace `’YOUR_DEVICE_UUID’` with the actual UUID of the Bluetooth device you want to connect to.

This is a basic example to get you started. Depending on your specific use case, you may need to handle additional Bluetooth events or retrieve specific characteristics from the connected device.

Share:

Facebook
Twitter
Pinterest
LinkedIn

Leave a Reply

Your email address will not be published. Required fields are marked *