diff --git a/.fvmrc b/.fvmrc new file mode 100644 index 00000000..03c3fb3b --- /dev/null +++ b/.fvmrc @@ -0,0 +1,3 @@ +{ + "flutter": "3.19.6" +} \ No newline at end of file diff --git a/.gitignore b/.gitignore index f980fc98..83ed48ba 100644 --- a/.gitignore +++ b/.gitignore @@ -1,20 +1,59 @@ +# Miscellaneous +*.class +*.log +*.pyc +*.swp .DS_Store .atom/ -.idea +.buildlog/ +.history +.svn/ +.gradle/ + +# IntelliJ related +*.iml +*.ipr +*.iws +.idea/ + +# Flutter/Dart/Pub related +**/doc/api/ +.dart_tool/ +.flutter-plugins +.flutter-plugins-dependencies .packages +.pub-cache/ .pub/ +/build/ +*.g.dart + +# Web related +lib/generated_plugin_registrant.dart + +# Symbolication related +app.*.symbols + +# Obfuscation related +app.*.map.json + +# Exceptions to above rules. +!/packages/flutter_tools/test/data/dart_dependencies_test/**/.packages +/ios/Flutter/.last_build_id +/ios/build/ + + +# FVM Version Cache +.fvm/ + +# Previously included from original FlutterBleLib build/ ios/.generated/ packages -pubspec.lock -*.iml example/android/res/values/strings_en.arb res/values/strings_en.arb lib/generated/ example/lib/generated/ example/.flutter-plugins-dependencies -.dart_tool/ -example/ios/Podfile.lock .vscode/settings.json org.eclipse.buildship.core.prefs .project diff --git a/analysis_options.yaml b/analysis_options.yaml index 7ddec7bd..96049137 100644 --- a/analysis_options.yaml +++ b/analysis_options.yaml @@ -1,10 +1,8 @@ -include: package:pedantic/analysis_options.yaml +include: package:flutter_lints/flutter.yaml analyzer: - exclude: [test/**] - + exclude: + - "**.mocks.dart" linter: rules: - prefer_single_quotes: false - omit_local_variable_types: false - unawaited_futures: false + constant_identifier_names: false \ No newline at end of file diff --git a/android/.gitignore b/android/.gitignore index c6cbe562..bc2100d8 100644 --- a/android/.gitignore +++ b/android/.gitignore @@ -1,8 +1,7 @@ -*.iml -.gradle +gradle-wrapper.jar +/.gradle +/captures/ +/gradlew +/gradlew.bat /local.properties -/.idea/workspace.xml -/.idea/libraries -.DS_Store -/build -/captures +GeneratedPluginRegistrant.java diff --git a/android/build.gradle b/android/build.gradle index 64e247dc..d42b55dc 100644 --- a/android/build.gradle +++ b/android/build.gradle @@ -8,7 +8,7 @@ buildscript { } dependencies { - classpath 'com.android.tools.build:gradle:3.5.3' + classpath 'com.android.tools.build:gradle:7.3.0' } } @@ -36,5 +36,5 @@ android { dependencies { implementation 'androidx.annotation:annotation:1.1.0' - implementation 'com.github.Polidea:MultiPlatformBleAdapter:0.1.8' + implementation 'com.github.dotintent:MultiPlatformBleAdapter:0.1.8' } diff --git a/android/gradle/wrapper/gradle-wrapper.properties b/android/gradle/wrapper/gradle-wrapper.properties index 01a286e9..b9fa41cb 100644 --- a/android/gradle/wrapper/gradle-wrapper.properties +++ b/android/gradle/wrapper/gradle-wrapper.properties @@ -2,4 +2,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.4-bin.zip diff --git a/android/src/main/java/com/polidea/flutter_ble_lib/FlutterBleLibPlugin.java b/android/src/main/java/com/polidea/flutter_ble_lib/FlutterBleLibPlugin.java index 94b5469f..6888b523 100644 --- a/android/src/main/java/com/polidea/flutter_ble_lib/FlutterBleLibPlugin.java +++ b/android/src/main/java/com/polidea/flutter_ble_lib/FlutterBleLibPlugin.java @@ -1,8 +1,11 @@ package com.polidea.flutter_ble_lib; +import android.app.Activity; import android.content.Context; import android.util.Log; +import androidx.annotation.NonNull; + import com.polidea.flutter_ble_lib.constant.ArgumentKey; import com.polidea.flutter_ble_lib.constant.ChannelName; import com.polidea.flutter_ble_lib.constant.MethodName; @@ -12,8 +15,8 @@ import com.polidea.flutter_ble_lib.delegate.DescriptorsDelegate; import com.polidea.flutter_ble_lib.delegate.DeviceConnectionDelegate; import com.polidea.flutter_ble_lib.delegate.DevicesDelegate; -import com.polidea.flutter_ble_lib.delegate.LogLevelDelegate; import com.polidea.flutter_ble_lib.delegate.DiscoveryDelegate; +import com.polidea.flutter_ble_lib.delegate.LogLevelDelegate; import com.polidea.flutter_ble_lib.delegate.MtuDelegate; import com.polidea.flutter_ble_lib.delegate.RssiDelegate; import com.polidea.flutter_ble_lib.event.AdapterStateStreamHandler; @@ -31,15 +34,17 @@ import java.util.LinkedList; import java.util.List; -import androidx.annotation.NonNull; +import io.flutter.embedding.engine.plugins.FlutterPlugin; +import io.flutter.embedding.engine.plugins.activity.ActivityAware; +import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding; +import io.flutter.plugin.common.BinaryMessenger; import io.flutter.plugin.common.EventChannel; import io.flutter.plugin.common.MethodCall; import io.flutter.plugin.common.MethodChannel; import io.flutter.plugin.common.MethodChannel.MethodCallHandler; import io.flutter.plugin.common.MethodChannel.Result; -import io.flutter.plugin.common.PluginRegistry.Registrar; -public class FlutterBleLibPlugin implements MethodCallHandler { +public class FlutterBleLibPlugin implements MethodCallHandler, FlutterPlugin, ActivityAware { static final String TAG = FlutterBleLibPlugin.class.getName(); @@ -53,16 +58,32 @@ public class FlutterBleLibPlugin implements MethodCallHandler { private List delegates = new LinkedList<>(); - public static void registerWith(Registrar registrar) { - final MethodChannel channel = new MethodChannel(registrar.messenger(), ChannelName.FLUTTER_BLE_LIB); + static MethodChannel channel; + private Activity activity; + + private static FlutterBleLibPlugin factory(Context context, Activity activity) { + FlutterBleLibPlugin plugin = new FlutterBleLibPlugin(); + plugin.context = context; + plugin.activity = activity; + return plugin; + } + + /** + * Initializes the plugin. + * + * @param context registrar.context() or binding.getApplicationContext() + * @param messenger registrar.messenger() or binding.getBinaryMessenger() + */ + private static void init(Context context, BinaryMessenger messenger, Activity activity) { + channel = new MethodChannel(messenger, ChannelName.FLUTTER_BLE_LIB); - final EventChannel bluetoothStateChannel = new EventChannel(registrar.messenger(), ChannelName.ADAPTER_STATE_CHANGES); - final EventChannel restoreStateChannel = new EventChannel(registrar.messenger(), ChannelName.STATE_RESTORE_EVENTS); - final EventChannel scanningChannel = new EventChannel(registrar.messenger(), ChannelName.SCANNING_EVENTS); - final EventChannel connectionStateChannel = new EventChannel(registrar.messenger(), ChannelName.CONNECTION_STATE_CHANGE_EVENTS); - final EventChannel characteristicMonitorChannel = new EventChannel(registrar.messenger(), ChannelName.MONITOR_CHARACTERISTIC); + final EventChannel bluetoothStateChannel = new EventChannel(messenger, ChannelName.ADAPTER_STATE_CHANGES); + final EventChannel restoreStateChannel = new EventChannel(messenger, ChannelName.STATE_RESTORE_EVENTS); + final EventChannel scanningChannel = new EventChannel(messenger, ChannelName.SCANNING_EVENTS); + final EventChannel connectionStateChannel = new EventChannel(messenger, ChannelName.CONNECTION_STATE_CHANGE_EVENTS); + final EventChannel characteristicMonitorChannel = new EventChannel(messenger, ChannelName.MONITOR_CHARACTERISTIC); - final FlutterBleLibPlugin plugin = new FlutterBleLibPlugin(registrar.context()); + final FlutterBleLibPlugin plugin = factory(context, activity); channel.setMethodCallHandler(plugin); @@ -73,10 +94,6 @@ public static void registerWith(Registrar registrar) { characteristicMonitorChannel.setStreamHandler(plugin.characteristicsMonitorStreamHandler); } - private FlutterBleLibPlugin(Context context) { - this.context = context; - } - private void setupAdapter(Context context) { bleAdapter = BleAdapterFactory.getNewAdapter(context); delegates.add(new DeviceConnectionDelegate(bleAdapter, connectionStateStreamHandler)); @@ -192,4 +209,38 @@ private void cancelTransaction(MethodCall call, Result result) { } result.success(null); } + + // FlutterPlugin interface: + + @Override + public void onAttachedToEngine(@NonNull FlutterPluginBinding binding) { + init(binding.getApplicationContext(), binding.getBinaryMessenger(), null); + } + + @Override + public void onDetachedFromEngine(@NonNull FlutterPluginBinding binding) { + channel.setMethodCallHandler(null); + } + + // ActivityAware interface: + + @Override + public void onAttachedToActivity(@NonNull ActivityPluginBinding binding) { + activity = binding.getActivity(); + } + + @Override + public void onDetachedFromActivityForConfigChanges() { + activity = null; + } + + @Override + public void onReattachedToActivityForConfigChanges(@NonNull ActivityPluginBinding binding) { + activity = binding.getActivity(); + } + + @Override + public void onDetachedFromActivity() { + activity = null; + } } diff --git a/android/src/main/java/com/polidea/flutter_ble_lib/delegate/CharacteristicsDelegate.java b/android/src/main/java/com/polidea/flutter_ble_lib/delegate/CharacteristicsDelegate.java index 2e1e5aba..61289530 100644 --- a/android/src/main/java/com/polidea/flutter_ble_lib/delegate/CharacteristicsDelegate.java +++ b/android/src/main/java/com/polidea/flutter_ble_lib/delegate/CharacteristicsDelegate.java @@ -181,7 +181,7 @@ private void readCharacteristicForDevice( @Override public void onSuccess(Characteristic data) { try { - result.success(characteristicsResponseJsonConverter.toJson(createCharacteristicResponse(data))); + result.success(characteristicsResponseJsonConverter.toJson(createCharacteristicResponse(data, transactionId))); } catch (JSONException e) { e.printStackTrace(); result.error(null, e.getMessage(), null); @@ -495,10 +495,6 @@ public void run() { result.success(null); } - private SingleCharacteristicResponse createCharacteristicResponse(Characteristic characteristic) { - return createCharacteristicResponse(characteristic, null); - } - private SingleCharacteristicResponse createCharacteristicResponse(Characteristic characteristic, String transactionId) { return new SingleCharacteristicResponse( characteristic, diff --git a/example/android/app/src/main/AndroidManifest.xml b/example/android/app/src/main/AndroidManifest.xml index 6dcf69d8..e0b4ea5f 100644 --- a/example/android/app/src/main/AndroidManifest.xml +++ b/example/android/app/src/main/AndroidManifest.xml @@ -8,7 +8,6 @@ additional functionality it is fine to subclass or reimplement FlutterApplication and put your custom class here. --> + diff --git a/example/android/app/src/main/java/com/polidea/flutter_ble_lib_example/MainActivity.java b/example/android/app/src/main/java/com/polidea/flutter_ble_lib_example/MainActivity.java index f0cbbdc3..6dc07cfb 100644 --- a/example/android/app/src/main/java/com/polidea/flutter_ble_lib_example/MainActivity.java +++ b/example/android/app/src/main/java/com/polidea/flutter_ble_lib_example/MainActivity.java @@ -1,13 +1,5 @@ package com.polidea.flutter_ble_lib_example; -import android.os.Bundle; -import io.flutter.app.FlutterActivity; -import io.flutter.plugins.GeneratedPluginRegistrant; +import io.flutter.embedding.android.FlutterActivity; -public class MainActivity extends FlutterActivity { - @Override - protected void onCreate(Bundle savedInstanceState) { - super.onCreate(savedInstanceState); - GeneratedPluginRegistrant.registerWith(this); - } -} +public class MainActivity extends FlutterActivity {} diff --git a/example/android/gradle/wrapper/gradle-wrapper.properties b/example/android/gradle/wrapper/gradle-wrapper.properties index 296b146b..b0276817 100644 --- a/example/android/gradle/wrapper/gradle-wrapper.properties +++ b/example/android/gradle/wrapper/gradle-wrapper.properties @@ -3,4 +3,4 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-5.6.2-all.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.4-bin.zip diff --git a/example/lib/device_details/device_detail_view.dart b/example/lib/device_details/device_detail_view.dart index 529314ca..e5a47d6e 100644 --- a/example/lib/device_details/device_detail_view.dart +++ b/example/lib/device_details/device_detail_view.dart @@ -60,14 +60,12 @@ class DeviceDetailsViewState extends State { @override Widget build(BuildContext context) { final deviceDetailsBloc = _deviceDetailsBloc; - return WillPopScope( - onWillPop: () { - if (deviceDetailsBloc == null) { - return Future.value(true); + return PopScope( + canPop: deviceDetailsBloc == null, + onPopInvoked: (didPop) { + if (deviceDetailsBloc != null) { + deviceDetailsBloc.disconnect(); } - return deviceDetailsBloc.disconnect().then((_) { - return false; - }); }, child: DefaultTabController( length: 2, diff --git a/example/lib/device_details/device_details_bloc.dart b/example/lib/device_details/device_details_bloc.dart index b237dc43..9044b27f 100644 --- a/example/lib/device_details/device_details_bloc.dart +++ b/example/lib/device_details/device_details_bloc.dart @@ -7,9 +7,6 @@ import 'package:flutter_ble_lib_example/repository/device_repository.dart'; import 'package:flutter_ble_lib_example/test_scenarios/test_scenarios.dart'; import 'package:rxdart/rxdart.dart'; -import '../model/ble_device.dart'; -import '../repository/device_repository.dart'; - class DeviceDetailsBloc { final BleManager _bleManager; final DeviceRepository _deviceRepository; @@ -25,7 +22,7 @@ class DeviceDetailsBloc { Stream> get logs => _logsController.stream; - Stream get disconnectedDevice => _deviceRepository.pickedDevice + Stream get disconnectedDevice => _deviceRepository.pickedDevice .skipWhile((bleDevice) => bleDevice != null).cast(); List _logs = []; diff --git a/example/lib/device_details/view/button_view.dart b/example/lib/device_details/view/button_view.dart index a5457fda..8f5224ec 100644 --- a/example/lib/device_details/view/button_view.dart +++ b/example/lib/device_details/view/button_view.dart @@ -11,9 +11,11 @@ class ButtonView extends StatelessWidget { return Expanded( child: Padding( padding: const EdgeInsets.all(2.0), - child: RaisedButton( - color: Colors.blue, - textColor: Colors.white, + child: ElevatedButton( + style: ButtonStyle( + backgroundColor: MaterialStateProperty.all(Colors.blue), + foregroundColor: MaterialStateProperty.all(Colors.white), + ), child: Text(_text), onPressed: action, ), diff --git a/example/lib/devices_list/devices_list_view.dart b/example/lib/devices_list/devices_list_view.dart index a73a90ce..d87fa41f 100644 --- a/example/lib/devices_list/devices_list_view.dart +++ b/example/lib/devices_list/devices_list_view.dart @@ -142,7 +142,7 @@ class DevicesList extends ListView { padding: const EdgeInsets.all(8.0), child: Image.asset('assets/ti_logo.png'), ), - backgroundColor: Theme.of(context).accentColor); + backgroundColor: Theme.of(context).colorScheme.secondary); case DeviceCategory.hex: return CircleAvatar( child: CustomPaint(painter: HexPainter(), size: Size(20, 24)), diff --git a/example/lib/main.dart b/example/lib/main.dart index 25005b03..b792af23 100644 --- a/example/lib/main.dart +++ b/example/lib/main.dart @@ -20,7 +20,7 @@ class MyApp extends StatelessWidget { title: 'FlutterBleLib example', theme: new ThemeData( primaryColor: new Color(0xFF0A3D91), - accentColor: new Color(0xFFCC0000), + colorScheme: ColorScheme.fromSwatch().copyWith(secondary: new Color(0xFFCC0000)), ), initialRoute: "/", routes: { diff --git a/example/pubspec.lock b/example/pubspec.lock new file mode 100644 index 00000000..20cdb696 --- /dev/null +++ b/example/pubspec.lock @@ -0,0 +1,244 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + async: + dependency: transitive + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + collection: + dependency: transitive + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + cupertino_icons: + dependency: "direct main" + description: + name: cupertino_icons + sha256: ba631d1c7f7bef6b729a622b7b752645a2d076dba9976925b8f25725a30e1ee6 + url: "https://pub.dev" + source: hosted + version: "1.0.8" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + fimber: + dependency: "direct main" + description: + name: fimber + sha256: "1415768ddd9fd66f134dbc53f731107554c98175a63d4e93234478a113ffabb8" + url: "https://pub.dev" + source: hosted + version: "0.6.6" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_ble_lib: + dependency: "direct dev" + description: + path: ".." + relative: true + source: path + version: "2.4.0" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + url: "https://pub.dev" + source: hosted + version: "10.0.0" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + matcher: + dependency: transitive + description: + name: matcher + sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + url: "https://pub.dev" + source: hosted + version: "0.12.16+1" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + url: "https://pub.dev" + source: hosted + version: "0.8.0" + meta: + dependency: transitive + description: + name: meta + sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + url: "https://pub.dev" + source: hosted + version: "1.11.0" + path: + dependency: transitive + description: + name: path + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + permission_handler: + dependency: "direct main" + description: + name: permission_handler + sha256: "390a98f0b998e78f839a687a41ed6fb887103c96224ce43be3d4f2b3cbc2b720" + url: "https://pub.dev" + source: hosted + version: "6.1.3" + permission_handler_platform_interface: + dependency: transitive + description: + name: permission_handler_platform_interface + sha256: "6760eb5ef34589224771010805bea6054ad28453906936f843a8cc4d3a55c4a4" + url: "https://pub.dev" + source: hosted + version: "3.12.0" + plugin_platform_interface: + dependency: transitive + description: + name: plugin_platform_interface + sha256: "4820fbfdb9478b1ebae27888254d445073732dae3d6ea81f0b7e06d5dedc3f02" + url: "https://pub.dev" + source: hosted + version: "2.1.8" + rxdart: + dependency: "direct main" + description: + name: rxdart + sha256: "2ef8b4e91cb3b55d155e0e34eeae0ac7107974e451495c955ac04ddee8cc21fd" + url: "https://pub.dev" + source: hosted + version: "0.26.0" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + url: "https://pub.dev" + source: hosted + version: "13.0.0" +sdks: + dart: ">=3.2.0-0 <4.0.0" + flutter: ">=2.5.0" diff --git a/ios/.gitignore b/ios/.gitignore index 710ec6cf..190de103 100644 --- a/ios/.gitignore +++ b/ios/.gitignore @@ -1,36 +1,33 @@ -.idea/ -.vagrant/ -.sconsign.dblite -.svn/ - -.DS_Store -*.swp -profile - -DerivedData/ -build/ -GeneratedPluginRegistrant.h -GeneratedPluginRegistrant.m - -.generated/ - -*.pbxuser *.mode1v3 *.mode2v3 +*.moved-aside +*.pbxuser *.perspectivev3 - -!default.pbxuser +**/*sync/ +.sconsign.dblite +.tags* +**/.vagrant/ +**/DerivedData/ +Icon? +**/Pods/ +**/.symlinks/ +profile +xcuserdata +**/.generated/ +Flutter/App.framework +Flutter/Flutter.framework +Flutter/Flutter.podspec +Flutter/Debug.xcconfig +Flutter/Generated.xcconfig +Flutter/app.flx +Flutter/app.zip +Flutter/flutter_assets/ +Flutter/flutter_export_environment.sh +ServiceDefinitions.json +Runner/GeneratedPluginRegistrant.* + +# Exceptions to above rules. !default.mode1v3 !default.mode2v3 +!default.pbxuser !default.perspectivev3 - -xcuserdata - -*.moved-aside - -*.pyc -*sync/ -Icon? -.tags* - -/Flutter/Generated.xcconfig diff --git a/lib/ble_manager.dart b/lib/ble_manager.dart index 97ae9eb8..04c2c315 100644 --- a/lib/ble_manager.dart +++ b/lib/ble_manager.dart @@ -1,4 +1,4 @@ -part of flutter_ble_lib; +part of 'flutter_ble_lib.dart'; /// Callback used to inform about peripherals restored by the system. /// diff --git a/lib/characteristic.dart b/lib/characteristic.dart index 8356f45b..2a2f7aeb 100644 --- a/lib/characteristic.dart +++ b/lib/characteristic.dart @@ -1,4 +1,4 @@ -part of flutter_ble_lib; +part of 'flutter_ble_lib.dart'; abstract class _CharacteristicMetadata { static const String uuid = "characteristicUuid"; @@ -40,10 +40,9 @@ class Characteristic extends InternalCharacteristic { /// True if this characteristic can be monitored via indications. bool isIndicatable; - Characteristic.fromJson(Map jsonObject, Service service, + Characteristic.fromJson(Map jsonObject, this.service, ManagerForCharacteristic manager) : _manager = manager, - service = service, uuid = jsonObject[_CharacteristicMetadata.uuid], isReadable = jsonObject[_CharacteristicMetadata.isReadable], isWritableWithResponse = @@ -175,8 +174,8 @@ class CharacteristicWithValue extends Characteristic { Map jsonObject, Service service, ManagerForCharacteristic manager, - ) : value = base64Decode(jsonObject[_CharacteristicMetadata.value]), - super.fromJson(jsonObject, service, manager); + ) : value = base64Decode(jsonObject[_CharacteristicMetadata.value]), + super.fromJson(jsonObject, service, manager); @override bool operator ==(Object other) { @@ -188,11 +187,10 @@ class CharacteristicWithValue extends Characteristic { } @override - int get hashCode => super.hashCode; + int get hashCode => Object.hash(super.hashCode, value.toString()); @override String toString() { - return super.toString() + - ' CharacteristicWithValue{value = ${value.toString()}'; + return '${super.toString()} CharacteristicWithValue{value = ${value.toString()}'; } } diff --git a/lib/descriptor.dart b/lib/descriptor.dart index b1e4f0ad..c475ce54 100644 --- a/lib/descriptor.dart +++ b/lib/descriptor.dart @@ -1,4 +1,4 @@ -part of flutter_ble_lib; +part of 'flutter_ble_lib.dart'; abstract class _DescriptorMetadata { static const String uuid = 'descriptorUuid'; @@ -13,12 +13,11 @@ class Descriptor extends InternalDescriptor { Descriptor.fromJson( Map jsonObject, - Characteristic characteristic, + this.characteristic, ManagerForDescriptor manager, - ) : _manager = manager, - characteristic = characteristic, - uuid = jsonObject[_DescriptorMetadata.uuid], - super(jsonObject[_DescriptorMetadata.id]); + ) : _manager = manager, + uuid = jsonObject[_DescriptorMetadata.uuid], + super(jsonObject[_DescriptorMetadata.id]); Future read({String? transactionId}) => _manager.readDescriptorForIdentifier( @@ -54,6 +53,6 @@ class DescriptorWithValue extends Descriptor { Map jsonObject, Characteristic characteristic, ManagerForDescriptor manager, - ) : value = base64Decode(jsonObject[_DescriptorMetadata.value]), - super.fromJson(jsonObject, characteristic, manager); + ) : value = base64Decode(jsonObject[_DescriptorMetadata.value]), + super.fromJson(jsonObject, characteristic, manager); } diff --git a/lib/error/ble_error.dart b/lib/error/ble_error.dart index 2054e5dd..15477227 100644 --- a/lib/error/ble_error.dart +++ b/lib/error/ble_error.dart @@ -1,4 +1,4 @@ -part of flutter_ble_lib; +part of '../flutter_ble_lib.dart'; abstract class _BleErrorMetadata { static const String errorCode = "errorCode"; diff --git a/lib/flutter_ble_lib.dart b/lib/flutter_ble_lib.dart index a330fe19..59355060 100644 --- a/lib/flutter_ble_lib.dart +++ b/lib/flutter_ble_lib.dart @@ -41,18 +41,10 @@ import 'package:flutter_ble_lib/src/_internal.dart'; import 'package:flutter_ble_lib/src/_managers_for_classes.dart'; import 'package:flutter_ble_lib/src/util/_transaction_id_generator.dart'; -import 'src/_managers_for_classes.dart'; - -part 'error/ble_error.dart'; - part 'ble_manager.dart'; - part 'characteristic.dart'; - part 'descriptor.dart'; - +part 'error/ble_error.dart'; part 'peripheral.dart'; - part 'scan_result.dart'; - part 'service.dart'; diff --git a/lib/peripheral.dart b/lib/peripheral.dart index 0d1134e0..2c74e2ae 100644 --- a/lib/peripheral.dart +++ b/lib/peripheral.dart @@ -1,4 +1,4 @@ -part of flutter_ble_lib; +part of 'flutter_ble_lib.dart'; abstract class _PeripheralMetadata { static const name = "name"; diff --git a/lib/scan_result.dart b/lib/scan_result.dart index 8f29805c..6cae06e4 100644 --- a/lib/scan_result.dart +++ b/lib/scan_result.dart @@ -1,4 +1,4 @@ -part of flutter_ble_lib; +part of 'flutter_ble_lib.dart'; abstract class _ScanResultMetadata { static const String rssi = "rssi"; @@ -27,28 +27,22 @@ class ScanResult { /// A packet of data advertised by the peripheral. final AdvertisementData advertisementData; - + ScanResult._( - this.peripheral, + this.peripheral, this.rssi, - this.advertisementData, - {this.isConnectable, - List? overflowServiceUuids, + this.advertisementData, { + this.isConnectable, + List? overflowServiceUuids, }) : overflowServiceUuids = overflowServiceUuids ?? []; - factory ScanResult.fromJson( - Map json, - ManagerForPeripheral manager - ) { + Map json, ManagerForPeripheral manager) { assert(json[_ScanResultMetadata.rssi] is int); - return ScanResult._( - Peripheral.fromJson(json, manager), - json[_ScanResultMetadata.rssi], - AdvertisementData._fromJson(json), - isConnectable: json[_ScanResultMetadata.isConnectable], - overflowServiceUuids: json[_ScanResultMetadata.overflowServiceUuids] - ); + return ScanResult._(Peripheral.fromJson(json, manager), + json[_ScanResultMetadata.rssi], AdvertisementData._fromJson(json), + isConnectable: json[_ScanResultMetadata.isConnectable], + overflowServiceUuids: json[_ScanResultMetadata.overflowServiceUuids]); } } @@ -83,10 +77,8 @@ class AdvertisementData { _mapToListOfStringsOrNull(json[_ScanResultMetadata.serviceUuids]), localName = json[_ScanResultMetadata.localName], txPowerLevel = json[_ScanResultMetadata.txPowerLevel], - solicitedServiceUuids = - _mapToListOfStringsOrNull( - json[_ScanResultMetadata.solicitedServiceUuids] - ); + solicitedServiceUuids = _mapToListOfStringsOrNull( + json[_ScanResultMetadata.solicitedServiceUuids]); static Map? _getServiceDataOrNull( Map? serviceData) { diff --git a/lib/service.dart b/lib/service.dart index 409ded39..2d9b61e4 100644 --- a/lib/service.dart +++ b/lib/service.dart @@ -1,4 +1,4 @@ -part of flutter_ble_lib; +part of 'flutter_ble_lib.dart'; abstract class _ServiceMetadata { static const String uuid = "serviceUuid"; @@ -17,11 +17,10 @@ class Service extends InternalService { Service.fromJson( Map jsonObject, - Peripheral peripheral, + this.peripheral, this._manager, - ) : peripheral = peripheral, - uuid = jsonObject[_ServiceMetadata.uuid], - super(jsonObject[_ServiceMetadata.id]); + ) : uuid = jsonObject[_ServiceMetadata.uuid], + super(jsonObject[_ServiceMetadata.id]); /// Returns a list of [Characteristic]s of this service. Future> characteristics() => diff --git a/lib/src/_constants.dart b/lib/src/_constants.dart index 838ad857..a4a7de9a 100644 --- a/lib/src/_constants.dart +++ b/lib/src/_constants.dart @@ -75,14 +75,13 @@ abstract class MethodName { abstract class ChannelName { static const String flutterBleLib = "flutter_ble_lib"; - static const String adapterStateChanges = flutterBleLib + "/stateChanges"; - static const String stateRestoreEvents = - flutterBleLib + "/stateRestoreEvents"; - static const String scanningEvents = flutterBleLib + "/scanningEvents"; + static const String adapterStateChanges = "$flutterBleLib/stateChanges"; + static const String stateRestoreEvents = "$flutterBleLib/stateRestoreEvents"; + static const String scanningEvents = "$flutterBleLib/scanningEvents"; static const String connectionStateChangeEvents = - flutterBleLib + "/connectionStateChangeEvents"; + "$flutterBleLib/connectionStateChangeEvents"; static const String monitorCharacteristic = - flutterBleLib + "/monitorCharacteristic"; + "$flutterBleLib/monitorCharacteristic"; } abstract class ArgumentName { diff --git a/lib/src/_internal.dart b/lib/src/_internal.dart index 5463159b..e20dfa75 100644 --- a/lib/src/_internal.dart +++ b/lib/src/_internal.dart @@ -2,6 +2,7 @@ library _internal; import 'dart:async'; import 'dart:convert'; +// This is included in foundation in newer flutter versions, but not in olders ones (eg, 2.8.1) import 'dart:typed_data'; import 'package:collection/collection.dart'; @@ -16,27 +17,15 @@ import 'package:flutter_ble_lib/src/util/_transformers.dart'; import '_managers_for_classes.dart'; part 'base_entities.dart'; - -part 'internal_ble_manager.dart'; - part 'bridge/bluetooth_state_mixin.dart'; - part 'bridge/characteristics_mixin.dart'; - -part 'bridge/device_connection_mixin.dart'; - part 'bridge/descriptors_mixin.dart'; - +part 'bridge/device_connection_mixin.dart'; part 'bridge/device_rssi_mixin.dart'; - part 'bridge/devices_mixin.dart'; - part 'bridge/discovery_mixin.dart'; - part 'bridge/lib_core.dart'; - part 'bridge/log_level_mixin.dart'; - part 'bridge/mtu_mixin.dart'; - part 'bridge/scanning_mixin.dart'; +part 'internal_ble_manager.dart'; diff --git a/lib/src/base_entities.dart b/lib/src/base_entities.dart index f332e3a0..4dafa805 100644 --- a/lib/src/base_entities.dart +++ b/lib/src/base_entities.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '_internal.dart'; class InternalService { final int _id; @@ -17,4 +17,3 @@ class InternalDescriptor { InternalDescriptor(this._id); } - diff --git a/lib/src/bridge/bluetooth_state_mixin.dart b/lib/src/bridge/bluetooth_state_mixin.dart index bc379167..037bde24 100644 --- a/lib/src/bridge/bluetooth_state_mixin.dart +++ b/lib/src/bridge/bluetooth_state_mixin.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; mixin BluetoothStateMixin on FlutterBLE { final Stream _adapterStateChanges = diff --git a/lib/src/bridge/characteristics_mixin.dart b/lib/src/bridge/characteristics_mixin.dart index 12a80d52..b6c540d8 100644 --- a/lib/src/bridge/characteristics_mixin.dart +++ b/lib/src/bridge/characteristics_mixin.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; mixin CharacteristicsMixin on FlutterBLE { final Stream _characteristicsMonitoringEvents = @@ -26,9 +26,8 @@ mixin CharacteristicsMixin on FlutterBLE { rawJsonValue = rawValue; } return _parseCharacteristicWithValueWithTransactionIdResponse( - peripheral, - rawJsonValue - ).value; + peripheral, rawJsonValue) + .value; }); Future readCharacteristicForDevice( @@ -55,9 +54,7 @@ mixin CharacteristicsMixin on FlutterBLE { rawJsonValue = rawValue; } return _parseCharacteristicWithValueWithTransactionIdResponse( - peripheral, - rawJsonValue - ); + peripheral, rawJsonValue); }); Future readCharacteristicForService( @@ -83,9 +80,7 @@ mixin CharacteristicsMixin on FlutterBLE { rawJsonValue = rawValue; } return _parseCharacteristicWithValueWithTransactionIdResponse( - peripheral, - rawJsonValue - ); + peripheral, rawJsonValue); }); Future writeCharacteristicForIdentifier( @@ -163,13 +158,15 @@ mixin CharacteristicsMixin on FlutterBLE { int characteristicIdentifier, String transactionId, ) { - void Function() startMonitoring = () => _methodChannel.invokeMethod( - MethodName.monitorCharacteristicForIdentifier, - { - ArgumentName.characteristicIdentifier: characteristicIdentifier, - ArgumentName.transactionId: transactionId, - }, - ); + void startMonitoring() { + _methodChannel.invokeMethod( + MethodName.monitorCharacteristicForIdentifier, + { + ArgumentName.characteristicIdentifier: characteristicIdentifier, + ArgumentName.transactionId: transactionId, + }, + ); + } bool characteristicFilter( CharacteristicWithValueAndTransactionId characteristic, @@ -181,7 +178,7 @@ mixin CharacteristicsMixin on FlutterBLE { transactionId, characteristic._transactionId ?? "", ); - }; + } return _createMonitoringStream( startMonitoring, @@ -197,22 +194,25 @@ mixin CharacteristicsMixin on FlutterBLE { String characteristicUuid, String transactionId, ) { - void Function() startMonitoring = () => _methodChannel.invokeMethod( - MethodName.monitorCharacteristicForDevice, - { - ArgumentName.deviceIdentifier: peripheral.identifier, - ArgumentName.serviceUuid: serviceUuid, - ArgumentName.characteristicUuid: characteristicUuid, - ArgumentName.transactionId: transactionId, - }, - ); + void startMonitoring() { + _methodChannel.invokeMethod( + MethodName.monitorCharacteristicForDevice, + { + ArgumentName.deviceIdentifier: peripheral.identifier, + ArgumentName.serviceUuid: serviceUuid, + ArgumentName.characteristicUuid: characteristicUuid, + ArgumentName.transactionId: transactionId, + }, + ); + } - bool Function(CharacteristicWithValueAndTransactionId) - characteristicsFilter = (characteristic) => - equalsIgnoreAsciiCase(characteristicUuid, characteristic.uuid) && - equalsIgnoreAsciiCase(serviceUuid, characteristic.service.uuid) && - equalsIgnoreAsciiCase( - transactionId, characteristic._transactionId ?? ""); + bool characteristicsFilter( + CharacteristicWithValueAndTransactionId characteristic) { + return equalsIgnoreAsciiCase(characteristicUuid, characteristic.uuid) && + equalsIgnoreAsciiCase(serviceUuid, characteristic.service.uuid) && + equalsIgnoreAsciiCase( + transactionId, characteristic._transactionId ?? ""); + } return _createMonitoringStream( startMonitoring, @@ -228,21 +228,24 @@ mixin CharacteristicsMixin on FlutterBLE { String characteristicUuid, String transactionId, ) { - void Function() startMonitoring = () => _methodChannel.invokeMethod( - MethodName.monitorCharacteristicForService, - { - ArgumentName.serviceIdentifier: serviceIdentifier, - ArgumentName.characteristicUuid: characteristicUuid, - ArgumentName.transactionId: transactionId, - }, - ); + void startMonitoring() { + _methodChannel.invokeMethod( + MethodName.monitorCharacteristicForService, + { + ArgumentName.serviceIdentifier: serviceIdentifier, + ArgumentName.characteristicUuid: characteristicUuid, + ArgumentName.transactionId: transactionId, + }, + ); + } - bool Function(CharacteristicWithValueAndTransactionId) - characteristicFilter = (characteristic) => - equalsIgnoreAsciiCase(characteristicUuid, characteristic.uuid) && - serviceIdentifier == characteristic.service._id && - equalsIgnoreAsciiCase( - transactionId, characteristic._transactionId ?? ""); + bool characteristicFilter( + CharacteristicWithValueAndTransactionId characteristic) { + return equalsIgnoreAsciiCase(characteristicUuid, characteristic.uuid) && + serviceIdentifier == characteristic.service._id && + equalsIgnoreAsciiCase( + transactionId, characteristic._transactionId ?? ""); + } return _createMonitoringStream( startMonitoring, @@ -259,26 +262,23 @@ mixin CharacteristicsMixin on FlutterBLE { String transactionId, ) { Stream stream = - _characteristicsMonitoringEvents - .map((rawValue) { - String rawJsonValue = ""; - if (rawValue is String) { - rawJsonValue = rawValue; - } - return _parseCharacteristicWithValueWithTransactionIdResponse( - peripheral, - rawJsonValue - ); - }) - .where(filter) - .handleError((errorJson) => - _throwErrorIfMatchesWithTransactionId(errorJson, transactionId)) - .transform( - CancelOnErrorStreamTransformer() - ); + _characteristicsMonitoringEvents + .map((rawValue) { + String rawJsonValue = ""; + if (rawValue is String) { + rawJsonValue = rawValue; + } + return _parseCharacteristicWithValueWithTransactionIdResponse( + peripheral, rawJsonValue); + }) + .where(filter) + .handleError((errorJson) => + _throwErrorIfMatchesWithTransactionId(errorJson, transactionId)) + .transform( + CancelOnErrorStreamTransformer()); StreamController streamController = - StreamController.broadcast( + StreamController( onListen: onListen, onCancel: () => cancelTransaction(transactionId), ); @@ -311,10 +311,8 @@ mixin CharacteristicsMixin on FlutterBLE { rootObject["characteristic"], service, _manager); } - void _throwErrorIfMatchesWithTransactionId(PlatformException errorJson, String transactionId) { - if (errorJson is PlatformException == false) { - return; - } + void _throwErrorIfMatchesWithTransactionId( + PlatformException errorJson, String transactionId) { final errorDetails = jsonDecode(errorJson.details); if (transactionId != errorDetails["transactionId"]) { return; @@ -351,6 +349,5 @@ class CharacteristicWithValueAndTransactionId extends CharacteristicWithValue { @override String toString() => - super.toString() + - ' CharacteristicWithValueAndTransactionId{transactionId: $_transactionId}'; + '${super.toString()} CharacteristicWithValueAndTransactionId{transactionId: $_transactionId}'; } diff --git a/lib/src/bridge/descriptors_mixin.dart b/lib/src/bridge/descriptors_mixin.dart index e29218a0..dfc8c38a 100644 --- a/lib/src/bridge/descriptors_mixin.dart +++ b/lib/src/bridge/descriptors_mixin.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; mixin DescriptorsMixin on FlutterBLE { Future readDescriptorForPeripheral( diff --git a/lib/src/bridge/device_connection_mixin.dart b/lib/src/bridge/device_connection_mixin.dart index b1eadd99..dff720e9 100644 --- a/lib/src/bridge/device_connection_mixin.dart +++ b/lib/src/bridge/device_connection_mixin.dart @@ -1,17 +1,12 @@ -part of _internal; +part of '../_internal.dart'; mixin DeviceConnectionMixin on FlutterBLE { final Stream _peripheralConnectionStateChanges = const EventChannel(ChannelName.connectionStateChangeEvents) .receiveBroadcastStream(); - Future connectToPeripheral( - String deviceIdentifier, - bool isAutoConnect, - int requestMtu, - bool refreshGatt, - Duration? timeout - ) async { + Future connectToPeripheral(String deviceIdentifier, bool isAutoConnect, + int requestMtu, bool refreshGatt, Duration? timeout) async { return await _methodChannel.invokeMethod( MethodName.connectToDevice, { @@ -80,16 +75,12 @@ mixin DeviceConnectionMixin on FlutterBLE { return await _methodChannel .invokeMethod(MethodName.isDeviceConnected, { ArgumentName.deviceIdentifier: peripheralIdentifier, - }).catchError( - (errorJson) { - if (errorJson is MissingPluginException) { - return Future.error(errorJson); - } - return Future.error( - BleError.fromJson(jsonDecode(errorJson.details)) - ); + }).catchError((errorJson) { + if (errorJson is MissingPluginException) { + return Future.error(errorJson); } - ); + return Future.error(BleError.fromJson(jsonDecode(errorJson.details))); + }); } Future disconnectOrCancelPeripheralConnection( diff --git a/lib/src/bridge/device_rssi_mixin.dart b/lib/src/bridge/device_rssi_mixin.dart index 1673c33b..ae3851c5 100644 --- a/lib/src/bridge/device_rssi_mixin.dart +++ b/lib/src/bridge/device_rssi_mixin.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; mixin RssiMixin on FlutterBLE { Future rssi(Peripheral peripheral, String transactionId) async { diff --git a/lib/src/bridge/devices_mixin.dart b/lib/src/bridge/devices_mixin.dart index 872e145e..9c582f81 100644 --- a/lib/src/bridge/devices_mixin.dart +++ b/lib/src/bridge/devices_mixin.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; mixin DevicesMixin on FlutterBLE { Future> knownDevices( @@ -7,7 +7,7 @@ mixin DevicesMixin on FlutterBLE { .invokeMethod(MethodName.knownDevices, { ArgumentName.deviceIdentifiers: peripheralIdentifiers, }).then((peripheralsJson) { - print("known devices json: $peripheralsJson"); + debugPrint("known devices json: $peripheralsJson"); return _parsePeripheralsJson(peripheralsJson); }); } @@ -17,7 +17,7 @@ mixin DevicesMixin on FlutterBLE { .invokeMethod(MethodName.connectedDevices, { ArgumentName.uuids: serviceUuids, }).then((peripheralsJson) { - print("connected devices json: $peripheralsJson"); + debugPrint("connected devices json: $peripheralsJson"); return _parsePeripheralsJson(peripheralsJson); }); } diff --git a/lib/src/bridge/discovery_mixin.dart b/lib/src/bridge/discovery_mixin.dart index 3feb110a..8ecf3f63 100644 --- a/lib/src/bridge/discovery_mixin.dart +++ b/lib/src/bridge/discovery_mixin.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; mixin DiscoveryMixin on FlutterBLE { Future discoverAllServicesAndCharacteristics( diff --git a/lib/src/bridge/lib_core.dart b/lib/src/bridge/lib_core.dart index 318f004a..5cadb8b2 100644 --- a/lib/src/bridge/lib_core.dart +++ b/lib/src/bridge/lib_core.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; abstract class FlutterBLE { final InternalBleManager _manager; @@ -33,35 +33,34 @@ class FlutterBleLib extends FlutterBLE FlutterBleLib(InternalBleManager manager) : super._(manager); - Future> restoredState() async { + Future> restoredState() async { final peripherals = await _restoreStateEvents - .map( - (jsonString) { - if (jsonString == null || - jsonString is String == false) { - return null; - } - final restoredPeripheralsJson = - (jsonDecode(jsonString) as List) - .cast>(); - return restoredPeripheralsJson - .map((peripheralJson) => - Peripheral.fromJson(peripheralJson, _manager)) - .toList(); - - }, - ) - .take(1) - .single; + .map( + (jsonString) { + if (jsonString == null || jsonString is String == false) { + return null; + } + final restoredPeripheralsJson = + (jsonDecode(jsonString) as List) + .cast>(); + return restoredPeripheralsJson + .map((peripheralJson) => + Peripheral.fromJson(peripheralJson, _manager)) + .toList(); + }, + ) + .take(1) + .single; return peripherals ?? []; } - Future isClientCreated() => - _methodChannel.invokeMethod(MethodName.isClientCreated) + Future isClientCreated() => _methodChannel + .invokeMethod(MethodName.isClientCreated) .then((value) => value!); Future createClient(String? restoreStateIdentifier) async { - await _methodChannel.invokeMethod(MethodName.createClient, { + await _methodChannel.invokeMethod( + MethodName.createClient, { ArgumentName.restoreStateIdentifier: restoreStateIdentifier }); } diff --git a/lib/src/bridge/log_level_mixin.dart b/lib/src/bridge/log_level_mixin.dart index fb8056d5..3ce1356e 100644 --- a/lib/src/bridge/log_level_mixin.dart +++ b/lib/src/bridge/log_level_mixin.dart @@ -1,12 +1,12 @@ -part of _internal; +part of '../_internal.dart'; mixin LogLevelMixin on FlutterBLE { Future setLogLevel(LogLevel logLevel) async { - print("set log level to ${describeEnum(logLevel)}"); + debugPrint("set log level to ${logLevel.name}"); return await _methodChannel.invokeMethod( MethodName.setLogLevel, { - ArgumentName.logLevel: describeEnum(logLevel), + ArgumentName.logLevel: logLevel.name, }, ).catchError((errorJson) => Future.error(BleError.fromJson(jsonDecode(errorJson.details)))); @@ -19,8 +19,8 @@ mixin LogLevelMixin on FlutterBLE { } LogLevel _logLevelFromString(String logLevelName) { - print("try to get log level from: $logLevelName"); + debugPrint("try to get log level from: $logLevelName"); return LogLevel.values.firstWhere( - (e) => e.toString() == 'LogLevel.' + logLevelName.toLowerCase()); + (e) => e.toString() == 'LogLevel.${logLevelName.toLowerCase()}'); } } diff --git a/lib/src/bridge/mtu_mixin.dart b/lib/src/bridge/mtu_mixin.dart index b5948913..2df37438 100644 --- a/lib/src/bridge/mtu_mixin.dart +++ b/lib/src/bridge/mtu_mixin.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '../_internal.dart'; mixin MtuMixin on FlutterBLE { Future requestMtu( diff --git a/lib/src/bridge/scanning_mixin.dart b/lib/src/bridge/scanning_mixin.dart index 84d18410..f7fee0d9 100644 --- a/lib/src/bridge/scanning_mixin.dart +++ b/lib/src/bridge/scanning_mixin.dart @@ -1,26 +1,26 @@ -part of _internal; +part of '../_internal.dart'; mixin ScanningMixin on FlutterBLE { Stream? _activeScanEvents; Stream get _scanEvents { var scanEvents = _activeScanEvents; if (scanEvents == null) { - scanEvents = - const EventChannel( - ChannelName.scanningEvents - ).receiveBroadcastStream().handleError( - (errorJson) => throw BleError.fromJson( - jsonDecode(errorJson.details) - ), - test: (error) => error is PlatformException, - ).map( - (scanResultJson) => - ScanResult.fromJson(jsonDecode(scanResultJson), _manager), - ); + scanEvents = const EventChannel(ChannelName.scanningEvents) + .receiveBroadcastStream() + .handleError( + (errorJson) => + throw BleError.fromJson(jsonDecode(errorJson.details)), + test: (error) => error is PlatformException, + ) + .map( + (scanResultJson) => + ScanResult.fromJson(jsonDecode(scanResultJson), _manager), + ); _activeScanEvents = scanEvents; } return scanEvents; } + void _resetScanEvents() { _activeScanEvents = null; } diff --git a/lib/src/internal_ble_manager.dart b/lib/src/internal_ble_manager.dart index 442bc4df..fe66185a 100644 --- a/lib/src/internal_ble_manager.dart +++ b/lib/src/internal_ble_manager.dart @@ -1,4 +1,4 @@ -part of _internal; +part of '_internal.dart'; class InternalBleManager implements @@ -8,7 +8,7 @@ class InternalBleManager ManagerForCharacteristic, ManagerForDescriptor { late FlutterBleLib _bleLib; - + InternalBleManager() { _bleLib = FlutterBleLib(this); } @@ -179,13 +179,12 @@ class InternalBleManager Peripheral peripheral, String transactionId, ) { - print("call channel read RSSI"); + debugPrint("call channel read RSSI"); return _bleLib.rssi(peripheral, transactionId); } @override - Future requestMtu( - Peripheral peripheral, int mtu, String transactionId) { + Future requestMtu(Peripheral peripheral, int mtu, String transactionId) { return _bleLib.requestMtu(peripheral, mtu, transactionId); } diff --git a/lib/src/util/_transaction_id_generator.dart b/lib/src/util/_transaction_id_generator.dart index df261165..b5270479 100644 --- a/lib/src/util/_transaction_id_generator.dart +++ b/lib/src/util/_transaction_id_generator.dart @@ -1,11 +1,6 @@ -import 'package:meta/meta.dart'; - abstract class TransactionIdGenerator { static int _id = 0; - @visibleForTesting - static int get id => _id; - static String getNextId() { _id++; return _id.toString(); diff --git a/pubspec.lock b/pubspec.lock new file mode 100644 index 00000000..6e54d3b1 --- /dev/null +++ b/pubspec.lock @@ -0,0 +1,549 @@ +# Generated by pub +# See https://dart.dev/tools/pub/glossary#lockfile +packages: + _fe_analyzer_shared: + dependency: transitive + description: + name: _fe_analyzer_shared + sha256: "0b2f2bd91ba804e53a61d757b986f89f1f9eaed5b11e4b2f5a2468d86d6c9fc7" + url: "https://pub.dev" + source: hosted + version: "67.0.0" + analyzer: + dependency: transitive + description: + name: analyzer + sha256: "37577842a27e4338429a1cbc32679d508836510b056f1eedf0c8d20e39c1383d" + url: "https://pub.dev" + source: hosted + version: "6.4.1" + args: + dependency: transitive + description: + name: args + sha256: "7cf60b9f0cc88203c5a190b4cd62a99feea42759a7fa695010eb5de1c0b2252a" + url: "https://pub.dev" + source: hosted + version: "2.5.0" + async: + dependency: "direct main" + description: + name: async + sha256: "947bfcf187f74dbc5e146c9eb9c0f10c9f8b30743e341481c1e2ed3ecc18c20c" + url: "https://pub.dev" + source: hosted + version: "2.11.0" + boolean_selector: + dependency: transitive + description: + name: boolean_selector + sha256: "6cfb5af12253eaf2b368f07bacc5a80d1301a071c73360d746b7f2e32d762c66" + url: "https://pub.dev" + source: hosted + version: "2.1.1" + build: + dependency: transitive + description: + name: build + sha256: "80184af8b6cb3e5c1c4ec6d8544d27711700bc3e6d2efad04238c7b5290889f0" + url: "https://pub.dev" + source: hosted + version: "2.4.1" + build_config: + dependency: transitive + description: + name: build_config + sha256: bf80fcfb46a29945b423bd9aad884590fb1dc69b330a4d4700cac476af1708d1 + url: "https://pub.dev" + source: hosted + version: "1.1.1" + build_daemon: + dependency: transitive + description: + name: build_daemon + sha256: "0343061a33da9c5810b2d6cee51945127d8f4c060b7fbdd9d54917f0a3feaaa1" + url: "https://pub.dev" + source: hosted + version: "4.0.1" + build_resolvers: + dependency: transitive + description: + name: build_resolvers + sha256: "339086358431fa15d7eca8b6a36e5d783728cf025e559b834f4609a1fcfb7b0a" + url: "https://pub.dev" + source: hosted + version: "2.4.2" + build_runner: + dependency: "direct dev" + description: + name: build_runner + sha256: "3ac61a79bfb6f6cc11f693591063a7f19a7af628dc52f141743edac5c16e8c22" + url: "https://pub.dev" + source: hosted + version: "2.4.9" + build_runner_core: + dependency: transitive + description: + name: build_runner_core + sha256: "4ae8ffe5ac758da294ecf1802f2aff01558d8b1b00616aa7538ea9a8a5d50799" + url: "https://pub.dev" + source: hosted + version: "7.3.0" + built_collection: + dependency: transitive + description: + name: built_collection + sha256: "376e3dd27b51ea877c28d525560790aee2e6fbb5f20e2f85d5081027d94e2100" + url: "https://pub.dev" + source: hosted + version: "5.1.1" + built_value: + dependency: transitive + description: + name: built_value + sha256: c7913a9737ee4007efedaffc968c049fd0f3d0e49109e778edc10de9426005cb + url: "https://pub.dev" + source: hosted + version: "8.9.2" + characters: + dependency: transitive + description: + name: characters + sha256: "04a925763edad70e8443c99234dc3328f442e811f1d8fd1a72f1c8ad0f69a605" + url: "https://pub.dev" + source: hosted + version: "1.3.0" + checked_yaml: + dependency: transitive + description: + name: checked_yaml + sha256: feb6bed21949061731a7a75fc5d2aa727cf160b91af9a3e464c5e3a32e28b5ff + url: "https://pub.dev" + source: hosted + version: "2.0.3" + clock: + dependency: transitive + description: + name: clock + sha256: cb6d7f03e1de671e34607e909a7213e31d7752be4fb66a86d29fe1eb14bfb5cf + url: "https://pub.dev" + source: hosted + version: "1.1.1" + code_builder: + dependency: transitive + description: + name: code_builder + sha256: f692079e25e7869c14132d39f223f8eec9830eb76131925143b2129c4bb01b37 + url: "https://pub.dev" + source: hosted + version: "4.10.0" + collection: + dependency: "direct main" + description: + name: collection + sha256: ee67cb0715911d28db6bf4af1026078bd6f0128b07a5f66fb2ed94ec6783c09a + url: "https://pub.dev" + source: hosted + version: "1.18.0" + convert: + dependency: transitive + description: + name: convert + sha256: "0f08b14755d163f6e2134cb58222dd25ea2a2ee8a195e53983d57c075324d592" + url: "https://pub.dev" + source: hosted + version: "3.1.1" + crypto: + dependency: transitive + description: + name: crypto + sha256: ff625774173754681d66daaf4a448684fb04b78f902da9cb3d308c19cc5e8bab + url: "https://pub.dev" + source: hosted + version: "3.0.3" + dart_style: + dependency: transitive + description: + name: dart_style + sha256: "99e066ce75c89d6b29903d788a7bb9369cf754f7b24bf70bf4b6d6d6b26853b9" + url: "https://pub.dev" + source: hosted + version: "2.3.6" + fake_async: + dependency: transitive + description: + name: fake_async + sha256: "511392330127add0b769b75a987850d136345d9227c6b94c96a04cf4a391bf78" + url: "https://pub.dev" + source: hosted + version: "1.3.1" + file: + dependency: transitive + description: + name: file + sha256: "5fc22d7c25582e38ad9a8515372cd9a93834027aacf1801cf01164dac0ffa08c" + url: "https://pub.dev" + source: hosted + version: "7.0.0" + fixnum: + dependency: transitive + description: + name: fixnum + sha256: "25517a4deb0c03aa0f32fd12db525856438902d9c16536311e76cdc57b31d7d1" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + flutter: + dependency: "direct main" + description: flutter + source: sdk + version: "0.0.0" + flutter_lints: + dependency: "direct dev" + description: + name: flutter_lints + sha256: "9e8c3858111da373efc5aa341de011d9bd23e2c5c5e0c62bccf32438e192d7b1" + url: "https://pub.dev" + source: hosted + version: "3.0.2" + flutter_test: + dependency: "direct dev" + description: flutter + source: sdk + version: "0.0.0" + frontend_server_client: + dependency: transitive + description: + name: frontend_server_client + sha256: f64a0333a82f30b0cca061bc3d143813a486dc086b574bfb233b7c1372427694 + url: "https://pub.dev" + source: hosted + version: "4.0.0" + glob: + dependency: transitive + description: + name: glob + sha256: "0e7014b3b7d4dac1ca4d6114f82bf1782ee86745b9b42a92c9289c23d8a0ab63" + url: "https://pub.dev" + source: hosted + version: "2.1.2" + graphs: + dependency: transitive + description: + name: graphs + sha256: aedc5a15e78fc65a6e23bcd927f24c64dd995062bcd1ca6eda65a3cff92a4d19 + url: "https://pub.dev" + source: hosted + version: "2.3.1" + http_multi_server: + dependency: transitive + description: + name: http_multi_server + sha256: "97486f20f9c2f7be8f514851703d0119c3596d14ea63227af6f7a481ef2b2f8b" + url: "https://pub.dev" + source: hosted + version: "3.2.1" + http_parser: + dependency: transitive + description: + name: http_parser + sha256: "2aa08ce0341cc9b354a498388e30986515406668dbcc4f7c950c3e715496693b" + url: "https://pub.dev" + source: hosted + version: "4.0.2" + io: + dependency: transitive + description: + name: io + sha256: "2ec25704aba361659e10e3e5f5d672068d332fc8ac516421d483a11e5cbd061e" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + js: + dependency: transitive + description: + name: js + sha256: c1b2e9b5ea78c45e1a0788d29606ba27dc5f71f019f32ca5140f61ef071838cf + url: "https://pub.dev" + source: hosted + version: "0.7.1" + json_annotation: + dependency: transitive + description: + name: json_annotation + sha256: "1ce844379ca14835a50d2f019a3099f419082cfdd231cd86a142af94dd5c6bb1" + url: "https://pub.dev" + source: hosted + version: "4.9.0" + leak_tracker: + dependency: transitive + description: + name: leak_tracker + sha256: "78eb209deea09858f5269f5a5b02be4049535f568c07b275096836f01ea323fa" + url: "https://pub.dev" + source: hosted + version: "10.0.0" + leak_tracker_flutter_testing: + dependency: transitive + description: + name: leak_tracker_flutter_testing + sha256: b46c5e37c19120a8a01918cfaf293547f47269f7cb4b0058f21531c2465d6ef0 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + leak_tracker_testing: + dependency: transitive + description: + name: leak_tracker_testing + sha256: a597f72a664dbd293f3bfc51f9ba69816f84dcd403cdac7066cb3f6003f3ab47 + url: "https://pub.dev" + source: hosted + version: "2.0.1" + lints: + dependency: transitive + description: + name: lints + sha256: cbf8d4b858bb0134ef3ef87841abdf8d63bfc255c266b7bf6b39daa1085c4290 + url: "https://pub.dev" + source: hosted + version: "3.0.0" + logging: + dependency: transitive + description: + name: logging + sha256: "623a88c9594aa774443aa3eb2d41807a48486b5613e67599fb4c41c0ad47c340" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + matcher: + dependency: transitive + description: + name: matcher + sha256: d2323aa2060500f906aa31a895b4030b6da3ebdcc5619d14ce1aada65cd161cb + url: "https://pub.dev" + source: hosted + version: "0.12.16+1" + material_color_utilities: + dependency: transitive + description: + name: material_color_utilities + sha256: "0e0a020085b65b6083975e499759762399b4475f766c21668c4ecca34ea74e5a" + url: "https://pub.dev" + source: hosted + version: "0.8.0" + meta: + dependency: transitive + description: + name: meta + sha256: d584fa6707a52763a52446f02cc621b077888fb63b93bbcb1143a7be5a0c0c04 + url: "https://pub.dev" + source: hosted + version: "1.11.0" + mime: + dependency: transitive + description: + name: mime + sha256: "2e123074287cc9fd6c09de8336dae606d1ddb88d9ac47358826db698c176a1f2" + url: "https://pub.dev" + source: hosted + version: "1.0.5" + mockito: + dependency: "direct dev" + description: + name: mockito + sha256: "6841eed20a7befac0ce07df8116c8b8233ed1f4486a7647c7fc5a02ae6163917" + url: "https://pub.dev" + source: hosted + version: "5.4.4" + package_config: + dependency: transitive + description: + name: package_config + sha256: "1c5b77ccc91e4823a5af61ee74e6b972db1ef98c2ff5a18d3161c982a55448bd" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + path: + dependency: transitive + description: + name: path + sha256: "087ce49c3f0dc39180befefc60fdb4acd8f8620e5682fe2476afd0b3688bb4af" + url: "https://pub.dev" + source: hosted + version: "1.9.0" + pool: + dependency: transitive + description: + name: pool + sha256: "20fe868b6314b322ea036ba325e6fc0711a22948856475e2c2b6306e8ab39c2a" + url: "https://pub.dev" + source: hosted + version: "1.5.1" + pub_semver: + dependency: transitive + description: + name: pub_semver + sha256: "40d3ab1bbd474c4c2328c91e3a7df8c6dd629b79ece4c4bd04bee496a224fb0c" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + pubspec_parse: + dependency: transitive + description: + name: pubspec_parse + sha256: c63b2876e58e194e4b0828fcb080ad0e06d051cb607a6be51a9e084f47cb9367 + url: "https://pub.dev" + source: hosted + version: "1.2.3" + shelf: + dependency: transitive + description: + name: shelf + sha256: ad29c505aee705f41a4d8963641f91ac4cee3c8fad5947e033390a7bd8180fa4 + url: "https://pub.dev" + source: hosted + version: "1.4.1" + shelf_web_socket: + dependency: transitive + description: + name: shelf_web_socket + sha256: "9ca081be41c60190ebcb4766b2486a7d50261db7bd0f5d9615f2d653637a84c1" + url: "https://pub.dev" + source: hosted + version: "1.0.4" + sky_engine: + dependency: transitive + description: flutter + source: sdk + version: "0.0.99" + source_gen: + dependency: transitive + description: + name: source_gen + sha256: "14658ba5f669685cd3d63701d01b31ea748310f7ab854e471962670abcf57832" + url: "https://pub.dev" + source: hosted + version: "1.5.0" + source_span: + dependency: transitive + description: + name: source_span + sha256: "53e943d4206a5e30df338fd4c6e7a077e02254531b138a15aec3bd143c1a8b3c" + url: "https://pub.dev" + source: hosted + version: "1.10.0" + stack_trace: + dependency: transitive + description: + name: stack_trace + sha256: "73713990125a6d93122541237550ee3352a2d84baad52d375a4cad2eb9b7ce0b" + url: "https://pub.dev" + source: hosted + version: "1.11.1" + stream_channel: + dependency: transitive + description: + name: stream_channel + sha256: ba2aa5d8cc609d96bbb2899c28934f9e1af5cddbd60a827822ea467161eb54e7 + url: "https://pub.dev" + source: hosted + version: "2.1.2" + stream_transform: + dependency: transitive + description: + name: stream_transform + sha256: "14a00e794c7c11aa145a170587321aedce29769c08d7f58b1d141da75e3b1c6f" + url: "https://pub.dev" + source: hosted + version: "2.1.0" + string_scanner: + dependency: transitive + description: + name: string_scanner + sha256: "556692adab6cfa87322a115640c11f13cb77b3f076ddcc5d6ae3c20242bedcde" + url: "https://pub.dev" + source: hosted + version: "1.2.0" + term_glyph: + dependency: transitive + description: + name: term_glyph + sha256: a29248a84fbb7c79282b40b8c72a1209db169a2e0542bce341da992fe1bc7e84 + url: "https://pub.dev" + source: hosted + version: "1.2.1" + test_api: + dependency: transitive + description: + name: test_api + sha256: "5c2f730018264d276c20e4f1503fd1308dfbbae39ec8ee63c5236311ac06954b" + url: "https://pub.dev" + source: hosted + version: "0.6.1" + timing: + dependency: transitive + description: + name: timing + sha256: "70a3b636575d4163c477e6de42f247a23b315ae20e86442bebe32d3cabf61c32" + url: "https://pub.dev" + source: hosted + version: "1.0.1" + typed_data: + dependency: transitive + description: + name: typed_data + sha256: facc8d6582f16042dd49f2463ff1bd6e2c9ef9f3d5da3d9b087e244a7b564b3c + url: "https://pub.dev" + source: hosted + version: "1.3.2" + vector_math: + dependency: transitive + description: + name: vector_math + sha256: "80b3257d1492ce4d091729e3a67a60407d227c27241d6927be0130c98e741803" + url: "https://pub.dev" + source: hosted + version: "2.1.4" + vm_service: + dependency: transitive + description: + name: vm_service + sha256: b3d56ff4341b8f182b96aceb2fa20e3dcb336b9f867bc0eafc0de10f1048e957 + url: "https://pub.dev" + source: hosted + version: "13.0.0" + watcher: + dependency: transitive + description: + name: watcher + sha256: "3d2ad6751b3c16cf07c7fca317a1413b3f26530319181b37e3b9039b84fc01d8" + url: "https://pub.dev" + source: hosted + version: "1.1.0" + web: + dependency: transitive + description: + name: web + sha256: "97da13628db363c635202ad97068d47c5b8aa555808e7a9411963c533b449b27" + url: "https://pub.dev" + source: hosted + version: "0.5.1" + web_socket_channel: + dependency: transitive + description: + name: web_socket_channel + sha256: "58c6666b342a38816b2e7e50ed0f1e261959630becd4c879c4f26bfa14aa5a42" + url: "https://pub.dev" + source: hosted + version: "2.4.5" + yaml: + dependency: transitive + description: + name: yaml + sha256: "75769501ea3489fca56601ff33454fe45507ea3bfb014161abc3b43ae25989d5" + url: "https://pub.dev" + source: hosted + version: "3.1.2" +sdks: + dart: ">=3.3.0 <4.0.0" + flutter: ">=1.10.0" diff --git a/pubspec.yaml b/pubspec.yaml index 08664996..6e7f1db7 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -1,12 +1,13 @@ name: flutter_ble_lib description: FlutterBle Library is a flutter library that supports BLE operations. It uses MultiPlatformBleAdapter as a native backend.. version: 2.4.0 -homepage: https://github.com/Polidea/FlutterBleLib +homepage: https://github.com/cbreezier/FlutterBleLib +repository: https://github.com/cbreezier/FlutterBleLib.git environment: - sdk: ">=2.12.0-0 <3.0.0" + sdk: ">=2.15.0-0 <4.0.0" # Flutter versions prior to 1.10 did not support the flutter.plugin.platforms map. - flutter: ">=1.10.0 <2.0.0" + flutter: ">=1.10.0" dependencies: collection: ^1.15.0 @@ -15,12 +16,11 @@ dependencies: sdk: flutter dev_dependencies: - mockito: ^5.0.3 - build_runner: ^1.12.2 - pedantic: ^1.11.0 - flutter_test: sdk: flutter + mockito: ^5.0.3 + build_runner: ^2.4.9 + flutter_lints: ^3.0.2 # For information on the generic Dart part of this file, see the # following page: https://dart.dev/tools/pub/pubspec diff --git a/test/characteristic_test.dart b/test/characteristic_test.dart index 882dc2a7..c303de69 100644 --- a/test/characteristic_test.dart +++ b/test/characteristic_test.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:developer'; import 'dart:typed_data'; import 'package:flutter_ble_lib/flutter_ble_lib.dart'; @@ -16,7 +15,7 @@ import 'test_util/descriptor_generator.dart'; @GenerateMocks( [Peripheral, ManagerForDescriptor, DescriptorWithValue], customMocks: [ - MockSpec(returnNullOnMissingStub: true), + MockSpec(onMissingStub: OnMissingStub.returnDefault), ] ) void main() { diff --git a/test/descriptor_test.dart b/test/descriptor_test.dart index fa42207a..e7e6be14 100644 --- a/test/descriptor_test.dart +++ b/test/descriptor_test.dart @@ -1,4 +1,3 @@ -import 'dart:async'; import 'dart:typed_data'; import 'package:flutter_ble_lib/flutter_ble_lib.dart'; diff --git a/test/scan_result.dart b/test/scan_result.dart index 12365e0c..06af9359 100644 --- a/test/scan_result.dart +++ b/test/scan_result.dart @@ -4,9 +4,11 @@ import 'dart:typed_data'; import 'package:flutter_ble_lib/flutter_ble_lib.dart'; import 'package:flutter_test/flutter_test.dart'; +import 'src/bridge/lib_core_test.mocks.dart'; + void main() { group("Test manufacturer data deserialization:", () { - void testManufacturerDataDeserialization(Uint8List manufacturerData) { + void testManufacturerDataDeserialization(Uint8List? manufacturerData) { test("$manufacturerData is deserialized correctly", () { //given String serializedScanResult = @@ -14,7 +16,7 @@ void main() { //when ScanResult scanResult = - ScanResult.fromJson(jsonDecode(serializedScanResult), null); + ScanResult.fromJson(jsonDecode(serializedScanResult), MockInternalBleManager()); //then expect(scanResult.advertisementData.manufacturerData, @@ -28,7 +30,7 @@ void main() { }); group("Test service data deserialization", () { - void testServiceDataDeserialization(Map serviceData) { + void testServiceDataDeserialization(Map? serviceData) { test("$serviceData is deserialized correctly", () { //given String serializedScanResult = @@ -36,7 +38,7 @@ void main() { //when ScanResult scanResult = - ScanResult.fromJson(jsonDecode(serializedScanResult), null); + ScanResult.fromJson(jsonDecode(serializedScanResult), MockInternalBleManager()); //then expect(scanResult.advertisementData.serviceData, equals(serviceData)); @@ -58,13 +60,13 @@ String _createJsonScanResult({ String name = "Valid name", int rssi = -60, bool isConnectable = true, - List overflowServiceUuids, - Uint8List manufacturerData, - Map serviceData, - List serviceUuids, - String localName, - int txPowerLevel, - List solicitedServiceUuids, + List? overflowServiceUuids, + Uint8List? manufacturerData, + Map? serviceData, + List? serviceUuids, + String? localName, + int? txPowerLevel, + List? solicitedServiceUuids, }) { String serializedManufacturerData; if (manufacturerData != null) { @@ -87,7 +89,7 @@ String _createJsonScanResult({ "\"solicitedServiceUuids\": ${_jsonizeList(solicitedServiceUuids)}}"; } -String _jsonizeList(List list) { +String _jsonizeList(List? list) { if (list == null) { return "null"; } else { @@ -103,7 +105,7 @@ String _jsonizeList(List list) { } } -String _jsonizeMap(Map map) { +String _jsonizeMap(Map? map) { if (map == null) { return "null"; } else { diff --git a/test/src/bridge/lib_core_test.dart b/test/src/bridge/lib_core_test.dart index 7ed3679f..7d4e4e7d 100644 --- a/test/src/bridge/lib_core_test.dart +++ b/test/src/bridge/lib_core_test.dart @@ -1,8 +1,7 @@ import 'dart:async'; -@Timeout(const Duration(milliseconds: 500)) import 'dart:convert'; -import 'dart:typed_data'; +import 'package:flutter/foundation.dart'; import 'package:flutter/services.dart'; import 'package:flutter_ble_lib/flutter_ble_lib.dart'; import 'package:flutter_ble_lib/src/_internal.dart'; @@ -16,7 +15,7 @@ import '../../json/ble_error_jsons.dart'; const flutterBleLibMethodChannelName = 'flutter_ble_lib'; const monitorCharacteristicEventChannelName = - flutterBleLibMethodChannelName + '/monitorCharacteristic'; + '$flutterBleLibMethodChannelName/monitorCharacteristic'; const mockServiceUuid = "A0C8AAC8-2C37-4CE4-9110-EA7E09704D54"; const mockCharacteristicUuid = "A56CCE6A-2178-4710-81CA-7895309A1350"; const mockCharacteristicId = 44; @@ -29,56 +28,44 @@ void main() { TestWidgetsFlutterBinding.ensureInitialized(); late FlutterBleLib bleLib; final peripheral = MockPeripheral(); - MethodChannel methodChannel = MethodChannel(flutterBleLibMethodChannelName); + MethodChannel methodChannel = const MethodChannel(flutterBleLibMethodChannelName); MethodChannel eventMethodChannel = - MethodChannel(monitorCharacteristicEventChannelName); + const MethodChannel(monitorCharacteristicEventChannelName); setUp(() { bleLib = FlutterBleLib(MockInternalBleManager()); when(peripheral.identifier).thenReturn("4B:99:4C:34:DE:77"); - methodChannel.setMockMethodCallHandler((call) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(methodChannel, (call) { return Future.value(""); }); - eventMethodChannel.setMockMethodCallHandler((call) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(eventMethodChannel, (call) { return Future.value(""); }); }); - Future _emitPlatformError(String errorJson) async { - final serBinding = ServicesBinding.instance; - if (serBinding == null) { - return; - } - await serBinding.defaultBinaryMessenger.handlePlatformMessage( + Future emitPlatformError(String errorJson) async { + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( monitorCharacteristicEventChannelName, const StandardMethodCodec().encodeErrorEnvelope( code: "irrelevant", details: errorJson ), (data) { - print(data); + debugPrint(data?.toString()); } ); } - Future _emitMonitoringEvent(String eventJson) async { - final serBinding = ServicesBinding.instance; - if (serBinding == null) { - return; - } - await serBinding.defaultBinaryMessenger.handlePlatformMessage( + Future emitMonitoringEvent(String eventJson) async { + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( monitorCharacteristicEventChannelName, const StandardMethodCodec().encodeSuccessEnvelope(eventJson), (data) {} ); } - Future _emitStreamCompletion() async { - final serBinding = ServicesBinding.instance; - if (serBinding == null) { - return; - } - await serBinding.defaultBinaryMessenger.handlePlatformMessage( + Future emitStreamCompletion() async { + await TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.handlePlatformMessage( monitorCharacteristicEventChannelName, null, (data) {}, @@ -132,7 +119,7 @@ void main() { } test('monitorCharacteristicForIdentifier cancels on stream error', () async { - final mockTransId = "asdasd"; + const mockTransId = "asdasd"; final fut = expectLater( bleLib.monitorCharacteristicForIdentifier(peripheral, 123, mockTransId), @@ -141,7 +128,7 @@ void main() { emitsDone, ]) ); - await _emitPlatformError(cancellationErrorJson(mockTransId)); + await emitPlatformError(cancellationErrorJson(mockTransId)); await fut; }); @@ -159,7 +146,7 @@ void main() { emitsError(isInstanceOf()), emitsDone, ])); - await _emitPlatformError(cancellationErrorJson(mockTransId)); + await emitPlatformError(cancellationErrorJson(mockTransId)); await fut; }); @@ -172,7 +159,7 @@ void main() { emitsError(isInstanceOf()), emitsDone, ])); - await _emitPlatformError(cancellationErrorJson(mockTransId)); + await emitPlatformError(cancellationErrorJson(mockTransId)); await fut; }); @@ -191,7 +178,7 @@ void main() { ]) ); - await _emitMonitoringEvent( + await emitMonitoringEvent( jsonEncode( createRawCharacteristic( mockIds: true, @@ -201,7 +188,7 @@ void main() { ) ) ); //[1,0,0,0] - await _emitMonitoringEvent( + await emitMonitoringEvent( jsonEncode( createRawCharacteristic( mockIds: true, @@ -211,7 +198,7 @@ void main() { ) ) ); //[0,1,0,0] - await _emitMonitoringEvent( + await emitMonitoringEvent( jsonEncode( createRawCharacteristic( mockIds: true, @@ -221,7 +208,7 @@ void main() { ) ) ); //[0,0,1,0] - await _emitMonitoringEvent( + await emitMonitoringEvent( jsonEncode( createRawCharacteristic( mockIds: true, @@ -231,7 +218,7 @@ void main() { ) ) ); //[0,0,0,1] - await _emitStreamCompletion(); + await emitStreamCompletion(); await fut; }); @@ -294,11 +281,11 @@ void main() { expect(expected, isNot(equals(invalid2))); expect(expected, isNot(equals(invalid3))); - await _emitMonitoringEvent(jsonEncode(valid)); - await _emitMonitoringEvent(jsonEncode(invalid1)); - await _emitMonitoringEvent(jsonEncode(invalid2)); - await _emitMonitoringEvent(jsonEncode(invalid3)); - await _emitStreamCompletion(); + await emitMonitoringEvent(jsonEncode(valid)); + await emitMonitoringEvent(jsonEncode(invalid1)); + await emitMonitoringEvent(jsonEncode(invalid2)); + await emitMonitoringEvent(jsonEncode(invalid3)); + await emitStreamCompletion(); await fut; }); @@ -319,25 +306,25 @@ void main() { emitsDone ])); - await _emitMonitoringEvent(jsonEncode(createRawCharacteristic( + await emitMonitoringEvent(jsonEncode(createRawCharacteristic( mockIds: true, serviceId: 1, characteristicUuid: "characteristicUuid", transactionId: "1"))); - await _emitMonitoringEvent(jsonEncode(createRawCharacteristic( + await emitMonitoringEvent(jsonEncode(createRawCharacteristic( mockIds: true, serviceId: 1, characteristicUuid: "fakeUuid", transactionId: "1"))); - await _emitMonitoringEvent(jsonEncode(createRawCharacteristic( + await emitMonitoringEvent(jsonEncode(createRawCharacteristic( mockIds: true, serviceId: 2, characteristicUuid: "characteristicUuid", transactionId: "1"))); - await _emitMonitoringEvent(jsonEncode(createRawCharacteristic( + await emitMonitoringEvent(jsonEncode(createRawCharacteristic( mockIds: true, serviceId: 1, characteristicUuid: "characteristicUuid", transactionId: "2"))); - await _emitStreamCompletion(); + await emitStreamCompletion(); await fut; }); @@ -352,7 +339,7 @@ void main() { StreamSubscription subscription1 = monitoringStream.listen((_) {}); int calledCount = 0; - methodChannel.setMockMethodCallHandler((call) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(methodChannel, (call) { if (call.method == MethodName.cancelTransaction && call.arguments[ArgumentName.transactionId] == "1") { calledCount++; @@ -378,7 +365,7 @@ void main() { StreamSubscription subscription = monitoringStream.listen((_) {}); int calledCount = 0; - methodChannel.setMockMethodCallHandler((call) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(methodChannel, (call) { if (call.method == MethodName.cancelTransaction && call.arguments[ArgumentName.transactionId] == "1") { calledCount++; @@ -405,7 +392,7 @@ void main() { monitoringStream.listen((_) {}); int calledCount = 0; - methodChannel.setMockMethodCallHandler((call) { + TestDefaultBinaryMessengerBinding.instance.defaultBinaryMessenger.setMockMethodCallHandler(methodChannel, (call) { if (call.method == MethodName.cancelTransaction && call.arguments[ArgumentName.transactionId] == "1") { calledCount++; diff --git a/test/test_util/characteristic_generator.dart b/test/test_util/characteristic_generator.dart index 0bb0bf7d..698c36b6 100644 --- a/test/test_util/characteristic_generator.dart +++ b/test/test_util/characteristic_generator.dart @@ -10,7 +10,7 @@ export './characteristic_generator.mocks.dart'; @GenerateMocks( [], customMocks:[ - MockSpec(returnNullOnMissingStub: true), + MockSpec(onMissingStub: OnMissingStub.returnDefault), ]) class CharacteristicGenerator { MockManagerForCharacteristic managerForCharacteristic;