Skip to content

Commit

Permalink
Merge branch 'develop' of https://github.com/dotintent/FlutterBleLib
Browse files Browse the repository at this point in the history
…into develop
  • Loading branch information
Leo Huang committed Feb 24, 2022
2 parents 754c3b6 + a4df42e commit eb2d904
Show file tree
Hide file tree
Showing 76 changed files with 3,292 additions and 827 deletions.
37 changes: 37 additions & 0 deletions .github/workflows/dart-flutter-package-analyzer.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
name: Dart/Flutter Package Analyzer
on: [push, pull_request]

jobs:

package-analysis:

runs-on: ubuntu-latest

steps:
- uses: actions/checkout@v2

- uses: axel-op/dart-package-analyzer@v3
# set an id for the current step
id: analysis
with:
githubToken: ${{ secrets.GITHUB_TOKEN }}

# You can then use this id to retrieve the outputs in the next steps.
# The following step shows how to exit the workflow with an error if the total score in percentage is below 50:
- name: Check scores
env:
# NB: "analysis" is the id set above. Replace it with the one you used if different.
TOTAL: ${{ steps.analysis.outputs.total }}
TOTAL_MAX: ${{ steps.analysis.outputs.total_max }}
ANALYSIS: ${{ steps.analysis.outputs.analysis }}
ANALYSIS_MAX: ${{ steps.analysis.outputs.analysis_max }}
run: |
if (( $ANALYSIS < $ANALYSIS_MAX ))
then
echo Unacceptable analysis score! Needs to be maxed out!
exit 1
elif (( $TOTAL < ($TOTAL_MAX - 10) ))
then
echo Unacceptable total score! Check dependencies and other factors!
exit 2
fi
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ lib/generated/
example/lib/generated/
example/.flutter-plugins-dependencies
.dart_tool/
example/ios/Podfile.lock
example/ios/Podfile.lock
.vscode/settings.json
org.eclipse.buildship.core.prefs
.project
.classpath
2 changes: 1 addition & 1 deletion .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ _android_job_template: &android_job_template
_ios_job_template: &ios_job_template
language: objective-c
os: osx
osx_image: xcode11.6
osx_image: xcode12.2
xcode_workspave: example/ios/Runner.xcworkspace
xcode_scheme: Runner
before_script:
Expand Down
34 changes: 34 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,37 @@
## 2.4.0

* Add `BleManager#isClientCreated()` for checking whether native client exists


## 2.3.2

* Fix lack of disconnection event on iOS if connection failed to be established

## 2.3.1

* Fix connection timeout on iOS
* Fix emitting current connection state on iOS
* Update MBA to 0.1.7:
* Fix lack of disconnection event on iOS when connection fails to be established
* Fix not all errors being passed through onError callbacks on Android (thanks, @eliaslecomte)

## 2.3.0

* add `BleManager.createUnsafePeripheral()` to allow for connecting to known peripheral without launching scan first
**NOTE:** this change will not work with BLEmulator below 1.2.0

## 2.2.9

* Fixed issue with incorrectly typed Stream

## 2.2.8

* Formatted all sources according to dartfmt for consistency

## 2.2.7

* Minor code style fixes. Adjusted device connection state monitoring.

## 2.2.6

