From 747f3083ab9e464d4a685b9267f562efd59073de Mon Sep 17 00:00:00 2001 From: Martijn van Welie Date: Fri, 8 May 2020 17:29:19 +0200 Subject: [PATCH] Adding new functionality to issue PIN codes for peripherals with a fixed PIN code --- .../java/com/welie/blessed/BluetoothCentral.java | 13 +++++++++++++ .../java/com/welie/blessed/BluetoothPeripheral.java | 12 +++++++++++- 2 files changed, 24 insertions(+), 1 deletion(-) diff --git a/blessed/src/main/java/com/welie/blessed/BluetoothCentral.java b/blessed/src/main/java/com/welie/blessed/BluetoothCentral.java index e8c12de..8c68894 100644 --- a/blessed/src/main/java/com/welie/blessed/BluetoothCentral.java +++ b/blessed/src/main/java/com/welie/blessed/BluetoothCentral.java @@ -118,6 +118,7 @@ public class BluetoothCentral { private final Map connectionRetries = new ConcurrentHashMap<>(); private boolean expectingBluetoothOffDisconnects = false; private Runnable disconnectRunnable; + private Map pinCodes = new ConcurrentHashMap<>(); //region Callbacks @@ -289,6 +290,11 @@ public void run() { } }); } + + @Override + public String getPincode(BluetoothPeripheral device) { + return pinCodes.get(device.getAddress()); + } }; //endregion @@ -902,6 +908,13 @@ private void cancelAutoConnectTimer() { } } + /** + * Add a fixed PIN code for a peripheral + */ + public void addPinForPeripheral(String peripheralAddress, String pin) { + pinCodes.put(peripheralAddress, pin); + } + /** * Remove bond for a peripheral. * diff --git a/blessed/src/main/java/com/welie/blessed/BluetoothPeripheral.java b/blessed/src/main/java/com/welie/blessed/BluetoothPeripheral.java index 160b925..4c828cb 100644 --- a/blessed/src/main/java/com/welie/blessed/BluetoothPeripheral.java +++ b/blessed/src/main/java/com/welie/blessed/BluetoothPeripheral.java @@ -717,8 +717,16 @@ public void onReceive(final Context context, final Intent intent) { return; // String values are used as the constants are not available for Android 4.3. - final int variant = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_VARIANT"/*BluetoothDevice.EXTRA_PAIRING_VARIANT*/, 0); + final int variant = intent.getIntExtra("android.bluetooth.device.extra.PAIRING_VARIANT", 0); Timber.d("pairing request received " + ", pairing variant: " + pairingVariantToString(variant) + " (" + variant + ")"); + + if (variant == PAIRING_VARIANT_PIN) { + String pin = listener.getPincode(BluetoothPeripheral.this); + if (pin != null) { + Timber.d("Setting PIN code for this peripheral using '%s'", pin); + device.setPin(pin.getBytes()); + } + } } }; @@ -1742,6 +1750,8 @@ interface InternalCallback { */ void disconnected(BluetoothPeripheral device, final int status); + String getPincode(BluetoothPeripheral device); + } /////////////////