Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add on write handler and errors #36

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -209,10 +209,12 @@ class QuickBluePlugin: FlutterPlugin, MethodCallHandler, EventChannel.StreamHand
"ConnectionState" to "connected"
))
} else {
// TODO Parse status code and send correct error messages
cleanConnection(gatt)
sendMessage(messageConnector, mapOf(
"deviceId" to gatt.device.address,
"ConnectionState" to "disconnected"
"ConnectionState" to "disconnected",
"error" to "Disconnection Reason : Status $status"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to connection error's PR

))
}
}
Expand Down Expand Up @@ -260,6 +262,13 @@ class QuickBluePlugin: FlutterPlugin, MethodCallHandler, EventChannel.StreamHand

override fun onCharacteristicWrite(gatt: BluetoothGatt?, characteristic: BluetoothGattCharacteristic, status: Int) {
Log.v(TAG, "onCharacteristicWrite ${characteristic.uuid}, ${characteristic.value.contentToString()} $status")
val deviceID = gatt?.device?.address ?: ""
// TODO Parse status code and send correct error messages
sendMessage(messageConnector, mapOf(
"deviceId" to deviceID,
"characteristic" to characteristic.uuid.toString(),
"error" to "Write Command Status : $status"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"Write Command Status : $status" is a error message, not a program recongized code

An ErrorCode with optional ErrorMessage is a better choice

))
}

override fun onCharacteristicChanged(gatt: BluetoothGatt, characteristic: BluetoothGattCharacteristic) {
Expand Down
20 changes: 19 additions & 1 deletion packages/quick_blue/darwin/QuickBlueDarwin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ public class QuickBlueDarwin: NSObject, FlutterPlugin {
case "stopScan":
manager.stopScan()
result(nil)
case "connect":
case "connect":
let arguments = call.arguments as! Dictionary<String, Any>
let deviceId = arguments["deviceId"] as! String
guard let peripheral = discoveredPeripherals[deviceId] else {
Expand Down Expand Up @@ -200,12 +200,22 @@ extension QuickBlueDarwin: CBCentralManagerDelegate {
"ConnectionState": "connected",
])
}

public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral,error: Error?) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to connection error's PR

print("centralManager:didFailToConnect \(peripheral.uuid.uuidString) error: \(String(describing: error))")
messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"ConnectionState": "disconnected",
"error": String(describing: error)
])
}

public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) {
print("centralManager:didDisconnectPeripheral: \(peripheral.uuid.uuidString) error: \(String(describing: error))")
messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"ConnectionState": "disconnected",
"error": String(describing: error)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to connection error's PR

])
}
}
Expand Down Expand Up @@ -248,6 +258,7 @@ extension QuickBlueDarwin: CBPeripheralDelegate {
}
self.messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"error": String(describing: error),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to discover error's PR

"ServiceState": "discovered",
"service": service.uuid.uuidStr,
"characteristics": service.characteristics!.map { $0.uuid.uuidStr }
Expand All @@ -257,13 +268,20 @@ extension QuickBlueDarwin: CBPeripheralDelegate {
public func peripheral(_ peripheral: CBPeripheral, didWriteValueFor characteristic: CBCharacteristic, error: Error?) {
let data = characteristic.value as NSData?
print("peripheral:didWriteValueForCharacteristic \(characteristic.uuid.uuidStr) \(String(describing: data)) error: \(String(describing: error))")
self.messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"write": "Success",
"characteristic": characteristic.uuid.uuidStr,
"error": String(describing: error)
])
}

