Git Product home page Git Product logo

react-native-google-nearby-connection's Introduction

react-native-google-nearby-connection npm version

React Native wrapper for Googles Nearby Connection API

Download the React Native Nearby Connection demo app from the Google Play Store (Android)

Install

Install package

npm i react-native-google-nearby-connection --save

Android

  • Make sure you are using Gradle 2.2.x (project build.gradle)
  • Add google-services
buildscript {
    ...
    dependencies {
        ...
        classpath 'com.android.tools.build:gradle:2.2.3'
        classpath 'com.google.gms:google-services:3.1.2'
        ...
    }
    ...
}
  • Add the following to your build.gradle's repositories section. (project build.gradle)
allprojects {
    repositories {
        ...
        maven { url "https://maven.google.com" }
        ...
    }
}

app:build.gradle

Add project under dependencies

android {
    ...
    compileSdkVersion 26
    buildToolsVersion "26.0.1"
    ...
    defaultConfig {
        ...
        minSdkVersion 16
        targetSdkVersion 26
        ...
        multiDexEnabled true
        ...
    }
...
dependencies {
    ...
    compile 'com.google.android.gms:play-services-nearby:11.8.0'
    compile project(':react-native-google-nearby-connection')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support:multidex:1.0.1'
    ...
}

settings.gradle

Include project, so gradle knows where to find the project

include ':react-native-google-nearby-connection'
project(':react-native-google-nearby-connection').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-google-nearby-connection/android')

MainApplication.java

We need to register our package

Add import com.butchmarshall.reactnative.google.nearby.connection.NearbyConnectionPackage; as an import statement and new NearbyConnectionPackage() in getPackages()

Usage

Import library

import NearbyConnection, {CommonStatusCodes, ConnectionsStatusCodes, Strategy, Payload, PayloadTransferUpdate} from 'react-native-google-nearby-connection';

Starting the discovery service

NearbyConnection.startDiscovering(
    serviceId                // A unique identifier for the service
);

Stopping the discovery service

NearbyConnection.stopDiscovering(serviceId);

Whether a service is currently discovering

NearbyConnection.isDiscovering();

Connect to a discovered endpoint

NearbyConnection.connectToEndpoint(
    serviceId,              // A unique identifier for the service
    endpointId              // ID of the endpoint to connect to
);

Disconnect from an endpoint

NearbyConnection.disconnectFromEndpoint(
    serviceId,              // A unique identifier for the service
    endpointId              // ID of the endpoint we wish to disconnect from
);

Starting the advertising service

NearbyConnection.startAdvertising(
    endpointName,           // This nodes endpoint name
    serviceId,              // A unique identifier for the service
    strategy                // The Strategy to be used when discovering or advertising to Nearby devices [See Strategy](https://developers.google.com/android/reference/com/google/android/gms/nearby/connection/Strategy)
);

Stopping the advertising service

NearbyConnection.stopAdvertising(
    serviceId                // A unique identifier for the service
);

Whether a service is currently advertising

NearbyConnection.isAdvertising();

Accepting a connection from an endpoint

NearbyConnection.acceptConnection(
    serviceId,               // A unique identifier for the service
    endpointId               // ID of the endpoint wishing to accept the connection from
);

Rejecting a connection from an endpoint

NearbyConnection.rejectConnection(
    serviceId,               // A unique identifier for the service
    endpointId               // ID of the endpoint wishing to reject the connection from
);

Removes a payload (free memory)

NearbyConnection.removePayload(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to stop playing audio from
    payloadId                // Unique identifier of the payload
);

Open the microphone and broadcast audio to an endpoint

NearbyConnection.openMicrophone(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to send the audio to
    metadata                 // String of metadata you wish to pass along with the stream
);

Stop broadcasting audio to an endpoint

NearbyConnection.closeMicrophone(
    serviceId,               // A unique identifier for the service
    endpointId               // ID of the endpoint wishing to stop sending audio to
);

Start playing an audio stream from a received payload (Payload.STREAM)

NearbyConnection.startPlayingAudioStream(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to start playing audio from
    payloadId                // Unique identifier of the payload
);

Stop playing an audio stream from a received payload (Payload.STREAM)

NearbyConnection.stopPlayingAudioStream(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to stop playing audio from
    payloadId                // Unique identifier of the payload
);

Send a file to a service endpoint (Payload.FILE)

NearbyConnection.sendFile(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to stop playing audio from
    uri,                     // Location of the file to send
    metadata                 // String of metadata you wish to pass along with the file
);

Save a file from a payload (Payload.FILE) to storage

NearbyConnection.saveFile(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to stop playing audio from
    payloadId,               // Unique identifier of the payload
).then({
    path,                    // Path where the file was saved on local filesystem
    originalFilename,        // The original name of the sent file
    metadata,                // Any metadata that was sent along with sendFile
}) => {
});