* Fixed scan quick failures not being reported to the listener (race condition in scanning_mixin.dart)
Expand Down
23 changes: 23 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,19 @@ Add [Privacy - Bluetooth Always Usage Description](https://developer.apple.com/d
...
```

#### Background mode

To support background capabilities add [The `bluetooth-central` Background Execution Mode](https://developer.apple.com/library/archive/documentation/NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/CoreBluetoothBackgroundProcessingForIOSApps/PerformingTasksWhileYourAppIsInTheBackground.html#//apple_ref/doc/uid/TP40013257-CH7-SW6) key to `[project]/ios/Runner/Info.plist` file.

```xml
...
<key>UIBackgroundModes</key>
<array>
<string>bluetooth-central</string>
</array>
...
```

## Usage

The library is organised around a few base entities, which are:
Expand Down Expand Up @@ -122,6 +135,16 @@ It filters the scan results to those that advertise a service with specified UUI

**NOTE:** `isConnectable` and `overflowServiceUuids` fields of `ScanResult` are iOS-only and remain `null` on Android.


### Connecting to saved peripheral

You can try to connect to a peripheral with known ID, be it previously scanned UUID on iOS or a MAC address on Android, and avoid the whole scanning operation in your application. To do so, you need to create an instance of `Peripheral` using:
```dart
Peripheral myPeripheral = bleManager.createUnsafePeripheral("< known id >");
```
Once you have the instance of the peripheral, you may proceed with the connection. But keep in mind
that [Android may still not find the peripheral without scanning it first](https://stackoverflow.com/questions/43476369/android-save-ble-device-to-reconnect-after-app-close/43482099#43482099).

### Connecting to peripheral

First you must obtain a _ScanResult_ from _BleManager.startPeripheralScan()_.
Expand Down
10 changes: 10 additions & 0 deletions analysis_options.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
include: package:pedantic/analysis_options.yaml

analyzer:
exclude: [test/**]

linter:
rules:
prefer_single_quotes: false
omit_local_variable_types: false
unawaited_futures: false
4 changes: 2 additions & 2 deletions android/build.gradle
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
group 'com.polidea.flutter_ble_lib'
version '2.2.5'
version '2.3.2'

buildscript {
repositories {
Expand Down Expand Up @@ -36,5 +36,5 @@ android {

dependencies {
implementation 'androidx.annotation:annotation:1.1.0'
implementation 'com.github.Polidea:MultiPlatformBleAdapter:0.1.6'
implementation 'com.github.Polidea:MultiPlatformBleAdapter:0.1.8'
}
Original file line number Diff line number Diff line change
Expand Up @@ -116,12 +116,22 @@ public void onMethodCall(MethodCall call, Result result) {
case MethodName.CANCEL_TRANSACTION:
cancelTransaction(call, result);
break;
case MethodName.IS_CLIENT_CREATED:
isClientCreated(result);
break;
default:
result.notImplemented();
}
}

private void isClientCreated(Result result) {
result.success(bleAdapter != null);
}

private void createClient(MethodCall call, Result result) {
if (bleAdapter != null) {
Log.w(TAG, "Overwriting existing native client. Use BleManager#isClientCreated to check whether a client already exists.");
}
setupAdapter(context);
bleAdapter.createClient(call.<String>argument(ArgumentKey.RESTORE_STATE_IDENTIFIER),
new OnEventCallback<String>() {
Expand All @@ -139,7 +149,9 @@ public void onEvent(Integer restoreStateIdentifier) {
}

private void destroyClient(Result result) {
bleAdapter.destroyClient();
if (bleAdapter != null) {
bleAdapter.destroyClient();
}
scanningStreamHandler.onComplete();
connectionStateStreamHandler.onComplete();
bleAdapter = null;
Expand Down Expand Up @@ -167,13 +179,17 @@ public void onError(BleError error) {
}

private void stopDeviceScan(Result result) {
bleAdapter.stopDeviceScan();
if (bleAdapter != null) {
bleAdapter.stopDeviceScan();
}
scanningStreamHandler.onComplete();
result.success(null);
}

private void cancelTransaction(MethodCall call, Result result) {
bleAdapter.cancelTransaction(call.<String>argument(ArgumentKey.TRANSACTION_ID));
if (bleAdapter != null) {
bleAdapter.cancelTransaction(call.<String>argument(ArgumentKey.TRANSACTION_ID));
}
result.success(null);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ public interface ArgumentKey {
String IS_AUTO_CONNECT = "isAutoConnect";
String REQUEST_MTU = "requestMtu";
String REFRESH_GATT = "refreshGatt";
String TIMEOUT_MILLIS = "timeoutMillis";
String TIMEOUT_MILLIS = "timeout";
String EMIT_CURRENT_VALUE = "emitCurrentValue";

String LOG_LEVEL = "logLevel";
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.polidea.flutter_ble_lib.constant;

public interface MethodName {
String IS_CLIENT_CREATED = "isClientCreated";
String CREATE_CLIENT = "createClient";
String DESTROY_CLIENT = "destroyClient";

Expand Down
81 changes: 16 additions & 65 deletions example/ios/Podfile
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# Uncomment this line to define a global platform for your project
# platform :ios, '9.0'
platform :ios, '9.0'

# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'
Expand All @@ -10,81 +10,32 @@ project 'Runner', {
'Release' => :release,
}

def parse_KV_file(file, separator='=')
file_abs_path = File.expand_path(file)
if !File.exists? file_abs_path
return [];
def flutter_root
generated_xcode_build_settings_path = File.expand_path(File.join('..', 'Flutter', 'Generated.xcconfig'), __FILE__)
unless File.exist?(generated_xcode_build_settings_path)
raise "#{generated_xcode_build_settings_path} must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
generated_key_values = {}
skip_line_start_symbols = ["#", "/"]
File.foreach(file_abs_path) do |line|
next if skip_line_start_symbols.any? { |symbol| line =~ /^\s*#{symbol}/ }
plugin = line.split(pattern=separator)
if plugin.length == 2
podname = plugin[0].strip()
path = plugin[1].strip()
podpath = File.expand_path("#{path}", file_abs_path)
generated_key_values[podname] = podpath
else
puts "Invalid plugin specification: #{line}"
end

File.foreach(generated_xcode_build_settings_path) do |line|
matches = line.match(/FLUTTER_ROOT\=(.*)/)
return matches[1].strip if matches
end
generated_key_values
raise "FLUTTER_ROOT not found in #{generated_xcode_build_settings_path}. Try deleting Generated.xcconfig, then run flutter pub get"
end

require File.expand_path(File.join('packages', 'flutter_tools', 'bin', 'podhelper'), flutter_root)

flutter_ios_podfile_setup

target 'Runner' do
use_frameworks!
use_modular_headers!

# Flutter Pod

copied_flutter_dir = File.join(__dir__, 'Flutter')
copied_framework_path = File.join(copied_flutter_dir, 'Flutter.framework')
copied_podspec_path = File.join(copied_flutter_dir, 'Flutter.podspec')
unless File.exist?(copied_framework_path) && File.exist?(copied_podspec_path)
# Copy Flutter.framework and Flutter.podspec to Flutter/ to have something to link against if the xcode backend script has not run yet.
# That script will copy the correct debug/profile/release version of the framework based on the currently selected Xcode configuration.
# CocoaPods will not embed the framework on pod install (before any build phases can generate) if the dylib does not exist.

generated_xcode_build_settings_path = File.join(copied_flutter_dir, 'Generated.xcconfig')
unless File.exist?(generated_xcode_build_settings_path)
raise "Generated.xcconfig must exist. If you're running pod install manually, make sure flutter pub get is executed first"
end
generated_xcode_build_settings = parse_KV_file(generated_xcode_build_settings_path)
cached_framework_dir = generated_xcode_build_settings['FLUTTER_FRAMEWORK_DIR'];

unless File.exist?(copied_framework_path)
FileUtils.cp_r(File.join(cached_framework_dir, 'Flutter.framework'), copied_flutter_dir)
end
unless File.exist?(copied_podspec_path)
FileUtils.cp(File.join(cached_framework_dir, 'Flutter.podspec'), copied_flutter_dir)
end
end

# Keep pod path relative so it can be checked into Podfile.lock.
pod 'Flutter', :path => 'Flutter'

# Plugin Pods

# Prepare symlinks folder. We use symlinks to avoid having Podfile.lock
# referring to absolute paths on developers' machines.
system('rm -rf .symlinks')
system('mkdir -p .symlinks/plugins')
plugin_pods = parse_KV_file('../.flutter-plugins')
plugin_pods.each do |name, path|
symlink = File.join('.symlinks', 'plugins', name)
File.symlink(path, symlink)
pod name, :path => File.join(symlink, 'ios')
end
flutter_install_all_ios_pods File.dirname(File.realpath(__FILE__))
end

# Prevent Cocoapods from embedding a second Flutter framework and causing an error with the new Xcode build system.
install! 'cocoapods', :disable_input_output_paths => true

post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings['ENABLE_BITCODE'] = 'NO'
end
flutter_additional_ios_build_settings(target)
end
end
Loading

0 comments on commit eb2d904

Please sign in to comment.