public func peripheral(_ peripheral: CBPeripheral, didUpdateValueFor characteristic: CBCharacteristic, error: Error?) {
let data = characteristic.value as NSData?
print("peripheral:didUpdateValueForCharacteristic \(characteristic.uuid) \(String(describing: data)) error: \(String(describing: error))")
self.messageConnector.sendMessage([
"deviceId": peripheral.uuid.uuidString,
"error": String(describing: error),
"characteristicValue": [
"characteristic": characteristic.uuid.uuidStr,
"value": FlutterStandardTypedData(bytes: characteristic.value!)
Expand Down
10 changes: 8 additions & 2 deletions packages/quick_blue/example/lib/peripheral_detail_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ class _PeripheralDetailPageState extends State<PeripheralDetailPage> {
QuickBlue.setConnectionHandler(_handleConnectionChange);
QuickBlue.setServiceHandler(_handleServiceDiscovery);
QuickBlue.setValueHandler(_handleValueChange);
QuickBlue.setWriteValueHandler(_handlerWriteValue);
}

@override
Expand All @@ -48,10 +49,15 @@ class _PeripheralDetailPageState extends State<PeripheralDetailPage> {
QuickBlue.setValueHandler(null);
QuickBlue.setServiceHandler(null);
QuickBlue.setConnectionHandler(null);
QuickBlue.setWriteValueHandler(null);
}

void _handleConnectionChange(String deviceId, BlueConnectionState state) {
debugPrint('_handleConnectionChange $deviceId, $state');
void _handlerWriteValue(String deviceId, String characteristicId, String? error) {
debugPrint('_handlerWriteValue $deviceId, State : $characteristicId ,Error : $error');
}

void _handleConnectionChange(String deviceId, BlueConnectionState state,String? error) {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to connection error's PR

debugPrint('_handleConnectionChange $deviceId,State : ${state.value} , Error : $error');
}

void _handleServiceDiscovery(String deviceId, String serviceId, List<String> characteristicIds) {
Expand Down
4 changes: 4 additions & 0 deletions packages/quick_blue/lib/quick_blue.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ class QuickBlue {
_platform.onConnectionChanged = onConnectionChanged;
}

static void setWriteValueHandler(OnWrite? onWrite) {
_platform.onWrite = onWrite;
}

static void discoverServices(String deviceId) => _platform.discoverServices(deviceId);

static void setServiceHandler(OnServiceDiscovered? onServiceDiscovered) {
Expand Down
17 changes: 10 additions & 7 deletions packages/quick_blue/lib/src/method_channel_quick_blue.dart
Original file line number Diff line number Diff line change
Expand Up @@ -64,18 +64,19 @@ class MethodChannelQuickBlue extends QuickBluePlatform {
}

@override
void discoverServices(String deviceId) {
_method.invokeMethod('discoverServices', {
Future<void> discoverServices(String deviceId) async{
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to discover error's PR

await _method.invokeMethod('discoverServices', {
'deviceId': deviceId,
}).then((_) => _log('discoverServices invokeMethod success'));
}

Future<void> _handleConnectorMessage(dynamic message) async {
_log('_handleConnectorMessage $message', logLevel: Level.ALL);
String? error = (message['error'] == null || message['error'] == 'nil') ? null : message['error'];
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Handle platform-specific type/string on platform. DO NOT handle in Dart/Flutter

if (message['ConnectionState'] != null) {
String deviceId = message['deviceId'];
BlueConnectionState connectionState = BlueConnectionState.parse(message['ConnectionState']);
onConnectionChanged?.call(deviceId, connectionState);
onConnectionChanged?.call(deviceId, connectionState,error);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to connection error's PR

} else if (message['ServiceState'] != null) {
if (message['ServiceState'] == 'discovered') {
String deviceId = message['deviceId'];
Expand All @@ -91,12 +92,14 @@ class MethodChannelQuickBlue extends QuickBluePlatform {
onValueChanged?.call(deviceId, characteristic, value);
} else if (message['mtuConfig'] != null) {
_mtuConfigController.add(message['mtuConfig']);
}else if (message['write'] != null) {
onWrite?.call(message['deviceId'],message['characteristic'],error);
}
}

@override
Future<void> setNotifiable(String deviceId, String service, String characteristic, BleInputProperty bleInputProperty) async {
_method.invokeMethod('setNotifiable', {
await _method.invokeMethod('setNotifiable', {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to notify error's PR

'deviceId': deviceId,
'service': service,
'characteristic': characteristic,
Expand All @@ -106,7 +109,7 @@ class MethodChannelQuickBlue extends QuickBluePlatform {

@override
Future<void> readValue(String deviceId, String service, String characteristic) async {
_method.invokeMethod('readValue', {
await _method.invokeMethod('readValue', {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to read error's PR

'deviceId': deviceId,
'service': service,
'characteristic': characteristic,
Expand All @@ -115,7 +118,7 @@ class MethodChannelQuickBlue extends QuickBluePlatform {

@override
Future<void> writeValue(String deviceId, String service, String characteristic, Uint8List value, BleOutputProperty bleOutputProperty) async {
_method.invokeMethod('writeValue', {
await _method.invokeMethod('writeValue', {
'deviceId': deviceId,
'service': service,
'characteristic': characteristic,
Expand All @@ -134,7 +137,7 @@ class MethodChannelQuickBlue extends QuickBluePlatform {

@override
Future<int> requestMtu(String deviceId, int expectedMtu) async {
_method.invokeMethod('requestMtu', {
await _method.invokeMethod('requestMtu', {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to mtu error's PR

'deviceId': deviceId,
'expectedMtu': expectedMtu,
}).then((_) => _log('requestMtu invokeMethod success'));
Expand Down
27 changes: 18 additions & 9 deletions packages/quick_blue/lib/src/quick_blue_linux.dart
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,24 @@ class QuickBlueLinux extends QuickBluePlatform {
@override
void connect(String deviceId) {
_findDeviceById(deviceId).connect().then((_) {
onConnectionChanged?.call(deviceId, BlueConnectionState.connected);
onConnectionChanged?.call(deviceId, BlueConnectionState.connected,null);
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Move to connection error's PR

});
//TODO : Listen for PropertisChanged event , to update Connection Status on Disconnection from BleDevice ,

// _findDeviceById(deviceId).propertiesChanged.listen((event) {
// print(event);
// });
}

@override
void disconnect(String deviceId) {
_findDeviceById(deviceId).disconnect().then((_) {
onConnectionChanged?.call(deviceId, BlueConnectionState.disconnected);
onConnectionChanged?.call(deviceId, BlueConnectionState.disconnected,null);
});
}

@override
void discoverServices(String deviceId) {
Future<void> discoverServices(String deviceId) async{
var device = _findDeviceById(deviceId);

for (var service in device.gattServices) {
Expand Down Expand Up @@ -173,13 +178,17 @@ class QuickBlueLinux extends QuickBluePlatform {
@override
Future<void> writeValue(String deviceId, String service, String characteristic, Uint8List value, BleOutputProperty bleOutputProperty) async {
var c = _getCharacteristic(deviceId, service, characteristic);

if (bleOutputProperty == BleOutputProperty.withResponse) {
await c.writeValue(value, type: BlueZGattCharacteristicWriteType.request);
} else {
await c.writeValue(value, type: BlueZGattCharacteristicWriteType.command);
try{
if (bleOutputProperty == BleOutputProperty.withResponse) {
await c.writeValue(value, type: BlueZGattCharacteristicWriteType.request);
} else {
await c.writeValue(value, type: BlueZGattCharacteristicWriteType.command);
}
_log('writeValue $characteristic, ${hex.encode(value)}');
onWrite?.call(deviceId,characteristic,null);
}catch(e){
onWrite?.call(deviceId,characteristic,e.toString());
}
_log('writeValue $characteristic, ${hex.encode(value)}');
}

@override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,14 @@ export 'models.dart';

typedef QuickLogger = Logger;

typedef OnConnectionChanged = void Function(String deviceId, BlueConnectionState state);
typedef OnConnectionChanged = void Function(String deviceId, BlueConnectionState state,String? error);

typedef OnServiceDiscovered = void Function(String deviceId, String serviceId, List<String> characteristicIds);

typedef OnValueChanged = void Function(String deviceId, String characteristicId, Uint8List value);

typedef OnWrite = void Function(String deviceId, String characteristicId, String? error);

abstract class QuickBluePlatform extends PlatformInterface {
QuickBluePlatform() : super(token: _token);

Expand Down Expand Up @@ -47,14 +49,16 @@ abstract class QuickBluePlatform extends PlatformInterface {

OnConnectionChanged? onConnectionChanged;

void discoverServices(String deviceId);
Future<void> discoverServices(String deviceId);

OnServiceDiscovered? onServiceDiscovered;

Future<void> setNotifiable(String deviceId, String service, String characteristic, BleInputProperty bleInputProperty);

OnValueChanged? onValueChanged;

OnWrite? onWrite;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

OnWriteValue


Future<void> readValue(String deviceId, String service, String characteristic);

Future<void> writeValue(String deviceId, String service, String characteristic, Uint8List value, BleOutputProperty bleOutputProperty);
Expand Down