Send a bytes payload (Payload.BYTES)

NearbyConnection.sendBytes(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to stop playing audio from
    bytes                    // A string of bytes to send
);

Read payload [Payload.Type.BYTES] or out of band file [Payload.Type.FILE] or stream [Payload.Type.STREAM] information

NearbyConnection.readBytes(
    serviceId,               // A unique identifier for the service
    endpointId,              // ID of the endpoint wishing to stop playing audio from
    payloadId                // Unique identifier of the payload
).then(({
    type,                    // The Payload.Type represented by this payload
    bytes,                   // [Payload.Type.BYTES] The bytes string that was sent
    payloadId,               // [Payload.Type.FILE or Payload.Type.STREAM] The payloadId of the payload this payload is describing
    filename,                // [Payload.Type.FILE] The name of the file being sent
    metadata,                // [Payload.Type.FILE] The metadata sent along with the file
    streamType,              // [Payload.Type.STREAM] The type of stream this is [audio or video]
}) => {
});

Callbacks

Endpoint Discovery

NearbyConnection.onDiscoveryStarting(({
    serviceId               // A unique identifier for the service
}) => {
    // Discovery services is starting
});

NearbyConnection.onDiscoveryStarted(({
    serviceId               // A unique identifier for the service
}) => {
    // Discovery services has started
});

NearbyConnection.onDiscoveryStartFailed(({
    serviceId               // A unique identifier for the service
    statusCode              // The status of the response [See CommonStatusCodes](https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes)
}) => {
    // Failed to start discovery service
});

// Note - Can take up to 3 min to time out
NearbyConnection.onEndpointLost(({
    endpointId,             // ID of the endpoint we lost
    endpointName,           // The name of the remote device we lost
    serviceId               // A unique identifier for the service
}) => {
    // Endpoint moved out of range or disconnected
});

NearbyConnection.onEndpointDiscovered(({
    endpointId,             // ID of the endpoint wishing to connect
    endpointName,           // The name of the remote device we're connecting to.
    serviceId               // A unique identifier for the service
}) => {
    // An endpoint has been discovered we can connect to
});

Endpoint Advertisement

NearbyConnection.onAdvertisingStarting(({
    endpointName,            // The name of the service thats starting to advertise
    serviceId,               // A unique identifier for the service
}) => {
    // Advertising service is starting
});

NearbyConnection.onAdvertisingStarted(({
    endpointName,            // The name of the service thats started to advertise
    serviceId,               // A unique identifier for the service
}) => {
    // Advertising service has started
});

NearbyConnection.onAdvertisingStartFailed(({
    endpointName,            // The name of the service thats failed to start to advertising
    serviceId,               // A unique identifier for the service
    statusCode,              // The status of the response [See CommonStatusCodes](https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes)
}) => {
    // Failed to start advertising service
});

Connection negotiation

NearbyConnection.onConnectionInitiatedToEndpoint(({
    endpointId,             // ID of the endpoint wishing to connect
    endpointName,           // The name of the remote device we're connecting to.
    authenticationToken,    // A small symmetrical token that has been given to both devices.
    serviceId,              // A unique identifier for the service
    incomingConnection      // True if the connection request was initated from a remote device.
}) => {
    // Connection has been initated
});

