BREAKING CHANGE: Update API for connection, communication channel state and is browser value (#14)

* refactor(lib, example, example_full): use streams for communication channel and is ios browser

* feat: add abstract toJson() to message

* refactor: add deprecations for nearby_service

* feat(example): update main.dart

* feat(nearby_service): add comments

* feat(nearby_service_platform_interface): add deprecation to getConnectedDeviceStream

* feat(nearby_service/message): add concrete implementation for toJson()

* feat(nearby_service/android): add deprecations

* fix(nearby_service/android): reset check for android device

* fix(nearby_service/ios): change ios service to deprecations variant

* chore(nearby_service): edit deprecation messages

* chore: update gitignore

* doc: add CONTRIBUTING file

* doc: update CONTRIBUTING file

* chore: update CONTRIBUTING.md

* chore: update CONTRIBUTING.md

* chore: version 0.1.0

* fix(example_full): move startListeningCommunicationChannelState() upper
This commit is contained in:
Kseniia Nikitina
2024-08-18 15:42:53 +02:00
committed by GitHub
parent 1818166d06
commit 7049c39cf0
15 changed files with 388 additions and 79 deletions
+83 -9
View File
@@ -74,8 +74,26 @@ abstract class NearbyService {
/// For **IOS** this is the state of the message stream subscription.
/// which is generated for the device with the current connected device ID.
///
@Deprecated(
'Use getCommunicationChannelStateStream or communicationChannelStateValue instead',
)
ValueListenable<CommunicationChannelState> get communicationChannelState;
///
/// **A value to determine the communication channel's status.**
///
/// For **Android** this is the socket connection state.
/// The server can wait for the client to connect,
/// and the client can be waiting for the server to be created.
/// Also, both can be in connected and unconnected states.
///
/// For **IOS** this is the state of the message stream subscription.
/// which is generated for the device with the current connected device ID.
///
/// **Can be used to retrieve the current state of the communication channel without listening to the stream via** [getCommunicationChannelStateStream].
///
CommunicationChannelState get communicationChannelStateValue;
///
/// Gets version of current platform.
///
@@ -147,10 +165,20 @@ abstract class NearbyService {
/// Returns the constantly updating [NearbyDevice] you are currently connected to.
/// If it returns null, then there is no connection at the moment.
///
@Deprecated('Use getConnectedDeviceStreamById instead')
Stream<NearbyDevice?> getConnectedDeviceStream(NearbyDevice device) {
return NearbyServicePlatform.instance.getConnectedDeviceStream(device);
}
///
/// Returns the constantly updating [NearbyDevice] you are currently connected to.
/// If it returns null, then there is no connection at the moment.
///
Stream<NearbyDevice?> getConnectedDeviceStreamById(String deviceId) {
return NearbyServicePlatform.instance
.getConnectedDeviceStreamById(deviceId);
}
///
/// Initialization of a platform-specific service.
///
@@ -166,7 +194,7 @@ abstract class NearbyService {
/// Starts searching for devices using a platform-specific service.
///
/// Note that the [NearbyIOSService] implementation starts **browsing** or
/// **advertising** depending on the [NearbyIOSService.isBrowser].
/// **advertising** depending on the [NearbyIOSService.isBrowserValue].
///
/// On Android can throw mapped from native platform exceptions:
/// 1. [NearbyServiceBusyException]
@@ -181,7 +209,7 @@ abstract class NearbyService {
/// Stops searching for devices using a platform-specific service.
///
/// Note that the [NearbyIOSService] implementation stops **browsing** or
/// **advertising** depending on the [NearbyIOSService.isBrowser].
/// **advertising** depending on the [NearbyIOSService.isBrowserValue].
///
/// On Android can throw mapped from native platform exceptions:
/// 1. [NearbyServiceBusyException]
@@ -208,16 +236,18 @@ abstract class NearbyService {
/// 4. [NearbyServiceGenericErrorException]
/// 5. [NearbyServiceUnknownException]
///
@Deprecated('Use connectById instead')
Future<bool> connect(NearbyDevice device);
///
/// Disconnects from passed [device] using a platform-specific service.
/// Connects to passed [deviceId] using a platform-specific service.
///
/// Note that the [NearbyIOSService] implementation **invites** or
/// **accepts invite** depending on the [NearbyIOSService.isBrowserValue].
///
/// Note that if [Platform.isIOS] == true, [NearbyIOSDevice] should be passed.
/// If [Platform.isAndroid] == true, [NearbyAndroidDevice] should be passed.
///
/// **For IOS [device] is required!!!**
///
/// On Android can throw mapped from native platform exceptions:
/// 1. [NearbyServiceBusyException]
/// 2. [NearbyServiceP2PUnsupportedException]
@@ -225,8 +255,41 @@ abstract class NearbyService {
/// 4. [NearbyServiceGenericErrorException]
/// 5. [NearbyServiceUnknownException]
///
Future<bool> connectById(String deviceId);
///
/// Disconnects from passed [device] using a platform-specific service.
///
/// Note that if [Platform.isIOS] == true, [NearbyIOSDevice] should be passed.
/// If [Platform.isAndroid] == true, [NearbyAndroidDevice] should be passed.
///
/// On Android can throw mapped from native platform exceptions:
/// 1. [NearbyServiceBusyException]
/// 2. [NearbyServiceP2PUnsupportedException]
/// 3. [NearbyServiceNoServiceRequestsException]
/// 4. [NearbyServiceGenericErrorException]
/// 5. [NearbyServiceUnknownException]
///
/// **For IOS [device] is required!!!**
@Deprecated('Use disconnectById instead')
Future<bool> disconnect([NearbyDevice? device]);
///
/// Disconnects from passed [deviceId] using a platform-specific service.
///
/// Note that if [Platform.isIOS] == true, [NearbyIOSDevice] should be passed.
/// If [Platform.isAndroid] == true, [NearbyAndroidDevice] should be passed.
///
/// On Android can throw mapped from native platform exceptions:
/// 1. [NearbyServiceBusyException]
/// 2. [NearbyServiceP2PUnsupportedException]
/// 3. [NearbyServiceNoServiceRequestsException]
/// 4. [NearbyServiceGenericErrorException]
/// 5. [NearbyServiceUnknownException]
///
/// **For IOS [deviceId] is required!!!**
Future<bool> disconnectById([String? deviceId]);
///
/// If the device is already connected, it does not mean that you can
/// send and receive data.
@@ -235,11 +298,9 @@ abstract class NearbyService {
/// You need to call [startCommunicationChannel] before using [send].
/// A communication channel can only be created if you are connected to some device.
///
/// You can monitor changes in communication channel state using the [communicationChannelState] getter.
/// You can monitor changes in communication channel state using the [getCommunicationChannelStateStream] method.
///
FutureOr<bool> startCommunicationChannel(
NearbyCommunicationChannelData data,
);
FutureOr<bool> startCommunicationChannel(NearbyCommunicationChannelData data);
///
/// If you called [startCommunicationChannel], remember that you have
@@ -250,6 +311,19 @@ abstract class NearbyService {
///
FutureOr<bool> endCommunicationChannel();
///
/// **A stream with values of [CommunicationChannelState] to determine the communication channel's status.**
///
/// For **Android** this is the socket connection state.
/// The server can wait for the client to connect,
/// and the client can be waiting for the server to be created.
/// Also, both can be in connected and unconnected states.
///
/// For **IOS** this is the state of the message stream subscription.
/// which is generated for the device with the current connected device ID.
///
Stream<CommunicationChannelState> getCommunicationChannelStateStream();
///
/// Method to send data to the created communication channel.
///
+7 -3
View File
@@ -54,13 +54,17 @@ class MethodChannelNearbyService extends NearbyServicePlatform {
}
@override
@Deprecated('Use getConnectedDeviceStreamById instead')
Stream<NearbyDevice?> getConnectedDeviceStream(NearbyDevice device) {
return getConnectedDeviceStreamById(device.info.id);
}
@override
Stream<NearbyDevice?> getConnectedDeviceStreamById(String deviceId) {
const connectedDeviceChannel = EventChannel(
"nearby_service_connected_device",
);
return connectedDeviceChannel
.receiveBroadcastStream(device.info.id)
.map((e) {
return connectedDeviceChannel.receiveBroadcastStream(deviceId).map((e) {
final updatedResult = ResultHandler.instance.handle(e);
return NearbyDeviceMapper.instance.mapToDevice(updatedResult);
});
@@ -48,11 +48,21 @@ abstract class NearbyServicePlatform extends PlatformInterface {
throw UnimplementedError('streamPeers() has not been implemented.');
}
@Deprecated('Use getConnectedDeviceStreamById instead')
Stream<NearbyDevice?> getConnectedDeviceStream(NearbyDevice device) {
throw UnimplementedError(
'getConnectedDeviceStream() has not been implemented.');
}
Stream<NearbyDevice?> getConnectedDeviceStreamById(String deviceId) {
throw UnimplementedError(
'getConnectedDeviceStreamById() has not been implemented.',
);
}
@Deprecated(
'This method will be removed. Method disconnect is platform-specific and you should use NearbyServiceIOSPlatform.disconnectById or NearbyServiceAndroidPlatform.disconnectById instead.',
)
Future<bool> disconnect(NearbyDevice device) {
throw UnimplementedError('disconnect() has not been implemented.');
}
+7
View File
@@ -1,3 +1,4 @@
import 'package:flutter/foundation.dart';
import 'package:nearby_service/nearby_service.dart';
///
@@ -36,4 +37,10 @@ abstract base class NearbyMessage<C extends NearbyMessageContent> {
String toString() {
return 'NearbyMessage{content: $content}';
}
///
/// Get [Map] from [NearbyMessage].
///
@mustCallSuper
Map<String, dynamic> toJson() => {'content': content.toJson()};
}
+13 -1
View File
@@ -23,10 +23,11 @@ final class OutgoingNearbyMessage<C extends NearbyMessageContent>
///
/// Get [Map] from [OutgoingNearbyMessage].
///
@override
Map<String, dynamic> toJson() {
return {
'content': content.toJson(),
'receiver': receiver.toJson(),
...super.toJson(),
};
}
@@ -92,4 +93,15 @@ final class ReceivedNearbyMessage<C extends NearbyMessageContent>
String toString() {
return 'ReceivedNearbyMessage{sender: $sender content: $content}';
}
///
/// Get [Map] from [ReceivedNearbyMessage].
///
@override
Map<String, dynamic> toJson() {
return {
'sender': sender.toJson(),
...super.toJson(),
};
}
}
@@ -1,5 +1,4 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:nearby_service/nearby_service.dart';
@@ -14,10 +13,16 @@ import 'socket_service/nearby_socket_service.dart';
class NearbyAndroidService extends NearbyService {
late final _socketService = NearbySocketService(this);
@Deprecated(
'Use getCommunicationChannelStateStream or communicationChannelStateValue instead',
)
@override
ValueListenable<CommunicationChannelState> get communicationChannelState {
return _socketService.state;
}
ValueListenable<CommunicationChannelState> get communicationChannelState =>
_socketService.communicationChannelState;
@override
CommunicationChannelState get communicationChannelStateValue =>
_socketService.communicationChannelStateValue;
///
/// Initializes Android [WifiP2PManager](https://developer.android.com/reference/android/net/wifi/p2p/WifiP2pManager)
@@ -53,19 +58,39 @@ class NearbyAndroidService extends NearbyService {
///
/// Note! Requires [NearbyAndroidDevice] to be passed.
///
@Deprecated('Use connectById instead')
@override
Future<bool> connect(NearbyDevice device) {
_requireAndroidDevice(device);
return NearbyServiceAndroidPlatform.instance.connect(device.info.id);
}
///
/// Connects to the [deviceId] on the Wifi Direct network.
///
@override
Future<bool> connectById(String deviceId) {
return NearbyServiceAndroidPlatform.instance.connect(deviceId);
}
///
/// Disconnects from the [device] on the Wifi Direct network.
///
/// [device] is not required for Android.
///
@Deprecated('Use disconnectById instead')
@override
Future<bool> disconnect([NearbyDevice? device]) {
return NearbyServiceAndroidPlatform.instance.disconnect();
}
///
/// Disconnects from the [deviceId] on the Wifi Direct network.
///
/// Note! Requires [NearbyAndroidDevice] to be passed.
///
@override
Future<bool> disconnect([NearbyDevice? device]) {
Future<bool> disconnectById([String? deviceId]) {
return NearbyServiceAndroidPlatform.instance.disconnect();
}
@@ -143,6 +168,11 @@ class NearbyAndroidService extends NearbyService {
return NearbyServiceAndroidPlatform.instance.getConnectionInfoStream();
}
@override
Stream<CommunicationChannelState> getCommunicationChannelStateStream() {
return _socketService.stateController.stream.asBroadcastStream();
}
void _requireAndroidDevice(NearbyDevice device) {
assert(
device is NearbyAndroidDevice,
@@ -30,7 +30,10 @@ class NearbySocketService {
_pingManager,
);
final state = ValueNotifier(CommunicationChannelState.notConnected);
late final stateController =
StreamController<CommunicationChannelState>.broadcast()
..add(_state.value)
..stream.asBroadcastStream().listen((e) => _state.value = e);
NearbyAndroidCommunicationChannelData _androidData =
const NearbyAndroidCommunicationChannelData();
@@ -40,6 +43,13 @@ class NearbySocketService {
HttpServer? _server;
StreamSubscription? _messagesSubscription;
final _state = ValueNotifier(CommunicationChannelState.notConnected);
CommunicationChannelState get communicationChannelStateValue => _state.value;
ValueListenable<CommunicationChannelState> get communicationChannelState =>
_state;
///
/// Start a socket with the user's role defined.
/// If he is the owner of the group, he becomes a server.
@@ -53,7 +63,7 @@ class NearbySocketService {
Future<bool> startSocket({
required NearbyCommunicationChannelData data,
}) async {
state.value = CommunicationChannelState.loading;
stateController.add(CommunicationChannelState.loading);
_androidData = data.androidData;
_connectedDeviceId = data.connectedDeviceId;
@@ -123,7 +133,7 @@ class NearbySocketService {
_server = null;
_connectedDeviceId = null;
state.value = CommunicationChannelState.notConnected;
stateController.add(CommunicationChannelState.notConnected);
return true;
} catch (e) {
return false;
@@ -134,7 +144,7 @@ class NearbySocketService {
required NearbyServiceMessagesListener socketListener,
required NearbyConnectionAndroidInfo info,
}) async {
if (state.value.isLoading) {
if (_state.value.isLoading) {
final response = await _network.pingServer(
address: info.ownerIpAddress,
port: _androidData.port,
@@ -216,23 +226,23 @@ class NearbySocketService {
}
},
onDone: () {
state.value = CommunicationChannelState.notConnected;
stateController.add(CommunicationChannelState.notConnected);
socketListener.onDone?.call();
},
onError: (e, s) {
Logger.error(e);
state.value = CommunicationChannelState.notConnected;
stateController.add(CommunicationChannelState.notConnected);
socketListener.onError?.call(e, s);
},
cancelOnError: socketListener.cancelOnError,
);
}
if (_messagesSubscription != null) {
state.value = CommunicationChannelState.connected;
stateController.add(CommunicationChannelState.connected);
Logger.info('Socket subscription was created successfully');
socketListener.onCreated?.call();
} else {
state.value = CommunicationChannelState.notConnected;
stateController.add(CommunicationChannelState.notConnected);
}
}
+88 -32
View File
@@ -14,29 +14,56 @@ import 'package:nearby_service/src/utils/stream_mapper.dart';
///
class NearbyIOSService extends NearbyService {
final _isBrowser = ValueNotifier<bool>(true);
final _state = ValueNotifier(CommunicationChannelState.notConnected);
final _communicationChannelState =
ValueNotifier(CommunicationChannelState.notConnected);
late final _isBrowserController = StreamController<bool>.broadcast()
..add(_isBrowser.value)
..stream.asBroadcastStream().listen((e) => _isBrowser.value = e);
late final _stateController =
StreamController<CommunicationChannelState>.broadcast()
..add(_communicationChannelState.value)
..stream
.asBroadcastStream()
.listen((e) => _communicationChannelState.value = e);
StreamSubscription? _messagesSubscription;
StreamSubscription? _resourcesSubscription;
@override
CommunicationChannelState get communicationChannelStateValue =>
_communicationChannelState.value;
@override
@Deprecated(
'Use getCommunicationChannelStateStream or communicationChannelStateValue instead',
)
ValueListenable<CommunicationChannelState> get communicationChannelState =>
_state;
_communicationChannelState;
///
/// Determines whether the current device is a **Browser** or **Advertiser**.
///
@Deprecated('Use getIsBrowserStream or isBrowserValue instead')
ValueListenable<bool> get isBrowser => _isBrowser;
///
/// Determines whether the current device is a **Browser** or **Advertiser**.
///
bool get isBrowserValue => _isBrowser.value;
///
/// Stream that determines whether the current device is a **Browser** or **Advertiser**.
///
/// * Browser will only see devices with Advertiser status in the peers list.
/// Browser sends connection requests.
/// * Advertiser will see in the peers list only devices with Browser
/// status that have sent it a connection request.
/// Advertiser accepts or rejects connection requests.
///
ValueListenable<bool> get isBrowser => _isBrowser;
String get _currentConnectionType {
return _isBrowser.value ? 'browsing' : 'advertising';
}
Stream<bool> getIsBrowserStream() =>
_isBrowserController.stream.asBroadcastStream();
///
/// Initializes [MCNearbyServiceAdvertiser](https://developer.apple.com/documentation/multipeerconnectivity/mcnearbyserviceadvertiser)
@@ -73,8 +100,8 @@ class NearbyIOSService extends NearbyService {
///
/// Starts discovery on the local P2P network.
///
/// Starts browsing for peers if [isBrowser] is true.
/// Starts advertising for peers if [isBrowser] is false.
/// Starts browsing for peers if [isBrowserValue] is true.
/// Starts advertising for peers if [isBrowserValue] is false.
///
@override
Future<bool> discover() async {
@@ -92,8 +119,8 @@ class NearbyIOSService extends NearbyService {
///
/// Slops discovery on the local P2P network.
///
/// Slops browsing for peers if [isBrowser] is true.
/// Slops advertising for peers if [isBrowser] is false.
/// Slops browsing for peers if [isBrowserValue] is true.
/// Slops advertising for peers if [isBrowserValue] is false.
///
@override
Future<bool> stopDiscovery() async {
@@ -112,24 +139,35 @@ class NearbyIOSService extends NearbyService {
///
/// Connects to the [device] on the P2P network.
///
/// Invites [device] if [isBrowser] is true.
/// Accepts invite from [device] if [isBrowser] is false.
/// Invites [device] if [isBrowserValue] is true.
/// Accepts invite from [device] if [isBrowserValue] is false.
///
/// Note! Requires [NearbyIOSDevice] to be passed.
///
@Deprecated('Use connectById instead')
@override
Future<bool> connect(NearbyDevice device) async {
_requireIOSDevice(device);
return connectById(device.info.id);
}
///
/// Connects to the [deviceId] on the P2P network.
///
/// Invites [deviceId] if [isBrowserValue] is true.
/// Accepts invite from [deviceId] if [isBrowserValue] is false.
///
@override
Future<bool> connectById(String deviceId) async {
final result = _isBrowser.value
? await NearbyServiceIOSPlatform.instance.invite(device.info.id)
: await NearbyServiceIOSPlatform.instance.acceptInvite(device.info.id);
? await NearbyServiceIOSPlatform.instance.invite(deviceId)
: await NearbyServiceIOSPlatform.instance.acceptInvite(deviceId);
_logResult(
result,
onSuccess:
'${_isBrowser.value ? 'Sent invitation to' : 'Accepted invitation from'} '
'${device.info.id}',
onError: 'Failed to connect to ${device.info.id}',
'$deviceId',
onError: 'Failed to connect to $deviceId',
);
return result;
}
@@ -139,17 +177,25 @@ class NearbyIOSService extends NearbyService {
///
/// Note! Requires [NearbyIOSDevice] to be passed.
///
@Deprecated('Use disconnectById instead')
@override
Future<bool> disconnect([NearbyDevice? device]) async {
if (device == null) return false;
_requireIOSDevice(device);
final result = await NearbyServiceIOSPlatform.instance.disconnect(
device.info.id,
);
return disconnectById(device.info.id);
}
///
/// Disconnects from the [deviceId] on the P2P network.
///
@override
Future<bool> disconnectById([String? deviceId]) async {
if (deviceId == null) return false;
final result = await NearbyServiceIOSPlatform.instance.disconnect(deviceId);
_logResult(
result,
onSuccess: 'Disconnected from ${device.info.id}',
onError: 'Failed to disconnect from ${device.info.id}',
onSuccess: 'Disconnected from $deviceId',
onError: 'Failed to disconnect from $deviceId',
);
return result;
}
@@ -163,7 +209,8 @@ class NearbyIOSService extends NearbyService {
NearbyCommunicationChannelData data,
) async {
Logger.debug('Creating messages subscription');
_state.value = CommunicationChannelState.loading;
_stateController.add(CommunicationChannelState.loading);
await endCommunicationChannel();
final eventListener = data.messagesListener;
final filesListener = data.filesListener;
@@ -175,12 +222,12 @@ class NearbyIOSService extends NearbyService {
.listen(
eventListener.onData,
onDone: () {
_state.value = CommunicationChannelState.notConnected;
_stateController.add(CommunicationChannelState.notConnected);
eventListener.onDone?.call();
},
onError: (e, s) {
Logger.error(e);
_state.value = CommunicationChannelState.notConnected;
_stateController.add(CommunicationChannelState.notConnected);
eventListener.onError?.call(e, s);
},
cancelOnError: eventListener.cancelOnError,
@@ -194,7 +241,7 @@ class NearbyIOSService extends NearbyService {
onDone: filesListener?.onDone,
onError: (e, s) {
Logger.error(e);
_state.value = CommunicationChannelState.notConnected;
_stateController.add(CommunicationChannelState.notConnected);
filesListener?.onError?.call(e, s);
},
cancelOnError: filesListener?.cancelOnError,
@@ -202,9 +249,9 @@ class NearbyIOSService extends NearbyService {
if (_messagesSubscription != null) {
Logger.info('Messages subscription was created successfully');
eventListener.onCreated?.call();
_state.value = CommunicationChannelState.connected;
_stateController.add(CommunicationChannelState.connected);
} else {
_state.value = CommunicationChannelState.notConnected;
_stateController.add(CommunicationChannelState.notConnected);
}
if (_resourcesSubscription != null) {
Logger.info('Resources subscription was created successfully');
@@ -223,7 +270,7 @@ class NearbyIOSService extends NearbyService {
await _resourcesSubscription?.cancel();
_messagesSubscription = null;
_resourcesSubscription = null;
_state.value = CommunicationChannelState.notConnected;
_stateController.add(CommunicationChannelState.notConnected);
Logger.debug('Communication channel was cancelled');
return true;
}
@@ -240,6 +287,11 @@ class NearbyIOSService extends NearbyService {
throw NearbyServiceException.invalidMessage(message.content);
}
@override
Stream<CommunicationChannelState> getCommunicationChannelStateStream() {
return _stateController.stream.asBroadcastStream();
}
///
/// If you want to ask the user to change the name on the network,
/// you can retrieve the name previously saved in
@@ -253,11 +305,11 @@ class NearbyIOSService extends NearbyService {
}
///
/// Changes the [isBrowser] to the passed [value].
/// Changes the [isBrowserValue] to the passed [value].
///
void setIsBrowser({required bool value}) {
Logger.debug('Is Browser Value was set to $value');
_isBrowser.value = value;
_isBrowserController.add(value);
}
void _logResult(
@@ -272,6 +324,10 @@ class NearbyIOSService extends NearbyService {
}
}
String get _currentConnectionType {
return _isBrowser.value ? 'browsing' : 'advertising';
}
void _requireIOSDevice(NearbyDevice device) {
assert(
device is NearbyIOSDevice,