Giter VIP home page Giter VIP logo

react-native-bluetooth-classic-apps's Introduction

react-native-bluetooth-classic-apps

Development applications used for programing/testing react-native-bluetooth-classic

Originally the development and example apps were stored inside the library itself react-native-blueooth-classic/BluetoothClassicExample which caused two major issues:

  1. There were issues writing tests (dependencies required for testing broke the Example app)
  2. With more apps being required (multiple React Native versions, functionality showcase, etc) the library would be polluted

Contribution

Feel free to add your own sample application, either:

  1. Within this project, specifically if help testing/debugging is required
  2. Updating this README.md with a link to your showcase application

Example Apps

Android Permissions!

When working with Android you'll need to request permissions manually:

import { PermissionsAndroid } from 'react-native';

/**
 * See https://reactnative.dev/docs/permissionsandroid for more information
 * on why this is required (dangerous permissions).
 */
const requestAccessFineLocationPermission = async () => {
  const granted = await PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    {
      title: 'Access fine location required for discovery',
      message:
        'In order to perform discovery, you must enable/allow ' +
        'fine location access.',
      buttonNeutral: 'Ask Me Later',
      buttonNegative: 'Cancel',
      buttonPositive: 'OK',
    }
  );
  return granted === PermissionsAndroid.RESULTS.GRANTED;
};

BluetoothClassicExample

The primary application used during development.

  • Supports the lowest versions of React Native (0.60.0), Android (26) and IOS (9)
  • Provides almost all functionality from the library
  • Configured to use the locally installed ../../react-native-bluetooth-classic/ project.

react-native-bluetooth-classic-apps's People

Contributors

akash-r-prabhu avatar kenjdavidson avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

react-native-bluetooth-classic-apps's Issues

Error while accessing any function in react-native-bluetooth-classics library.

Hello,

While accessing the isBluetoothEnabled or other function. Im getting the error says

TypeError: Cannot read property 'isBluetoothEnabled' of null:

I have console the RNBluetoothClassic to check the available function but the value, Im getting is null.

Error Log:
image

Packages Information:
"dependencies": {
"expo": "~49.0.15",
"expo-status-bar": "~1.6.0",
"react": "18.2.0",
"react-native": "0.72.6",
"react-native-bluetooth-classic": "^1.60.0-rc6"
},
"devDependencies": {
"@babel/core": "^7.20.0"
},

Android version: 8.1.0
Api level: 26

The code im using....
`import { StatusBar } from "expo-status-bar";
import { useEffect, useState } from "react";
import { StyleSheet, Text, View } from "react-native";
import { PermissionsAndroid } from "react-native";
import RNBluetoothClassic from "react-native-bluetooth-classic";

const requestAccessFineLocationPermission = async () => {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Access fine location required for discovery",
message:
"In order to perform discovery, you must enable/allow " +
"fine location access.",
buttonNeutral: "Ask Me Later",
buttonNegative: "Cancel",
buttonPositive: "OK",
}
);
return granted === PermissionsAndroid.RESULTS.GRANTED;
};
export default function App() {
const [permission, setPermission] = useState(false);
useEffect(() => {
if (requestAccessFineLocationPermission()) {
setPermission(true);
} else {
setPermission(false);
}
}, []);

const requestAccessbluethoothPermission = async () => {
console.log("List of function: ", RNBluetoothClassic && RNBluetoothClassic);
if (permission) {
try {
if (RNBluetoothClassic && RNBluetoothClassic.isBluetoothEnabled()) {
const devices = await RNBluetoothClassic.startDiscovery();
console.log("Discovered devices:", devices);
await RNBluetoothClassic.cancelDiscovery();
console.log("Bluetooth permissions granted");
} else {
console.log("Bluetooth permissions denied");
}
} catch (error) {
console.error("Error requesting permissions:", error);
}
}
};
permission && requestAccessbluethoothPermission();

return (

Open up App.js to start working ond your app!
{permission && Permission Recieved!}


);
}

const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
},
});
`

Connection Failed: java.io.IOException: read failed, socket might closed or timeout with -1

