Skip to content

Commit

Permalink
feat: refactor the nearby driver to fit the new sdk wrapper
Browse files Browse the repository at this point in the history
Signed-off-by: D4ryl00 <d4ryl00@gmail.com>
  • Loading branch information
D4ryl00 committed Mar 26, 2021
1 parent 87d7e6c commit ba8fca0
Show file tree
Hide file tree
Showing 16 changed files with 1,027 additions and 560 deletions.
7 changes: 5 additions & 2 deletions js/android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -223,7 +223,10 @@ dependencies {
implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0"

implementation project(':react-native-share')
implementation 'com.google.android.gms:play-services-nearby:17.0.0'

// Add Android Nearby
implementation "com.google.android.gms:play-services-nearby:16.0.0"
implementation 'com.google.android.gms:play-services-location:17.0.0'

debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") {
exclude group:'com.facebook.fbjni'
Expand Down Expand Up @@ -263,4 +266,4 @@ project.ext.vectoricons = [
iconFontNames: [ 'Feather.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"
13 changes: 12 additions & 1 deletion js/android/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,25 @@
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.VIBRATE"/>

<!-- Extra permissions for Android Nearby -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="com.google.android.providers.gsf.permission.WRITE_GSERVICES" />
<uses-permission android:name="android.permission.NFC"/>
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />

<application
android:networkSecurityConfig="@xml/network_security_config"
android:name=".MainApplication"
android:label="@string/app_name"
android:icon="@mipmap/ic_launcher"
android:allowBackup="false"
android:requestLegacyExternalStorage="true"
android:theme="@style/AppTheme">
android:theme="@style/AppTheme"
android:extractNativeLibs="true">

<activity
android:name=".MainActivity"
android:label="@string/app_name"
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,250 @@
package tech.berty.gobridge;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import bertybridge.Bertybridge;
import bertybridge.NativeNBDriver;

import java.io.File;
import java.nio.charset.StandardCharsets;
import java.util.Base64;

import bertybridge.ProximityTransport;
import tech.berty.gobridge.proximitydriverssdk.base.NearbyDriverSDK;
import tech.berty.gobridge.proximitydriverssdk.lifecycle.UserAcceptCallback;
import tech.berty.gobridge.proximitydriverssdk.lifecycle.UserConnectionCallback;
import tech.berty.gobridge.proximitydriverssdk.lifecycle.UserMessageCallback;
import tech.berty.gobridge.proximitydriverssdk.lifecycle.UserRequestCallback;
import tech.berty.gobridge.proximitydriverssdk.lifecycle.UserSearchCallback;
import tech.berty.gobridge.proximitydriverssdk.model.Endpoint;

import static androidx.core.content.ContextCompat.checkSelfPermission;

public class BertyNearbyDriver implements NativeNBDriver {
private static final String TAG = "bty.NearbyDriver";

private static final String SERVICE_ID = "tech.berty.bty.nearby";

private static final String[] REQUIRED_PERMISSIONS =
new String[]{
Manifest.permission.BLUETOOTH,
Manifest.permission.BLUETOOTH_ADMIN,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.ACCESS_FINE_LOCATION,
};

public static final String DefaultAddr = "/nearby/Qmeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee";
public static final int ProtocolCode = 0x0044;
public static final String ProtocolName = "nearby";

private NearbyDriverSDK nearby;
private Context mContext;
private String localPID;

private static ProximityTransport mTransport;

UserConnectionCallback userConnectionCallback = new UserConnectionCallback() {
// onConnectionRequested is the entry point for incoming connections
// we have to check if there are duplicated endpoints
@Override
public void onConnectionRequested(String endpointName, String endpointId, boolean isIncomingRequest) {
Log.i(TAG, String.format("onConnectionRequested called: userId=%s userName=%s", endpointId, endpointName));

nearby.acceptConnection(endpointId, userMessageCallback, userAcceptCallback);
}

@Override
public void onConnectionResult(final String endpointId, String endpointName, boolean isConnected) {
Log.i(TAG, String.format("onConnectionResult called: userId=%s userName=%s", endpointId, endpointName));

if (isConnected) {
Log.i(TAG, "Connected");
// inform BertyBridge that there is a new connection
mTransport.handleFoundPeer(endpointName);
} else {
Log.e(TAG, "Rejected");
// connection was rejected this has to be added later on
Log.e(TAG, String.format("onConnectionResult REJECTED: endpointId=%s unknown", endpointId));
}
}

@Override
public void onDisconnected(String endpointId, String endpointName) {
Log.i(TAG, String.format("onDisconnected called: userId=%s userName=%s", endpointId, endpointName));

// inform BertyBridge that there is a new connection
mTransport.handleLostPeer(endpointName);
}
};

UserMessageCallback userMessageCallback = new UserMessageCallback() {
@Override
public void onMessageReceived(String userId, byte[] payload) {
Log.d(TAG, String.format("onMessageReceived: userId=%s payload=%s payload(hex)=%s", userId, Base64.getEncoder().encodeToString(payload), bytesToHex(payload)));
Endpoint endpoint = nearby.getConnectedUser(userId);
if (endpoint == null) {
Log.e(TAG, String.format("onMessageReceived error: endpointId=%s not found", userId));
return ;
}

mTransport.receiveFromPeer(endpoint.getName(), payload);
}

@Override
public void onFileReceived(String userId, File file) {
}
};

UserSearchCallback userSearchCallback = new UserSearchCallback() {
// onUserFound is the entry point for outgoing connections
// we have to check if there are duplicated endpoints
@Override
public void onUserFound(String userName, String userId) {
Log.i(TAG, String.format("onUserFound called: userName=%s userId=%s", userName, userId));

// Request and accept connection since both run at the same time there is no client/server
//nearby.acceptConnection(userId, userMessageCallback, userAcceptCallback);
nearby.connectTo(localPID, userId, userConnectionCallback, userRequestCallback);
}

@Override
public void onUserLost(String userId) {
Log.i(TAG, String.format("onUserLost called: userId=%s", userId));
}
};

private UserAcceptCallback userAcceptCallback = new UserAcceptCallback() {
@Override
public void onConnectionAccepted(boolean success, String userId, int error) {
Log.i(TAG, String.format("Connection accept: " + success + " : " + userId));

// Check if connection is not accepted and request
// We could handle error case here also accept request
if (!success) {
nearby.connectTo(localPID, userId, userConnectionCallback, userRequestCallback);
}
}
};

private UserRequestCallback userRequestCallback = new UserRequestCallback() {
@Override
public void onConnectionRequested(boolean requested, String userName, String userId, int error) {
Log.i(TAG, String.format("Connection request: " + requested + " : " + userName + " : " + userId));

// Handle multiple requests when error code
if (error == 8012) {
nearby.connectTo(localPID, userId, userConnectionCallback, userRequestCallback);
}
}
};

public BertyNearbyDriver(Context context) {
this.mContext = context;

// init driver and bridge
nearby = NearbyDriverSDK.getInstance(context.getApplicationContext());
}

private boolean hasPermissions(Context context, String... permissions) {
for (String permission : permissions) {
if (checkSelfPermission(context, permission)
!= PackageManager.PERMISSION_GRANTED) {
Log.e(TAG, String.format("hasPermissions error: permission=%s not GRANTED", permission));
return false;
}
}
Log.d(TAG, String.format("hasPermissions: all permissions are GRANTED"));
return true;
}

@Override
public void start(String localPID) {
this.localPID = localPID;

this.mTransport = Bertybridge.getProximityTransport(ProtocolName);
if (mTransport == null) {
Log.e(TAG, "proximityTransporter not found");
return ;
}

if (!hasPermissions(mContext, REQUIRED_PERMISSIONS))
{
Log.e(TAG, "start error: canceled");
return ;
}

nearby.startSearching(SERVICE_ID, userSearchCallback);
nearby.startSharing(localPID, SERVICE_ID, userConnectionCallback);
}

@Override
public void stop() {
nearby.stopSharing();
nearby.stopSearching();
}

@Override
public boolean dialPeer(String remotePID) {
if (nearby.getEndpointFromName(remotePID) != null) {
return true;
}
return false;
}

@Override
public boolean sendToPeer(String remotePID, byte[] payload) {
Log.d(TAG, String.format("sendToPeer: userName=%s payload=%s payload(hex)=%s", remotePID, Base64.getEncoder().encodeToString(payload), bytesToHex(payload)));
Endpoint endpoint = nearby.getEndpointFromName(remotePID);

if (endpoint != null) {
nearby.sendMessage(endpoint.getId(), payload);

return true;
}

Log.e(TAG, String.format("sendToPeer error: remotePID=%s not found", remotePID));
return false;
}

@Override
public void closeConnWithPeer(String remotePID) {
Endpoint endpoint = nearby.getEndpointFromName(remotePID);

if (endpoint != null) {
nearby.disconnectFrom(endpoint.getId());
}
}

@Override
public long protocolCode() {
return ProtocolCode;
}

@Override
public String protocolName() {
return ProtocolName;
}

@Override
public String defaultAddr() {
return DefaultAddr;
}

public static String bytesToHex(byte[] bytes) {
final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@
import bertybridge.Config;
import tech.berty.android.MainApplication;
import tech.berty.gobridge.bledriver.BleInterface;
import tech.berty.gobridge.nearby.NBInterface;

public class GoBridgeModule extends ReactContextBaseJavaModule {
private final static String TAG = "GoBridge";
Expand Down Expand Up @@ -121,7 +120,7 @@ public void initBridge(Promise promise) {
config.setBleDriver(bleDriver);

// set NearBy driver
NBInterface NBDriver = new NBInterface(reactContext);
BertyNearbyDriver NBDriver = new BertyNearbyDriver(reactContext);
config.setNBDriver(NBDriver);

System.out.println("bflifecycle: calling Bertybridge.newBridge");
Expand Down

0 comments on commit ba8fca0

Please sign in to comment.