NearbyConnection.onConnectedToEndpoint(({
    endpointId,             // ID of the endpoint we connected to
    endpointName,           // The name of the service
    serviceId,              // A unique identifier for the service
}) => {
    // Succesful connection to an endpoint established
});

NearbyConnection.onEndpointConnectionFailed(({
    endpointId,             // ID of the endpoint we failed to connect to
    endpointName,           // The name of the service
    serviceId,              // A unique identifier for the service
    statusCode              // The status of the response [See CommonStatusCodes](https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes)
}) => {
    // Failed to connect to an endpoint
});

NearbyConnection.onDisconnectedFromEndpoint(({
    endpointId,             // ID of the endpoint we disconnected from
    endpointName,           // The name of the service
    serviceId,              // A unique identifier for the service
}) => {
    // Disconnected from an endpoint
});

Payload Status

Nearby.onReceivePayload(({
    serviceId,              // A unique identifier for the service
    endpointId,             // ID of the endpoint we got the payload from
    payloadType,            // The type of this payload (File or a Stream) [See Payload](https://developers.google.com/android/reference/com/google/android/gms/nearby/connection/Payload)
    payloadId               // Unique identifier of the payload
}) => {
    // Payload has been received
});

Nearby.onPayloadUpdate(({
    serviceId,              // A unique identifier for the service
    endpointId,             // ID of the endpoint we got the payload from
    bytesTransferred,       // Bytes transfered so far
    totalBytes,             // Total bytes to transfer
    payloadId,              // Unique identifier of the payload
    payloadStatus,          // [See PayloadTransferUpdate.Status](https://developers.google.com/android/reference/com/google/android/gms/nearby/connection/PayloadTransferUpdate.Status)
    payloadHashCode,        // ???
}) => {
    // Update on a previously received payload
});

Nearby.onSendPayloadFailed(({
    serviceId,              // A unique identifier for the service
    endpointId,             // ID of the endpoint wishing to connect
    statusCode              // The status of the response [See CommonStatusCodes](https://developers.google.com/android/reference/com/google/android/gms/common/api/CommonStatusCodes)
}) => {
    // Failed to send a payload
});

react-native-google-nearby-connection's People

Contributors

butchmarshall avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  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-google-nearby-connection's Issues

Project support

Wanted to check if the package is still being supported and worked on?

TypeError: null is not an object (evaluating '..NearbyConnection.endpoints')

Hi, butchmarshall

I tried to run your example into more recent google nearby. I spent a couple of days to tackle this and updated most of the Gradle and SDK versions to the most recent versions and it is building the app successfully except for this runtime error. I am using "react-native": "0.61.5".

Nearby_issue