I am using exactly the same (https://github.com/kenjdavidson/react-native-bluetooth-classic-apps/tree/main/BluetoothClassicExample) code to connect to devices in my application. But when selecting the device to connect, i am getting exception.

I have used follwed part of snippet to connect:

      console.log("connection is......", connection);
      if (!connection) {
        
        console.log(this.state.connectionOptions);
        connection = await this.props.device.connect({
           CONNECTOR_TYPE: "rfcomm",
           DELIMITER: "\n",
           DEVICE_CHARSET: Platform.OS === "ios" ? 1536 : "utf-8",
        });

        this.addData({
          data: "Connection successful",
          timestamp: new Date(),
          type: "info",
        });
      }

Can you please suggest me the solution

metro.config.js

the given path to library is wrong

const bluetoothLib = path.resolve( __dirname, '../BluetoothClassicExample/node_modules/react-native-bluetooth-classic' );

RN bluetooth classic app is not working on Android 10 and above

Hi,

i am trying to run RN bluetooth classic app on my Android (10) phone. But it gets struck when i click on Discover Devices button.

Below is the log:

2023-05-05 15:51:11.694 32070-32129/com.bluetoothclassicexample I/ReactNativeJS: Running application "BluetoothClassicExample" with appParams: {"rootTag":21}. __DEV__ === false, development-level warning are OFF, performance optimizations are ON

2023-05-05 15:51:11.723 32070-32070/com.bluetoothclassicexample D/RNBluetoothClassicModule: onHostResume: register Application receivers

2023-05-05 15:51:11.814 32070-32070/com.bluetoothclassicexample D/ViewRootImpl@e05321c[MainActivity]: MSG_RESIZED: frame=(0,0,1080,2340) ci=(0,85,0,126) vi=(0,85,0,126) or=1

2023-05-05 15:51:11.905 32070-32129/com.bluetoothclassicexample I/ReactNativeJS: DeviceListScreen::getBondedDevices
2023-05-05 15:51:11.907 32070-32129/com.bluetoothclassicexample I/ReactNativeJS: App::componentDidMount adding listeners: onBluetoothEnabled and onBluetoothDistabled

2023-05-05 15:51:11.907 32070-32129/com.bluetoothclassicexample I/ReactNativeJS: App::componentDidMount alternatively could use onStateChanged
2023-05-05 15:51:11.914 32070-32129/com.bluetoothclassicexample I/ReactNativeJS: App::componentDidMount Checking bluetooth status

2023-05-05 15:51:11.920 32070-32070/com.bluetoothclassicexample D/ScrollView: initGoToTop
2023-05-05 15:51:11.985 32070-32130/com.bluetoothclassicexample D/RNBluetoothClassicModule: Adding listener to BLUETOOTH_ENABLED, currently have 1 listeners

2023-05-05 15:51:11.988 32070-32130/com.bluetoothclassicexample D/RNBluetoothClassicModule: Adding listener to BLUETOOTH_DISABLED, currently have 1 listeners
2023-05-05 15:51:12.018 32070-32129/com.bluetoothclassicexample I/ReactNativeJS: 'DeviceListScreen::getBondedDevices found', [ { _bluetoothModule: 
         { _nativeModule: 
            { accept: { [Function] type: 'promise' },
              addListener: { [Function] type: 'async' },
              availableFromDevice: { [Function] type: 'promise' },
              cancelAccept: { [Function] type: 'promise' },
              cancelDiscovery: { [Function] type: 'promise' },
              clearFromDevice: { [Function] type: 'promise' },
              connectToDevice: { [Function] type: 'promise' },
              disconnectFromDevice: { [Function] type: 'promise' },
              getBondedDevices: { [Function] type: 'promise' },
              getConnectedDevice: { [Function] type: 'promise' },
              getConnectedDevices: { [Function] type: 'promise' },
              isBluetoothAvailable: { [Function] type: 'promise' },
              isBluetoothEnabled: { [Function] type: 'promise' },
              isDeviceConnected: { [Function] type: 'promise' },
              openBluetoothSettings: { [Function] type: 'async' },
              pairDevice: { [Function] type: 'promise' },
              readFromDevice: { [Function] type: 'promise' },
              removeAllListeners: { [Function] type: 'async' },
              removeListener: { [Function] type: 'async' },
              requestBluetoothEnabled: { [Function] type: 'promise' },
              setBluetoothAdapterName: { [Function] type: 'promise' },
              startDiscovery: { [Function] type: 'promise' },
              unpairDevice: { [Function] type: 'promise' },
              writeToDevice: { [Function] type: 'promise' },
              getConstants: [Function] },
           _eventEmitter: 
            { _subscriber: 
               { _subscriptionsForType: 
                  { didUpdateDimensions: 
                     [ { subscriber: [Circular],
                         emitter: 
                          { _subscriber: [Circular],
                            sharedSubscriber: [Circular],
                            _currentSubscription: null },
                         listener: [Function],
                         context: undefined,
                         eventType: 'didUpdateDimensions',
                         key: 0 } ],
                    hardwareBackPress: 
                     [ { subscriber: [Circular],
                         emitter: 
                          { _subscriber: [Circular],
                            sharedSubscriber: [Circular],
                            _currentSubscription: null },
                         listener: [Function],
                         context: undefined,
                         eventType: 'hardwareBackPress',
                         key: 0 } ],
                    collectBugExtraData: 
                     [ { subscriber: [Circular],
                         emitter: 
                          { _subscriber: [Circular],
                            sharedSubscriber: [Circular],
                            _currentSubscription: null },
                         listener: [Function: value],
                         context: null,
                         eventType: 'collectBugExtraData',
                         key: 0 } ],
                    collectRedBoxExtraData: 
                     [ { subscriber: [Circular],
                         emitter: 
                          { _subscriber: [Circular],
                            sharedSubscriber: [Circular],
                            _currentSubscription: null },
                         listener: [Function: value],
                         context: null,
                         eventType: 'collectRedBoxExtraData',
                         key: 0 } ],
                    keyboardWillShow: 
                     [ ,
                       ,
                       { subscriber: [Circular],
                         emitter: 
                          { _subscriber: [Circular],
                            dismiss: [Function],
                            scheduleLayoutAnimation: [Function] },
                         listener: [Function: bound scrollResponderKeyboardWillShow],
                         context: undefined,
                         eventType: 'keyboardWillShow',
                         key: 2 } ],
                    keyboardWillHide: 
                     [ ,
                       ,
                       { subscriber: [Ci

2023-05-05 15:51:15.187 32070-32130/com.bluetoothclassicexample D/BluetoothAdapter: startDiscovery

Clean up bluetooth-classic-example

Needs to be cleaned up, maybe a full overhaul making it more usable as an actual application.

  • Make the move to hooks/functions
  • Redesign the application screens for consistency
  • Redesign the state management

Serial Terminal is the defacto bluetooth serial app. In no way is this app meant to replace (or come close) but it has some nice things that would showcase the Bluetooth React Library.

Error: java.io.IOException: read failed, socket might closed or timeout, read ret: -1, when connect device.

react-native-bluetooth-classic: 1.60.0-rc.21
react-native: 0.64.1

when device.connect(), it meet error: java.io.IOException: read failed, socket might closed or timeout, read ret: -1

function BleClassic(props) {
  const [devices, setDevices] = useState([]);
  const [discovering, setDiscovering] = useState(false);

  useEffect(() => {
    checkBluetoothEnabled();
    return () => {
      cancelDiscovery();
    };
  }, []);

  const startDiscovery = async () => {
    if (Platform.OS !== 'android') {
      return;
    }
    let list = [];
    if (discovering) {
      return;
    }
    setDiscovering(true);
    try {
      let unpaired = await RNBluetoothClassic.startDiscovery();
      list = devices.concat(unpaired);
    } finally {
      setDevices(list);
      setDiscovering(false);
    }
  };

  const cancelDiscovery = async () => {
    if (Platform.OS === 'android') {
      RNBluetoothClassic.cancelDiscovery();
    }
  };

  const checkBluetoothEnabled = async () => {
    try {
      console.log('App::componentDidMount Checking bluetooth status');
      let enabled = await RNBluetoothClassic.isBluetoothEnabled();
      getBondedDevices();
      console.log(`App::componentDidMount Status: ${enabled}`);
    } catch (error) {
      console.log('App::componentDidMount Status Error: ', error);
    }
  };

  /**
   * Gets the currently bonded devices.
   */
  const getBondedDevices = async unloading => {
    try {
      let bonded = await RNBluetoothClassic.getBondedDevices();
      console.log('DeviceListScreen::getBondedDevices found', bonded);
      setDevices(bonded);
    } catch (error) {
      console.log('get devices error:', error);
    }
  };

  const renderItem = device => {
    const connectItem = device.connected ? styles.connectItem : null;
    return (
      <TouchableOpacity onPress={() => connect(device)}>
        <View style={[styles.item, connectItem]}>
          <View>
            <Text style={styles.name}>{device.name}</Text>
            <Text style={styles.itemId}>{device.address}</Text>
          </View>
          {device.connected ? (
            <Image source={require('../assets/img/lang-checked.png')} />
          ) : null}
        </View>
      </TouchableOpacity>
    );
  };

  const connect = async device => {
    try {
      let connection = await device.isConnected();
      console.log('是否连接:', connection);
      // 未连接
      if (!connection) {
        connection = await device.connect({secure: false});
        console.log('连接结果:', connection);
        msgTip('连接成功');
      } else {
        device.disconnect();
      }
    } catch (error) {
      console.log('连接过程错误:', error);
      msgTip(`Error: ${error.message}`);
    }
  };

  return (
    <SafeAreaView style={commonStyles.container}>
      <TouchableOpacity activeOpacity={1} onPress={startDiscovery}>
        <View style={styles.btnGroup}>
          <View style={[commonStyles.directionRow, commonStyles.alignCenter]}>
            <Image source={require('../assets/img/icon-bluetooth-blue.png')} />
            <Text style={styles.scanTitle}>{I18n.t('scanBle')}</Text>
            {discovering ? (
              <ActivityIndicator size={20} color="#58a1e0" />
            ) : null}
          </View>
          <Switch
            trackColor="#0f84df"
            onValueChange={startDiscovery}
            value={discovering}
          />
        </View>
      </TouchableOpacity>
      <Text style={styles.nearTitle}>{I18n.t('bleDevices')}</Text>
      <FlatList
        data={devices}
        renderItem={({item}) => renderItem(item)}
        keyExtractor={item => item.address}
      />
    </SafeAreaView>
  );
}

Add `[email protected]` development app

Library doesn't work due to changes to Native Modules with [email protected].

Started working on this in brance react-native-073. It's not the cleanest, but just attempting the straight conversion of the old app. There are a number of things that need to get re-written:

  • Finish the conversion of the components
  • Add in the local dependency to react-native-bluetooth-classic
  • Look into refactoring into a <BluetoothAdapterContext> to centralize the state

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.