Skip to content

Commit 994fee7

Browse files
authored
P2P Bluetooth peer discovery changes (#456)
* BT changes for common * Update cmakelist and bluetoothpeer enterprise check * Updated as build failure due to wrong checks and static declaration * Updating multipeer replicator argument to take protocol * Added release for BT peer and removed onIncommingConnection * Added documentation for APIs * Added public transport APIs and removed UUID sync * Updated the BluetoothPeer object creation in Java instead of native side * Updating addpeer and C4Peer creation and protocol usage * Conversion of MultipeerTransport and Enumset in java rather than in JNI part * Adding replicatorTansport API
1 parent b7bcaf7 commit 994fee7

16 files changed

Lines changed: 1016 additions & 9 deletions

android/main/AndroidManifest.xml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ limitations under the License.
2020
xmlns:tools="http://schemas.android.com/tools"
2121
>
2222

23+
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
2324
<uses-permission android:name="android.permission.INTERNET" />
2425
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
2526

common/CMakeLists.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,9 @@ add_library( LiteCoreJNI SHARED
6767
${JNI_SRC}/native_c4index.cc
6868
${JNI_SRC}/native_c4listener.cc
6969
${JNI_SRC}/native_c4multipeerreplicator.cc
70+
${JNI_SRC}/native_c4peerdiscoveryprovider.cc
71+
${JNI_SRC}/native_bluetoothpeer.cc
72+
${JNI_SRC}/MetadataHelper.cc
7073
${JNI_SRC}/native_c4observer.cc
7174
${JNI_SRC}/native_c4prediction.cc
7275
${JNI_SRC}/native_c4query.cc

common/main/cpp/MetadataHelper.cc

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
#if defined(COUCHBASE_ENTERPRISE) && defined(__ANDROID__)
2+
#include <jni.h>
3+
#include "c4PeerDiscovery.hh"
4+
#include "native_glue.hh"
5+
6+
namespace litecore::jni {
7+
// Helper to convert Java Map to Metadata
8+
C4Peer::Metadata javaMapToMetadata(JNIEnv* env, jobject map) {
9+
C4Peer::Metadata metadata;
10+
11+
if (!map) return metadata;
12+
13+
jclass mapClass = env->GetObjectClass(map);
14+
jmethodID entrySetMethod = env->GetMethodID(mapClass, "entrySet", "()Ljava/util/Set;");
15+
jobject entrySet = env->CallObjectMethod(map, entrySetMethod);
16+
17+
jclass setClass = env->GetObjectClass(entrySet);
18+
jmethodID toArrayMethod = env->GetMethodID(setClass, "toArray", "()[Ljava/lang/Object;");
19+
jobjectArray entries = (jobjectArray)env->CallObjectMethod(entrySet, toArrayMethod);
20+
21+
jsize entryCount = env->GetArrayLength(entries);
22+
23+
jclass entryClass = env->FindClass("java/util/Map$Entry");
24+
jmethodID getKeyMethod = env->GetMethodID(entryClass, "getKey", "()Ljava/lang/Object;");
25+
jmethodID getValueMethod = env->GetMethodID(entryClass, "getValue", "()Ljava/lang/Object;");
26+
27+
for (jsize i = 0; i < entryCount; i++) {
28+
jobject entry = env->GetObjectArrayElement(entries, i);
29+
jstring jKey = (jstring)env->CallObjectMethod(entry, getKeyMethod);
30+
jbyteArray jValue = (jbyteArray)env->CallObjectMethod(entry, getValueMethod);
31+
32+
std::string key = JstringToUTF8(env, jKey);
33+
jbyteArraySlice value(env, jValue);
34+
35+
metadata[std::string(key)] = fleece::alloc_slice(value);
36+
37+
env->DeleteLocalRef(entry);
38+
env->DeleteLocalRef(jKey);
39+
env->DeleteLocalRef(jValue);
40+
}
41+
42+
env->DeleteLocalRef(entrySet);
43+
env->DeleteLocalRef(entries);
44+
45+
return metadata;
46+
}
47+
48+
49+
jobject metadataToJavaMap(JNIEnv* env, const C4Peer::Metadata& metadata) {
50+
// Create HashMap
51+
jclass hashMapClass = env->FindClass("java/util/HashMap");
52+
jmethodID hashMapInit = env->GetMethodID(hashMapClass, "<init>", "(I)V");
53+
jobject hashMap = env->NewObject(hashMapClass, hashMapInit);
54+
55+
// Put method for HashMap
56+
jmethodID hashMapPut = env->GetMethodID(
57+
hashMapClass, "put",
58+
"(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"
59+
);
60+
61+
// Convert each key-value pair
62+
for (const auto& [key, value] : metadata) {
63+
// Convert key to Java String
64+
jstring jKey = UTF8ToJstring(env, key.c_str(), key.size());
65+
66+
// Convert value (fleece::alloc_slice) to Java byte[]
67+
jbyteArray jValue = toJByteArray(env, value);
68+
69+
// Put in map
70+
env->CallObjectMethod(hashMap, hashMapPut, jKey, jValue);
71+
72+
// Clean up local references
73+
env->DeleteLocalRef(jKey);
74+
env->DeleteLocalRef(jValue);
75+
}
76+
77+
env->DeleteLocalRef(hashMapClass);
78+
return hashMap;
79+
}
80+
}
81+
#endif

common/main/cpp/MetadataHelper.h

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#if defined(COUCHBASE_ENTERPRISE) && defined(__ANDROID__)
2+
#include <jni.h>
3+
4+
#include "c4PeerDiscovery.hh"
5+
6+
#ifndef COUCHBASE_LITE_JAVA_EE_ROOT_METADATAHELPER_H
7+
#define COUCHBASE_LITE_JAVA_EE_ROOT_METADATAHELPER_H
8+
9+
namespace litecore::jni {
10+
C4Peer::Metadata javaMapToMetadata(JNIEnv* env, jobject map);
11+
jobject metadataToJavaMap(JNIEnv* env, const C4Peer::Metadata& metadata);
12+
}
13+
14+
#endif //COUCHBASE_LITE_JAVA_EE_ROOT_METADATAHELPER_H
15+
#endif
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
2+
# P2P Bluetooth LE Synchronization Documentation
3+
4+
## 1. Overview
5+
6+
This document provides a detailed explanation of the P2P synchronization feature using Bluetooth Low Energy (BLE). The feature allows Couchbase Lite enabled devices to discover each other and synchronize data directly without the need for a central server.
7+
8+
## 2. Architecture
9+
10+
The P2P synchronization feature is built on a hybrid architecture that leverages both Java and C++ code.
11+
12+
* **Java Layer**: The Java layer is responsible for all platform-specific Bluetooth LE operations. This includes scanning for nearby devices, advertising the device's presence, and managing Bluetooth connections. By delegating these tasks to the Java layer, we ensure that the application can take advantage of the latest Android Bluetooth APIs and best practices.
13+
14+
* **C++ Layer**: The C++ layer contains the core logic for peer discovery and data synchronization. It is responsible for managing the state of discovered peers, handling metadata exchange, and orchestrating the overall synchronization process. The C++ layer communicates with the Java layer through the Java Native Interface (JNI).
15+
16+
This separation of concerns allows for a clean and maintainable codebase. The C++ layer remains platform-agnostic, while the Java layer handles the intricacies of the Android Bluetooth stack.
17+
18+
## 3. C++ Class Descriptions
19+
20+
### 3.1. `C4BLEProvider`
21+
22+
The `C4BLEProvider` class is the heart of the peer discovery process. It is a C++ class that runs in the native layer and is responsible for the following:
23+
24+
* **Starting and Stopping Peer Discovery**: The `C4BLEProvider` can be instructed to start or stop scanning for nearby peers. When scanning is active, the provider will notify the application of any discovered peers.
25+
* **Publishing the Device's Presence**: The `C4BLEProvider` can also be used to advertise the device's presence to other peers. This allows other devices to discover and connect to it.
26+
* **Managing Discovered Peers**: The `C4BLEProvider` maintains a list of all discovered peers and their current status (online or offline).
27+
* **Forwarding Calls to the Java Layer**: The `C4BLEProvider` uses JNI to forward calls to the Java layer for all Bluetooth-specific operations.
28+
29+
### 3.2. `C4Peer`
30+
31+
The `C4Peer` class represents a discovered peer in the network. It is a C++ class that contains the following information about a peer:
32+
33+
* **Peer ID**: A unique identifier for the peer.
34+
* **Online Status**: A boolean flag that indicates whether the peer is currently online and reachable.
35+
* **Metadata**: A collection of key-value pairs that can be used to store additional information about the peer.
36+
37+
The `C4Peer` class provides methods for getting and setting the peer's metadata, as well as for monitoring changes to the metadata.
38+
39+
### 3.3. `MetadataHelper`
40+
41+
The `MetadataHelper` is a C++ utility class that provides functions for converting between Java `Map` objects and the `C4Peer::Metadata` type. This is necessary because the metadata is exchanged between the Java and C++ layers as part of the peer discovery and synchronization process.
42+
43+
## 4. Java Class Descriptions
44+
45+
### 4.1. `BluetoothProvider`
46+
47+
The `BluetoothProvider` class is the main entry point for the Java-side of the P2P implementation. It acts as a bridge between the native C++ code and the Java-based `BleService`. It is responsible for:
48+
49+
* Creating and managing `BleService` instances.
50+
* Forwarding calls from the native layer to the `BleService` for starting/stopping browsing and publishing.
51+
* Handling callbacks from the `BleService` and forwarding them to the native layer.
52+
53+
### 4.2. `BluetoothPeer`
54+
55+
The `BluetoothPeer` class is the Java representation of a discovered peer. It mirrors the C++ `C4Peer` class and provides a high-level API for interacting with a peer. It is responsible for:
56+
57+
* Storing the peer's ID, online status, and metadata.
58+
* Providing methods for monitoring metadata changes and resolving the peer's URL.
59+
60+
### 4.3. `BleService`
61+
62+
The `BleService` class is the core of the Java-side implementation. It manages all Bluetooth LE operations, including:
63+
64+
* **Scanning**: It starts and stops scanning for nearby devices that are advertising the Couchbase Lite P2P service.
65+
* **Device Management**: It maintains a list of discovered devices (`CblBleDevice`) and manages their connection state.
66+
* **Publishing**: It coordinates with the `BlePublisher` to advertise the device's presence.
67+
* **L2CAP Connections**: It initiates L2CAP connections to discovered peers.
68+
69+
### 4.4. `BlePublisher`
70+
71+
The `BlePublisher` class is responsible for advertising the device's presence to other peers. It handles the complexities of BLE advertising, including:
72+
73+
* Starting and stopping advertising with the appropriate settings.
74+
* Managing the advertising lifecycle and handling failures.
75+
* Working in conjunction with the `BleGattServer` to host the Couchbase Lite service.
76+
77+
### 4.5. `CblBleDevice`
78+
79+
The `CblBleDevice` class represents a remote Bluetooth LE device that has been discovered by the `BleService`. It is responsible for:
80+
81+
* Managing the GATT connection to the remote device.
82+
* Discovering the Couchbase Lite P2P service and its characteristics.
83+
* Reading the peer's ID, port, and metadata from the GATT characteristics.
84+
* Initiating an L2CAP connection to the remote device.
85+
86+
### 4.6. `BleGattServer`
87+
88+
The `BleGattServer` class is responsible for creating and managing the GATT server that hosts the Couchbase Lite P2P service. Its key responsibilities include:
89+
90+
* Creating the GATT service with the required characteristics (ID, port, metadata).
91+
* Handling read requests for the characteristics from remote devices.
92+
* Optionally starting an L2CAP server to listen for incoming connections.
93+
94+
### 4.7. `BleL2CAPConnection`
95+
96+
The `BleL2CAPConnection` class is a wrapper around a BluetoothSocket that provides a simple interface for sending and receiving data over an L2CAP connection. It handles:
97+
98+
* Reading data from the socket in a background thread.
99+
* Writing data to the socket asynchronously.
100+
* Notifying a listener of incoming data and connection closure.
101+
102+
### 4.8. `BleP2pConstants`
103+
104+
This class defines the UUIDs for the Couchbase Lite P2P service and its characteristics, as well as other constants used by the BLE implementation.
105+
106+
### 4.9. Listeners and Handles
107+
108+
* **`BlePublisherListener`**: An interface for receiving lifecycle events from the `BlePublisher`.
109+
* **`BlePublisherHandle`**: A handle that allows for stopping an active advertising session.
110+
* **`BleGattInboundListener`**: An interface for receiving events related to inbound L2CAP connections.
111+
112+
## 5. Flows
113+
114+
### 5.1. Peer Discovery
115+
116+
The peer discovery process is initiated by the application, which calls the `startBrowsing()` method on the `C4BLEProvider` object. The `C4BLEProvider` then forwards this call to the Java layer, which begins scanning for nearby Bluetooth LE devices.
117+
118+
When a new device is discovered, the Java layer notifies the `C4BLEProvider`, which creates a new `C4Peer` object to represent the device. The `C4BLEProvider` then adds the new `C4Peer` to its list of discovered peers and notifies the application.
119+
120+
### 5.2. Publishing
121+
122+
To make itself discoverable to other devices, the application calls the `startPublishing()` method on the `C4BLEProvider` object. The `C4BLEProvider` then forwards this call to the Java layer, which begins advertising the device's presence.
123+
124+
The advertisement packet contains a service UUID that is specific to the application, as well as the device's display name and other relevant information.
125+
126+
### 5.3. Metadata Exchange
127+
128+
The P2P synchronization feature allows for the exchange of metadata between peers. This metadata can be used to store any application-specific information, such as the user's name or the device's capabilities.
129+
130+
The metadata is exchanged as part of the peer discovery process. When a device discovers a new peer, it can request the peer's metadata. The metadata is then sent over the Bluetooth connection and stored in the `C4Peer` object.
131+
132+
The application can also monitor changes to a peer's metadata. When the metadata changes, the `C4BLEProvider` will notify the application, which can then take appropriate action.
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
#ifndef COUCHBASE_LITE_JAVA_EE_ROOT_COM_COUCHBASE_LITE_INTERNAL_CORE_IMPL_NATIVEBLUETOOTHPEER_H
2+
#define COUCHBASE_LITE_JAVA_EE_ROOT_COM_COUCHBASE_LITE_INTERNAL_CORE_IMPL_NATIVEBLUETOOTHPEER_H
3+
4+
#pragma once
5+
6+
#include <jni.h>
7+
8+
#ifdef __cplusplus
9+
extern "C++" {
10+
#endif
11+
12+
/*
13+
* Class: com_couchbase_lite_internal_core_impl_NativeBluetoothPeer
14+
* Method: getId
15+
* Signature: (J)Ljava/lang/String;
16+
*/
17+
JNIEXPORT jstring JNICALL
18+
Java_com_couchbase_lite_internal_core_impl_NativeBluetoothPeer_getId(
19+
JNIEnv *, jclass, jlong);
20+
21+
/*
22+
* Class: com_couchbase_lite_internal_core_impl_NativeBluetoothPeer
23+
* Method: isOnline
24+
* Signature: (J)Z
25+
*/
26+
JNIEXPORT jboolean JNICALL
27+
Java_com_couchbase_lite_internal_core_impl_NativeBluetoothPeer_isOnline(
28+
JNIEnv *, jclass, jlong);
29+
30+
/*
31+
* Class: com_couchbase_lite_internal_core_impl_NativeBluetoothPeer
32+
* Method: getAllMetadata
33+
* Signature: (J)Ljava/util/Map;
34+
*/
35+
JNIEXPORT jobject JNICALL
36+
Java_com_couchbase_lite_internal_core_impl_NativeBluetoothPeer_getAllMetadata(
37+
JNIEnv *, jclass, jlong);
38+
39+
40+
/*
41+
* Class: com_couchbase_lite_internal_core_impl_NativeBluetoothPeer
42+
* Method: setMetadata
43+
* Signature: (JLjava/util/Map;)V
44+
*/
45+
JNIEXPORT void JNICALL
46+
Java_com_couchbase_lite_internal_core_impl_NativeBluetoothPeer_setMetadata(
47+
JNIEnv *, jclass, jlong, jobject);
48+
49+
/*
50+
* Class: com_couchbase_lite_internal_core_impl_NativeBluetoothPeer
51+
* Method: monitorMetadata
52+
* Signature: (JZ)V
53+
*/
54+
JNIEXPORT void JNICALL
55+
Java_com_couchbase_lite_internal_core_impl_NativeBluetoothPeer_monitorMetadata(
56+
JNIEnv *, jclass, jlong, jboolean);
57+
58+
JNIEXPORT void JNICALL
59+
Java_com_couchbase_lite_internal_core_impl_NativeBluetoothPeer_resolvedURL(
60+
JNIEnv *env, jclass clazz, jlong peerPtr, jstring jurl);
61+
62+
/*
63+
* Class: com_couchbase_lite_internal_core_impl_NativeBluetoothPeer
64+
* Method: release
65+
* Signature: (JZ)V
66+
*/
67+
JNIEXPORT void JNICALL
68+
Java_com_couchbase_lite_internal_core_impl_NativeBluetoothPeer_release(
69+
JNIEnv *env, jclass clazz, jlong peerPtr);
70+
71+
#ifdef __cplusplus
72+
}
73+
#endif
74+
75+
#endif //COUCHBASE_LITE_JAVA_EE_ROOT_COM_COUCHBASE_LITE_INTERNAL_CORE_IMPL_NATIVEBLUETOOTHPEER_H

common/main/cpp/com_couchbase_lite_internal_core_impl_NativeC4MultipeerReplicator.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ JNICALL Java_com_couchbase_lite_internal_core_impl_NativeC4MultipeerReplicator_c
2020
jclass,
2121
jlong,
2222
jstring,
23+
jint,
2324
jlong,
2425
jbyteArray,
2526
jlong,
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
#include <jni.h>
2+
3+
#ifndef COUCHBASE_LITE_JAVA_EE_ROOT_COM_COUCHBASE_LITE_INTERNAL_CORE_IMPL_NATIVEC4PEERDISCOVERYPROVIDER_H
4+
#define COUCHBASE_LITE_JAVA_EE_ROOT_COM_COUCHBASE_LITE_INTERNAL_CORE_IMPL_NATIVEC4PEERDISCOVERYPROVIDER_H
5+
6+
#ifdef __cplusplus
7+
extern "C++" {
8+
#endif
9+
10+
JNIEXPORT jlong JNICALL
11+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_create(
12+
JNIEnv *, jclass, jlong, jstring);
13+
14+
15+
JNIEXPORT void JNICALL
16+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_free(
17+
JNIEnv *, jclass, jlong);
18+
19+
JNIEXPORT void JNICALL
20+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_peerDiscovered(
21+
JNIEnv *env, jclass thiz, jlong providerPtr, jstring peerId, jobject metadata);
22+
23+
JNIEXPORT void JNICALL
24+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_peerLost(
25+
JNIEnv *env, jclass thiz, jlong providerPtr, jstring peerId);
26+
27+
28+
JNIEXPORT void JNICALL
29+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_onIncomingConnection(
30+
JNIEnv *env, jclass thiz, jlong providerPtr, jbyteArray peerId, jlong socketPtr);
31+
32+
JNIEXPORT jlong JNICALL
33+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_addPeer(
34+
JNIEnv *env, jclass thiz, jlong providerPtr, jstring peerId);
35+
36+
JNIEXPORT void JNICALL
37+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_removePeer(
38+
JNIEnv *env, jclass thiz, jlong providerPtr, jstring peerId);
39+
40+
JNIEXPORT jlong JNICALL
41+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_peerWithID(
42+
JNIEnv *env, jclass thiz, jlong providerPtr, jstring peerId);
43+
44+
JNIEXPORT void JNICALL
45+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_statusChanged(
46+
JNIEnv *env, jclass thiz, jlong providerPtr, jint mode, jboolean online,
47+
jint errorDomain, jint errorCode);
48+
49+
JNIEXPORT jlongArray JNICALL
50+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_peersWithProvider(
51+
JNIEnv *env, jclass thiz, jlong providerPtr);
52+
53+
JNIEXPORT jstring JNICALL
54+
Java_com_couchbase_lite_internal_core_impl_NativeC4PeerDiscoveryProvider_serviceUuidFromPeerGroup(
55+
JNIEnv* env, jclass, jstring peerGroup);
56+
57+
#ifdef __cplusplus
58+
}
59+
#endif
60+
61+
#endif //COUCHBASE_LITE_JAVA_EE_ROOT_COM_COUCHBASE_LITE_INTERNAL_CORE_IMPL_NATIVEC4PEERDISCOVERYPROVIDER_H

0 commit comments

Comments
 (0)