renderApplication.js (this file is part of React-Native and hasn't been modified in any way)

Screenshot 2020-02-02 20 58 45

index.js

class NearbyConnection {
	// Get all the endpoints
	static endpoints() {
		return NativeModules.NearbyConnection.endpoints();  // <- issue is here
	}

App.js

componentWillMount() {
   Nearby.endpoints().then(endpoints => {
     console.log('endpoints', endpoints);
   });
 }

Could you please take a quick look and point me in the right direction? Thanks!

my fork is in https://github.com/staminna/react-native-google-nearby-connection

Unable to Retry Nearby.saveFile() after initial permission failure (granting after initial failure)

Hey Butch, first need to say amazing library!

I have a question regarding the ability to call Nearby.saveFile(serviceId,endpointId,payloadId) after an initial permission failure. Currently, as long as a user has granted permissions to READ/WRITE external storage, calling Nearby.saveFile() has the promise resolve successfully. If permissions are not granted or are revoked before calling saveFile, one encounters a promise rejection. Until here things are still behaving as expected.

However, in my case I am trying to offer the user the ability to retry executing saveFile() at a later point by storing the serviceId, endpointId, and payloadId before initially calling saveFile. This way, once saveFile() is called and it fails, the user can be prompted to grant permissions within their settings or elsewhere and try calling it again. The problem is that when I allow the user to retry using the same serviceId, endpointId, and payloadId which previously failed due to permissions not being granted, the promise still rejects.

When I adb logcat I see it is failing with the message 03-24 14:31:03.806 24644 26856 V NearbyConnection: Cannot convert to file., which is line #1501 here

public void saveFile(final String serviceId, final String endpointId, final String payloadId, final Promise promise) {
logV("saveFile from service "+serviceId+" and endpoint " + endpointId + " and payload "+payloadId);
final Payload payload = mReceivedPayloads.get(serviceId+"_"+endpointId+"_"+payloadId);
if (payload == null) {
logV("Cannot find payload.");
promise.reject("");
return;
}
if (payload.getType() != Payload.Type.FILE) {
logV("Cannot save, not a file.");
promise.reject("");
return;
}
final String payloadFileData = mPayloadFileData.get(payloadId);
int colonIndex = payloadFileData.indexOf(':');
final String payloadFilename = payloadFileData.substring(0, colonIndex);
final String payloadMetadata = payloadFileData.substring(colonIndex+1);
if (payloadFilename == null) {
logV("Cannot find filename for "+payloadId);
promise.reject("");
return;
}
final Activity activity = getCurrentActivity();
permissionsCheck(activity, Arrays.asList(getRequiredStoragePermissions()), new Callable<Void>() {
@Override
public Void call() throws Exception {
File payloadFile = payload.asFile().asJavaFile();
if (payloadFile == null) {
logV("Cannot convert to file.");
promise.reject("");
}
else {
File destPath = payloadFile.getParentFile();
String extension = NearbyConnectionModule.getFileExtension(payloadFilename);
File destFile = NearbyConnectionModule.getUniqueFile(destPath, extension);
payloadFile.renameTo(destFile);
String destFilePath = destFile.getPath();
logV("file saved to "+destFilePath);
WritableMap out = Arguments.createMap();
out.putString("path", destFilePath);
out.putString("originalFilename", payloadFilename);
out.putString("metadata", payloadMetadata);
promise.resolve(out);
}
return null;
}
});
}

In other words it seems that
File payloadFile = payload.asFile().asJavaFile(); is null. I decided to log every payload variable until permissionsCheck fires and this is the below output:

03-24 14:31:03.805 24644 26856 V NearbyConnection: saveFile from service com.google.myApp.v1 and endpoint hT4- and payload -6821529802993021226
03-24 14:31:03.805 24644 26856 V NearbyConnection: Payload com.google.android.gms.nearby.connection.Payload@16edba2
03-24 14:31:03.805 24644 26856 V NearbyConnection: payload.getType() 2
03-24 14:31:03.805 24644 26856 V NearbyConnection: payloadFileData  awesomePhoto.WEBP:{"description":"a flower"}
03-24 14:31:03.805 24644 26856 V NearbyConnection: payloadFilename awesomePhoto.WEBP
03-24 14:31:03.805 24644 26856 V NearbyConnection: payloadMetadata {"description":"a flower"}
03-24 14:31:03.806 24644 26856 V NearbyConnection: Cannot convert to file.

Question/s: Any idea why payload.asFile().asJavaFile() returns null when retrying saveFile? Is it that the initial permissions failure causes the payload content to somehow be destroyed within the NearbyConnection cache so there is nothing to call payload.asFile().asJavaFile() on? Although I find it strange that calling payload.getType() works and other metadata still exists on the payload but asFile() fails. Any thoughts here would be amazing.

Assumption/Hypothesis: After the final payload is delivered, Nearby Connections attempts to write the file which, if the permissions are not given, fails. Therefore, regardless if permissions are then granted after, that final payload will still not have a file associated and, as such, will forever fail. If this is correct then there is no other option than to resend the file I'm guessing.

Stackoverflow link: https://stackoverflow.com/questions/55328027/nearbyconnection-payload-asfile-asjavafile-is-null-when-retrying-to-savefil

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.