more permission checks

This commit is contained in:
Milos Kozak 2022-07-21 19:19:31 +02:00
parent 6d3f0014c2
commit 6c4796fd21
19 changed files with 216 additions and 103 deletions

View file

@ -789,7 +789,6 @@
<string name="needsystemwindowpermission">Application needs system window permission for notifications</string> <string name="needsystemwindowpermission">Application needs system window permission for notifications</string>
<string name="needlocationpermission">Application needs location permission for BT scan and WiFi identification</string> <string name="needlocationpermission">Application needs location permission for BT scan and WiFi identification</string>
<string name="needstoragepermission">Application needs storage permission to be able store log files and export settings</string> <string name="needstoragepermission">Application needs storage permission to be able store log files and export settings</string>
<string name="needconnectpermission">Application needs bluetooth permission</string>
<string name="request">Request</string> <string name="request">Request</string>
<string name="open_navigation">Open navigation</string> <string name="open_navigation">Open navigation</string>
<string name="close_navigation">Close navigation</string> <string name="close_navigation">Close navigation</string>

View file

@ -1,8 +1,11 @@
package info.nightscout.androidaps.plugins.general.automation.triggers package info.nightscout.androidaps.plugins.general.automation.triggers
import android.Manifest
import android.bluetooth.BluetoothManager import android.bluetooth.BluetoothManager
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.widget.LinearLayout import android.widget.LinearLayout
import androidx.core.app.ActivityCompat
import com.google.common.base.Optional import com.google.common.base.Optional
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.automation.R
@ -13,9 +16,9 @@ import info.nightscout.androidaps.plugins.general.automation.elements.InputDropd
import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder
import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel import info.nightscout.androidaps.plugins.general.automation.elements.StaticLabel
import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.shared.logging.LTag import info.nightscout.shared.logging.LTag
import org.json.JSONObject import org.json.JSONObject
import java.util.*
import javax.inject.Inject import javax.inject.Inject
class TriggerBTDevice(injector: HasAndroidInjector) : Trigger(injector) { class TriggerBTDevice(injector: HasAndroidInjector) : Trigger(injector) {
@ -74,7 +77,11 @@ class TriggerBTDevice(injector: HasAndroidInjector) : Trigger(injector) {
// Get the list of paired BT devices to use in dropdown menu // Get the list of paired BT devices to use in dropdown menu
private fun devicesPaired(): ArrayList<CharSequence> { private fun devicesPaired(): ArrayList<CharSequence> {
val s = ArrayList<CharSequence>() val s = ArrayList<CharSequence>()
(context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter?.bondedDevices?.forEach { s.add(it.name) } if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
(context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter?.bondedDevices?.forEach { s.add(it.name) }
} else {
ToastUtils.errorToast(context, context.getString(R.string.needconnectpermission))
}
return s return s
} }

View file

@ -8,6 +8,8 @@
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" /> <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<application android:supportsRtl="true"> <application android:supportsRtl="true">
<activity <activity
android:name="info.nightscout.androidaps.activities.TDDStatsActivity" android:name="info.nightscout.androidaps.activities.TDDStatsActivity"

View file

@ -43,11 +43,10 @@ class BlePreCheck @Inject constructor(
} }
// change after SDK = 31+ // change after SDK = 31+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH_CONNECT") != PackageManager.PERMISSION_GRANTED || if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH_SCAN") != PackageManager.PERMISSION_GRANTED ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) != PackageManager.PERMISSION_GRANTED
) { ) {
//ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT), PERMISSION_REQUEST_BLUETOOTH) ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT), PERMISSION_REQUEST_BLUETOOTH)
ActivityCompat.requestPermissions(activity, arrayOf("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT"), PERMISSION_REQUEST_BLUETOOTH)
return false return false
} }
} }

View file

@ -0,0 +1,32 @@
package info.nightscout.androidaps.utils.ui
import android.Manifest
import kotlin.jvm.JvmOverloads
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.pm.PackageManager
import android.util.AttributeSet
import androidx.core.app.ActivityCompat
import androidx.preference.ListPreference
import info.nightscout.androidaps.core.R
import info.nightscout.androidaps.utils.ToastUtils
import java.util.*
class BluetoothDevicePreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ListPreference(context, attrs) {
init {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
val devices = Vector<CharSequence>()
(context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter?.let { bta ->
for (dev in bta.bondedDevices)
dev.name?.let { name -> devices.add(name) }
}
entries = devices.toTypedArray()
entryValues = devices.toTypedArray()
} else {
entries = emptyArray()
entryValues = emptyArray()
ToastUtils.errorToast(context, context.getString(R.string.needconnectpermission))
}
}
}

View file

@ -601,6 +601,7 @@
<string name="autotune_run_with_autoswitch">Autotune runned and profile automatically switched</string> <string name="autotune_run_with_autoswitch">Autotune runned and profile automatically switched</string>
<string name="autotune_run_with_error">Error during last Autotune run</string> <string name="autotune_run_with_error">Error during last Autotune run</string>
<string name="autotune_run_cancelled">Another run of Autotune is detected, run cancelled</string> <string name="autotune_run_cancelled">Another run of Autotune is detected, run cancelled</string>
<string name="needconnectpermission">Application needs bluetooth permission</string>
<plurals name="days"> <plurals name="days">
<item quantity="one">%1$d day</item> <item quantity="one">%1$d day</item>

View file

@ -1,22 +0,0 @@
package info.nightscout.androidaps.danar
import kotlin.jvm.JvmOverloads
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice
import android.bluetooth.BluetoothManager
import android.content.Context
import android.util.AttributeSet
import androidx.preference.ListPreference
import java.util.*
class BluetoothDevicePreference @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null) : ListPreference(context, attrs) {
init {
val entries = Vector<CharSequence>()
(context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager?)?.adapter?.let { bta ->
for (dev in bta.bondedDevices)
dev.name?.let { name -> entries.add(name) }
}
setEntries(entries.toTypedArray())
entryValues = entries.toTypedArray()
}
}

View file

@ -1,14 +1,18 @@
package info.nightscout.androidaps.danar.services; package info.nightscout.androidaps.danar.services;
import android.Manifest;
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket; import android.bluetooth.BluetoothSocket;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder; import android.os.IBinder;
import android.os.SystemClock; import android.os.SystemClock;
import androidx.core.app.ActivityCompat;
import java.io.IOException; import java.io.IOException;
import java.util.Set; import java.util.Set;
import java.util.UUID; import java.util.UUID;
@ -41,8 +45,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged;
import info.nightscout.androidaps.interfaces.ActivePlugin; import info.nightscout.androidaps.interfaces.ActivePlugin;
import info.nightscout.androidaps.interfaces.Profile; import info.nightscout.androidaps.interfaces.Profile;
import info.nightscout.androidaps.interfaces.PumpSync; import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.shared.logging.AAPSLogger; import info.nightscout.androidaps.interfaces.ResourceHelper;
import info.nightscout.shared.logging.LTag;
import info.nightscout.androidaps.plugins.bus.RxBus; import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification; import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress; import info.nightscout.androidaps.plugins.general.overview.events.EventOverviewBolusProgress;
@ -50,8 +53,9 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
import info.nightscout.androidaps.utils.DateUtil; import info.nightscout.androidaps.utils.DateUtil;
import info.nightscout.androidaps.utils.FabricPrivacy; import info.nightscout.androidaps.utils.FabricPrivacy;
import info.nightscout.androidaps.utils.ToastUtils; import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.interfaces.ResourceHelper;
import info.nightscout.androidaps.utils.rx.AapsSchedulers; import info.nightscout.androidaps.utils.rx.AapsSchedulers;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
import info.nightscout.shared.sharedPreferences.SP; import info.nightscout.shared.sharedPreferences.SP;
import io.reactivex.rxjava3.disposables.CompositeDisposable; import io.reactivex.rxjava3.disposables.CompositeDisposable;
@ -191,30 +195,32 @@ public abstract class AbstractDanaRExecutionService extends DaggerService {
protected void getBTSocketForSelectedPump() { protected void getBTSocketForSelectedPump() {
mDevName = sp.getString(R.string.key_danar_bt_name, ""); mDevName = sp.getString(R.string.key_danar_bt_name, "");
BluetoothAdapter bluetoothAdapter = ((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter(); if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
BluetoothAdapter bluetoothAdapter = ((BluetoothManager) context.getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
if (bluetoothAdapter != null) { if (bluetoothAdapter != null) {
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices(); Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices != null) if (bondedDevices != null)
for (BluetoothDevice device : bondedDevices) { for (BluetoothDevice device : bondedDevices) {
if (mDevName.equals(device.getName())) { if (mDevName.equals(device.getName())) {
mBTDevice = device; mBTDevice = device;
try { try {
mRfcommSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID); mRfcommSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) { } catch (IOException e) {
aapsLogger.error("Error creating socket: ", e); aapsLogger.error("Error creating socket: ", e);
}
break;
} }
break;
} }
} } else {
ToastUtils.INSTANCE.showToastInUiThread(context.getApplicationContext(), rh.gs(R.string.nobtadapter));
}
if (mBTDevice == null) {
ToastUtils.INSTANCE.showToastInUiThread(context.getApplicationContext(), rh.gs(R.string.devicenotfound));
}
} else { } else {
ToastUtils.INSTANCE.showToastInUiThread(context.getApplicationContext(), ToastUtils.INSTANCE.errorToast(context, context.getString(R.string.needconnectpermission));
rh.gs(R.string.nobtadapter));
}
if (mBTDevice == null) {
ToastUtils.INSTANCE.showToastInUiThread(context.getApplicationContext(),
rh.gs(R.string.devicenotfound));
} }
} }

View file

@ -8,7 +8,7 @@
android:title="@string/danar_pump_settings" android:title="@string/danar_pump_settings"
app:initialExpandedChildrenCount="0"> app:initialExpandedChildrenCount="0">
<info.nightscout.androidaps.danar.BluetoothDevicePreference <info.nightscout.androidaps.utils.ui.BluetoothDevicePreference
android:dialogTitle="@string/danar_bt_name_title" android:dialogTitle="@string/danar_bt_name_title"
android:key="@string/key_danar_bt_name" android:key="@string/key_danar_bt_name"
android:title="@string/danar_bt_name_title" /> android:title="@string/danar_bt_name_title" />

View file

@ -8,7 +8,7 @@
android:title="@string/danar_pump_settings" android:title="@string/danar_pump_settings"
app:initialExpandedChildrenCount="0"> app:initialExpandedChildrenCount="0">
<info.nightscout.androidaps.danar.BluetoothDevicePreference <info.nightscout.androidaps.utils.ui.BluetoothDevicePreference
android:dialogTitle="@string/danar_bt_name_title" android:dialogTitle="@string/danar_bt_name_title"
android:key="@string/key_danar_bt_name" android:key="@string/key_danar_bt_name"
android:title="@string/danar_bt_name_title" /> android:title="@string/danar_bt_name_title" />

View file

@ -8,7 +8,7 @@
android:title="@string/danar_pump_settings" android:title="@string/danar_pump_settings"
app:initialExpandedChildrenCount="0"> app:initialExpandedChildrenCount="0">
<info.nightscout.androidaps.danar.BluetoothDevicePreference <info.nightscout.androidaps.utils.ui.BluetoothDevicePreference
android:dialogTitle="@string/danar_bt_name_title" android:dialogTitle="@string/danar_bt_name_title"
android:key="@string/key_danar_bt_name" android:key="@string/key_danar_bt_name"
android:title="@string/danar_bt_name_title" /> android:title="@string/danar_bt_name_title" />

View file

@ -5,6 +5,8 @@
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" /> <uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<application> <application>
<activity <activity
android:name="info.nightscout.androidaps.danars.activities.BLEScanActivity" android:name="info.nightscout.androidaps.danars.activities.BLEScanActivity"

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.danars.activities package info.nightscout.androidaps.danars.activities
import android.Manifest
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothDevice
@ -9,6 +10,7 @@ import android.bluetooth.le.ScanCallback
import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanResult
import android.content.Context import android.content.Context
import android.content.pm.ActivityInfo import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
@ -16,14 +18,14 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.BaseAdapter import android.widget.BaseAdapter
import android.widget.TextView import android.widget.TextView
import androidx.core.app.ActivityCompat
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.danars.R import info.nightscout.androidaps.danars.R
import info.nightscout.androidaps.danars.databinding.DanarsBlescannerActivityBinding import info.nightscout.androidaps.danars.databinding.DanarsBlescannerActivityBinding
import info.nightscout.androidaps.danars.events.EventDanaRSDeviceChange import info.nightscout.androidaps.danars.events.EventDanaRSDeviceChange
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP
import java.util.*
import java.util.regex.Pattern import java.util.regex.Pattern
import javax.inject.Inject import javax.inject.Inject
@ -58,8 +60,12 @@ class BLEScanActivity : NoSplashAppCompatActivity() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
if (bluetoothAdapter?.isEnabled != true) bluetoothAdapter?.enable() if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
startScan() if (bluetoothAdapter?.isEnabled != true) bluetoothAdapter?.enable()
startScan()
} else {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
}
} }
override fun onPause() { override fun onPause() {
@ -68,17 +74,26 @@ class BLEScanActivity : NoSplashAppCompatActivity() {
} }
private fun startScan() = private fun startScan() =
try { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
bluetoothLeScanner?.startScan(mBleScanCallback) try {
} catch (e: IllegalStateException) { bluetoothLeScanner?.startScan(mBleScanCallback)
} // ignore BT not on } catch (ignore: IllegalStateException) {
} // ignore BT not on
} else {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
}
private fun stopScan() = private fun stopScan() =
try { if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
bluetoothLeScanner?.stopScan(mBleScanCallback) try {
} catch (e: IllegalStateException) { bluetoothLeScanner?.stopScan(mBleScanCallback)
} // ignore BT not on } catch (ignore: IllegalStateException) {
} // ignore BT not on
} else {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
}
@SuppressLint("MissingPermission")
private fun addBleDevice(device: BluetoothDevice?) { private fun addBleDevice(device: BluetoothDevice?) {
if (device == null || device.name == null || device.name == "") { if (device == null || device.name == null || device.name == "") {
return return
@ -132,11 +147,16 @@ class BLEScanActivity : NoSplashAppCompatActivity() {
override fun onClick(v: View) { override fun onClick(v: View) {
sp.putString(R.string.key_danars_address, item.device.address) sp.putString(R.string.key_danars_address, item.device.address)
sp.putString(R.string.key_danars_name, name.text.toString()) sp.putString(R.string.key_danars_name, name.text.toString())
item.device.createBond() if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
rxBus.send(EventDanaRSDeviceChange()) item.device.createBond()
rxBus.send(EventDanaRSDeviceChange())
} else {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
}
finish() finish()
} }
@SuppressLint("MissingPermission")
fun setData(data: BluetoothDeviceItem) { fun setData(data: BluetoothDeviceItem) {
var tTitle = data.device.name var tTitle = data.device.name
if (tTitle == null || tTitle == "") { if (tTitle == null || tTitle == "") {

View file

@ -1,10 +1,14 @@
package info.nightscout.androidaps.danars.services package info.nightscout.androidaps.danars.services
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.* import android.bluetooth.*
import android.content.Context import android.content.Context
import android.content.Intent import android.content.Intent
import android.content.pm.PackageManager
import android.os.SystemClock import android.os.SystemClock
import android.util.Base64 import android.util.Base64
import androidx.core.app.ActivityCompat
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.dana.DanaPump import info.nightscout.androidaps.dana.DanaPump
import info.nightscout.androidaps.danars.DanaRSPlugin import info.nightscout.androidaps.danars.DanaRSPlugin
@ -21,6 +25,7 @@ import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.extensions.notify import info.nightscout.androidaps.extensions.notify
import info.nightscout.androidaps.extensions.waitMillis import info.nightscout.androidaps.extensions.waitMillis
import info.nightscout.androidaps.interfaces.PumpSync import info.nightscout.androidaps.interfaces.PumpSync
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification import info.nightscout.androidaps.plugins.general.overview.events.EventDismissNotification
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification
@ -28,7 +33,6 @@ import info.nightscout.androidaps.plugins.general.overview.notifications.Notific
import info.nightscout.androidaps.utils.DateUtil import info.nightscout.androidaps.utils.DateUtil
import info.nightscout.androidaps.utils.T import info.nightscout.androidaps.utils.T
import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP
@ -90,6 +94,11 @@ class BLEComm @Inject internal constructor(
@Synchronized @Synchronized
fun connect(from: String, address: String?): Boolean { fun connect(from: String, address: String?): Boolean {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
aapsLogger.error(LTag.PUMPBTCOMM, "missing permission: $from")
return false
}
aapsLogger.debug(LTag.PUMPBTCOMM, "Initializing BLEComm.") aapsLogger.debug(LTag.PUMPBTCOMM, "Initializing BLEComm.")
if (bluetoothAdapter == null) { if (bluetoothAdapter == null) {
aapsLogger.error("Unable to obtain a BluetoothAdapter.") aapsLogger.error("Unable to obtain a BluetoothAdapter.")
@ -107,8 +116,10 @@ class BLEComm @Inject internal constructor(
return false return false
} }
if (device.bondState == BluetoothDevice.BOND_NONE) { if (device.bondState == BluetoothDevice.BOND_NONE) {
device.createBond() if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
SystemClock.sleep(10000) device.createBond()
SystemClock.sleep(10000)
}
return false return false
} }
isConnected = false isConnected = false
@ -131,6 +142,10 @@ class BLEComm @Inject internal constructor(
@Synchronized @Synchronized
fun disconnect(from: String) { fun disconnect(from: String) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
aapsLogger.error(LTag.PUMPBTCOMM, "missing permission: $from")
return
}
aapsLogger.debug(LTag.PUMPBTCOMM, "disconnect from: $from") aapsLogger.debug(LTag.PUMPBTCOMM, "disconnect from: $from")
if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_BLE5) { if (!encryptedDataRead && encryptedCommandSent && encryption == EncryptionType.ENCRYPTION_BLE5) {
@ -191,6 +206,7 @@ class BLEComm @Inject internal constructor(
} }
} }
@SuppressLint("MissingPermission")
@Synchronized fun close() { @Synchronized fun close() {
/* /*
if (!encryptedDataRead && !encryptedCommandSent) { if (!encryptedDataRead && !encryptedCommandSent) {
@ -268,6 +284,7 @@ class BLEComm @Inject internal constructor(
} }
} }
@SuppressLint("MissingPermission")
@Synchronized @Synchronized
private fun setCharacteristicNotification(characteristic: BluetoothGattCharacteristic?, enabled: Boolean) { private fun setCharacteristicNotification(characteristic: BluetoothGattCharacteristic?, enabled: Boolean) {
aapsLogger.debug(LTag.PUMPBTCOMM, "setCharacteristicNotification") aapsLogger.debug(LTag.PUMPBTCOMM, "setCharacteristicNotification")
@ -287,6 +304,7 @@ class BLEComm @Inject internal constructor(
} }
} }
@SuppressLint("MissingPermission")
@Synchronized @Synchronized
private fun writeCharacteristicNoResponse(characteristic: BluetoothGattCharacteristic, data: ByteArray) { private fun writeCharacteristicNoResponse(characteristic: BluetoothGattCharacteristic, data: ByteArray) {
Thread(Runnable { Thread(Runnable {
@ -346,6 +364,7 @@ class BLEComm @Inject internal constructor(
} }
} }
@SuppressLint("MissingPermission")
@Synchronized @Synchronized
private fun onConnectionStateChangeSynchronized(gatt: BluetoothGatt, newState: Int) { private fun onConnectionStateChangeSynchronized(gatt: BluetoothGatt, newState: Int) {
aapsLogger.debug(LTag.PUMPBTCOMM, "onConnectionStateChange") aapsLogger.debug(LTag.PUMPBTCOMM, "onConnectionStateChange")
@ -559,7 +578,7 @@ class BLEComm @Inject internal constructor(
sp.putString(rh.gs(R.string.key_dana_ble5_pairingkey) + danaRSPlugin.mDeviceName, pairingKey) sp.putString(rh.gs(R.string.key_dana_ble5_pairingkey) + danaRSPlugin.mDeviceName, pairingKey)
val storedPairingKey = sp.getString(rh.gs(R.string.key_dana_ble5_pairingkey) + danaRSPlugin.mDeviceName, "") val storedPairingKey = sp.getString(rh.gs(R.string.key_dana_ble5_pairingkey) + danaRSPlugin.mDeviceName, "")
if (storedPairingKey.isNullOrBlank()) { if (storedPairingKey.isBlank()) {
removeBond() removeBond()
disconnect("Non existing pairing key") disconnect("Non existing pairing key")
} }

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.diaconn.activities package info.nightscout.androidaps.diaconn.activities
import android.Manifest
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothDevice
@ -11,6 +12,7 @@ import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings import android.bluetooth.le.ScanSettings
import android.content.Context import android.content.Context
import android.content.pm.ActivityInfo import android.content.pm.ActivityInfo
import android.content.pm.PackageManager
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.Looper import android.os.Looper
@ -19,12 +21,13 @@ import android.view.View
import android.view.ViewGroup import android.view.ViewGroup
import android.widget.BaseAdapter import android.widget.BaseAdapter
import android.widget.TextView import android.widget.TextView
import androidx.core.app.ActivityCompat
import info.nightscout.androidaps.activities.NoSplashAppCompatActivity import info.nightscout.androidaps.activities.NoSplashAppCompatActivity
import info.nightscout.androidaps.diaconn.events.EventDiaconnG8DeviceChange
import info.nightscout.androidaps.diaconn.R import info.nightscout.androidaps.diaconn.R
import info.nightscout.androidaps.diaconn.databinding.DiaconnG8BlescannerActivityBinding import info.nightscout.androidaps.diaconn.databinding.DiaconnG8BlescannerActivityBinding
import info.nightscout.androidaps.plugins.bus.RxBus import info.nightscout.androidaps.diaconn.events.EventDiaconnG8DeviceChange
import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP
import java.util.* import java.util.*
import javax.inject.Inject import javax.inject.Inject
@ -61,18 +64,25 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() {
override fun onResume() { override fun onResume() {
super.onResume() super.onResume()
bluetoothAdapter?.let { bluetoothAdapter -> if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
if (!bluetoothAdapter.isEnabled) bluetoothAdapter.enable() bluetoothAdapter?.let { bluetoothAdapter ->
bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner if (!bluetoothAdapter.isEnabled) bluetoothAdapter.enable()
startScan() bluetoothLeScanner = bluetoothAdapter.bluetoothLeScanner
startScan()
}
} else {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
} }
} }
override fun onPause() { override fun onPause() {
super.onPause() super.onPause()
stopScan() if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
stopScan()
}
} }
@SuppressLint("MissingPermission")
private fun startScan() = private fun startScan() =
try { try {
val filters: MutableList<ScanFilter> = ArrayList() val filters: MutableList<ScanFilter> = ArrayList()
@ -86,16 +96,21 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() {
.build() .build()
bluetoothLeScanner?.startScan(filters, settings, mBleScanCallback) bluetoothLeScanner?.startScan(filters, settings, mBleScanCallback)
} catch (e: IllegalStateException) { } catch (ignored: IllegalStateException) {
} // ignore BT not on } // ignore BT not on
@SuppressLint("MissingPermission")
private fun stopScan() = private fun stopScan() =
try { try {
bluetoothLeScanner?.stopScan(mBleScanCallback) bluetoothLeScanner?.stopScan(mBleScanCallback)
} catch (e: IllegalStateException) { } catch (ignored: IllegalStateException) {
} // ignore BT not on } // ignore BT not on
private fun addBleDevice(device: BluetoothDevice?) { private fun addBleDevice(device: BluetoothDevice?) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
return
}
if (device == null || device.name == null || device.name == "") { if (device == null || device.name == null || device.name == "") {
return return
} }
@ -145,6 +160,7 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() {
v.setOnClickListener(this@ViewHolder) v.setOnClickListener(this@ViewHolder)
} }
@SuppressLint("MissingPermission")
override fun onClick(v: View) { override fun onClick(v: View) {
sp.putString(R.string.key_diaconn_g8_address, item.device.address) sp.putString(R.string.key_diaconn_g8_address, item.device.address)
sp.putString(R.string.key_diaconn_g8_name, name.text.toString()) sp.putString(R.string.key_diaconn_g8_name, name.text.toString())
@ -153,6 +169,7 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() {
finish() finish()
} }
@SuppressLint("MissingPermission")
fun setData(data: BluetoothDeviceItem) { fun setData(data: BluetoothDeviceItem) {
var tTitle = data.device.name var tTitle = data.device.name
if (tTitle == null || tTitle == "") { if (tTitle == null || tTitle == "") {
@ -168,6 +185,7 @@ class DiaconnG8BLEScanActivity : NoSplashAppCompatActivity() {
// //
inner class BluetoothDeviceItem internal constructor(val device: BluetoothDevice) { inner class BluetoothDeviceItem internal constructor(val device: BluetoothDevice) {
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (other !is BluetoothDeviceItem) { if (other !is BluetoothDeviceItem) {
return false return false

View file

@ -1,9 +1,12 @@
package info.nightscout.androidaps.diaconn.service package info.nightscout.androidaps.diaconn.service
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.* import android.bluetooth.*
import android.content.Context import android.content.Context
import android.content.Intent import android.content.pm.PackageManager
import android.os.SystemClock import android.os.SystemClock
import androidx.core.app.ActivityCompat
import dagger.android.HasAndroidInjector import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.diaconn.DiaconnG8Pump import info.nightscout.androidaps.diaconn.DiaconnG8Pump
@ -12,10 +15,11 @@ import info.nightscout.androidaps.diaconn.packet.*
import info.nightscout.androidaps.events.EventPumpStatusChanged import info.nightscout.androidaps.events.EventPumpStatusChanged
import info.nightscout.androidaps.extensions.notify import info.nightscout.androidaps.extensions.notify
import info.nightscout.androidaps.extensions.waitMillis import info.nightscout.androidaps.extensions.waitMillis
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag import info.nightscout.shared.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.interfaces.ResourceHelper
import java.util.* import java.util.*
import java.util.concurrent.ScheduledFuture import java.util.concurrent.ScheduledFuture
import javax.inject.Inject import javax.inject.Inject
@ -66,6 +70,11 @@ class BLECommonService @Inject internal constructor(
@Synchronized @Synchronized
fun connect(from: String, address: String?): Boolean { fun connect(from: String, address: String?): Boolean {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
ToastUtils.errorToast(context, context.getString(info.nightscout.androidaps.core.R.string.needconnectpermission))
aapsLogger.error(LTag.PUMPBTCOMM, "missing permission: $from")
return false
}
aapsLogger.debug(LTag.PUMPBTCOMM, "Initializing Bluetooth ") aapsLogger.debug(LTag.PUMPBTCOMM, "Initializing Bluetooth ")
if (bluetoothAdapter == null) { if (bluetoothAdapter == null) {
aapsLogger.error("Unable to obtain a BluetoothAdapter.") aapsLogger.error("Unable to obtain a BluetoothAdapter.")
@ -98,6 +107,10 @@ class BLECommonService @Inject internal constructor(
@Synchronized @Synchronized
fun disconnect(from: String) { fun disconnect(from: String) {
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != PackageManager.PERMISSION_GRANTED) {
aapsLogger.error(LTag.PUMPBTCOMM, "missing permission: $from")
return
}
aapsLogger.debug(LTag.PUMPBTCOMM, "disconnect from: $from") aapsLogger.debug(LTag.PUMPBTCOMM, "disconnect from: $from")
// cancel previous scheduled disconnection to prevent closing upcoming connection // cancel previous scheduled disconnection to prevent closing upcoming connection
@ -117,6 +130,7 @@ class BLECommonService @Inject internal constructor(
SystemClock.sleep(2000) SystemClock.sleep(2000)
} }
@SuppressLint("MissingPermission")
@Synchronized @Synchronized
fun close() { fun close() {
aapsLogger.debug(LTag.PUMPBTCOMM, "BluetoothAdapter close") aapsLogger.debug(LTag.PUMPBTCOMM, "BluetoothAdapter close")
@ -159,6 +173,7 @@ class BLECommonService @Inject internal constructor(
} }
} }
@SuppressLint("MissingPermission")
@Synchronized @Synchronized
private fun writeCharacteristicNoResponse(characteristic: BluetoothGattCharacteristic, data: ByteArray) { private fun writeCharacteristicNoResponse(characteristic: BluetoothGattCharacteristic, data: ByteArray) {
Thread(Runnable { Thread(Runnable {
@ -197,6 +212,7 @@ class BLECommonService @Inject internal constructor(
return bluetoothGatt?.services return bluetoothGatt?.services
} }
@SuppressLint("MissingPermission")
@Synchronized @Synchronized
private fun findCharacteristic() { private fun findCharacteristic() {
val gattServices = getSupportedGattServices() ?: return val gattServices = getSupportedGattServices() ?: return
@ -222,6 +238,7 @@ class BLECommonService @Inject internal constructor(
} }
} }
@SuppressLint("MissingPermission")
@Synchronized @Synchronized
private fun onConnectionStateChangeSynchronized(gatt: BluetoothGatt, newState: Int) { private fun onConnectionStateChangeSynchronized(gatt: BluetoothGatt, newState: Int) {
aapsLogger.debug(LTag.PUMPBTCOMM, "onConnectionStateChange newState : $newState") aapsLogger.debug(LTag.PUMPBTCOMM, "onConnectionStateChange newState : $newState")

View file

@ -1,16 +1,19 @@
package info.nightscout.androidaps.plugins.pump.insight.connection_service; package info.nightscout.androidaps.plugins.pump.insight.connection_service;
import android.Manifest;
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager; import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket; import android.bluetooth.BluetoothSocket;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Binder; import android.os.Binder;
import android.os.IBinder; import android.os.IBinder;
import android.os.PowerManager; import android.os.PowerManager;
import androidx.annotation.Nullable; import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import org.spongycastle.crypto.InvalidCipherTextException; import org.spongycastle.crypto.InvalidCipherTextException;
@ -23,8 +26,6 @@ import javax.inject.Inject;
import dagger.android.DaggerService; import dagger.android.DaggerService;
import info.nightscout.androidaps.insight.R; import info.nightscout.androidaps.insight.R;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.AppLayerMessage; import info.nightscout.androidaps.plugins.pump.insight.app_layer.AppLayerMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.ReadParameterBlockMessage; import info.nightscout.androidaps.plugins.pump.insight.app_layer.ReadParameterBlockMessage;
import info.nightscout.androidaps.plugins.pump.insight.app_layer.configuration.CloseConfigurationWriteSessionMessage; import info.nightscout.androidaps.plugins.pump.insight.app_layer.configuration.CloseConfigurationWriteSessionMessage;
@ -87,6 +88,8 @@ import info.nightscout.androidaps.plugins.pump.insight.utils.PairingDataStorage;
import info.nightscout.androidaps.plugins.pump.insight.utils.crypto.Cryptograph; import info.nightscout.androidaps.plugins.pump.insight.utils.crypto.Cryptograph;
import info.nightscout.androidaps.plugins.pump.insight.utils.crypto.DerivedKeys; import info.nightscout.androidaps.plugins.pump.insight.utils.crypto.DerivedKeys;
import info.nightscout.androidaps.plugins.pump.insight.utils.crypto.KeyPair; import info.nightscout.androidaps.plugins.pump.insight.utils.crypto.KeyPair;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
import info.nightscout.shared.sharedPreferences.SP; import info.nightscout.shared.sharedPreferences.SP;
public class InsightConnectionService extends DaggerService implements ConnectionEstablisher.Callback, InputStreamReader.Callback, OutputStreamWriter.Callback { public class InsightConnectionService extends DaggerService implements ConnectionEstablisher.Callback, InputStreamReader.Callback, OutputStreamWriter.Callback {
@ -108,7 +111,7 @@ public class InsightConnectionService extends DaggerService implements Connectio
private DelayedActionThread disconnectTimer; private DelayedActionThread disconnectTimer;
private DelayedActionThread recoveryTimer; private DelayedActionThread recoveryTimer;
private DelayedActionThread timeoutTimer; private DelayedActionThread timeoutTimer;
private BluetoothAdapter bluetoothAdapter; @Nullable private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice; private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket; private BluetoothSocket bluetoothSocket;
private ConnectionEstablisher connectionEstablisher; private ConnectionEstablisher connectionEstablisher;
@ -258,10 +261,12 @@ public class InsightConnectionService extends DaggerService implements Connectio
@Override @Override
public synchronized void onCreate() { public synchronized void onCreate() {
super.onCreate(); super.onCreate();
bluetoothAdapter = ((BluetoothManager)getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter(); if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
pairingDataStorage = new PairingDataStorage(this); bluetoothAdapter = ((BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
state = pairingDataStorage.isPaired() ? InsightState.DISCONNECTED : InsightState.NOT_PAIRED; pairingDataStorage = new PairingDataStorage(this);
wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:InsightConnectionService"); state = pairingDataStorage.isPaired() ? InsightState.DISCONNECTED : InsightState.NOT_PAIRED;
wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:InsightConnectionService");
}
} }
private void setState(InsightState state) { private void setState(InsightState state) {
@ -426,6 +431,7 @@ public class InsightConnectionService extends DaggerService implements Connectio
} }
private synchronized void connect() { private synchronized void connect() {
if (bluetoothAdapter == null) return;
if (bluetoothDevice == null) if (bluetoothDevice == null)
bluetoothDevice = bluetoothAdapter.getRemoteDevice(pairingDataStorage.getMacAddress()); bluetoothDevice = bluetoothAdapter.getRemoteDevice(pairingDataStorage.getMacAddress());
setState(InsightState.CONNECTING); setState(InsightState.CONNECTING);

View file

@ -133,7 +133,7 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
aapsLogger.debug(TAG, "Device can be detected near, so trying to remove bond if possible.") aapsLogger.debug(TAG, "Device can be detected near, so trying to remove bond if possible.")
bleSelector.removeDevice(bluetoothDevice!!) bleSelector.removeDevice(bluetoothDevice!!)
} else { } else {
val remoteDevice = bluetoothAdapter!!.getRemoteDevice(deviceAddress) val remoteDevice = bluetoothAdapter?.getRemoteDevice(deviceAddress)
if (remoteDevice != null) { if (remoteDevice != null) {
bleSelector.removeDevice(remoteDevice) bleSelector.removeDevice(remoteDevice)
} }
@ -184,7 +184,7 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
} }
private fun prepareForScanning() { private fun prepareForScanning() {
bleScanner = bluetoothAdapter!!.bluetoothLeScanner bleScanner = bluetoothAdapter?.bluetoothLeScanner
settings = bleSelector.getScanSettings() settings = bleSelector.getScanSettings()
filters = bleSelector.getScanFilters() filters = bleSelector.getScanFilters()
} }
@ -243,7 +243,7 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
binding.pumpBleConfigButtonScanStop.visibility = View.VISIBLE binding.pumpBleConfigButtonScanStop.visibility = View.VISIBLE
} }
scanning = true scanning = true
bleScanner!!.startScan(filters, settings, bleScanCallback) bleScanner?.startScan(filters, settings, bleScanCallback)
aapsLogger.debug(LTag.PUMPBTCOMM, "startLeDeviceScan: Scanning Start") aapsLogger.debug(LTag.PUMPBTCOMM, "startLeDeviceScan: Scanning Start")
bleSelector.onStartLeDeviceScan(this@PumpBLEConfigActivity) bleSelector.onStartLeDeviceScan(this@PumpBLEConfigActivity)
} }
@ -251,7 +251,7 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
private fun stopLeDeviceScan(manualStop: Boolean) { private fun stopLeDeviceScan(manualStop: Boolean) {
if (scanning) { if (scanning) {
scanning = false scanning = false
bleScanner!!.stopScan(bleScanCallback) bleScanner?.stopScan(bleScanCallback)
aapsLogger.debug(LTag.PUMPBTCOMM, "stopLeDeviceScan: Scanning Stop") aapsLogger.debug(LTag.PUMPBTCOMM, "stopLeDeviceScan: Scanning Stop")
bleSelector.onStopLeDeviceScan(this@PumpBLEConfigActivity) bleSelector.onStopLeDeviceScan(this@PumpBLEConfigActivity)
handler.removeCallbacks(stopScanAfterTimeoutRunnable) handler.removeCallbacks(stopScanAfterTimeoutRunnable)
@ -320,8 +320,8 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
if (currentlySelectedAddress == device.address) { if (currentlySelectedAddress == device.address) {
deviceName += " (" + resources.getString(R.string.ble_config_scan_selected) + ")" deviceName += " (" + resources.getString(R.string.ble_config_scan_selected) + ")"
} }
holder.deviceName!!.text = deviceName holder.deviceName?.text = deviceName
holder.deviceAddress!!.text = device.address holder.deviceAddress?.text = device.address
return v!! return v!!
} }
} }

View file

@ -1,5 +1,6 @@
package info.nightscout.androidaps.plugins.pump.common.dialog package info.nightscout.androidaps.plugins.pump.common.dialog
import android.Manifest
import android.annotation.SuppressLint import android.annotation.SuppressLint
import android.bluetooth.BluetoothAdapter import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothDevice import android.bluetooth.BluetoothDevice
@ -10,6 +11,7 @@ import android.bluetooth.le.ScanFilter
import android.bluetooth.le.ScanResult import android.bluetooth.le.ScanResult
import android.bluetooth.le.ScanSettings import android.bluetooth.le.ScanSettings
import android.content.Context import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle import android.os.Bundle
import android.os.Handler import android.os.Handler
import android.os.HandlerThread import android.os.HandlerThread
@ -22,8 +24,10 @@ import android.widget.AdapterView.OnItemClickListener
import android.widget.BaseAdapter import android.widget.BaseAdapter
import android.widget.TextView import android.widget.TextView
import android.widget.Toast import android.widget.Toast
import androidx.core.app.ActivityCompat
import dagger.android.support.DaggerAppCompatActivity import dagger.android.support.DaggerAppCompatActivity
import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.ActivePlugin
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck import info.nightscout.androidaps.plugins.pump.common.ble.BlePreCheck
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.R import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.R
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.RileyLinkConst
@ -32,7 +36,6 @@ import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.ble.data.Gatt
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileyLinkBleConfigActivityBinding import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.databinding.RileyLinkBleConfigActivityBinding
import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice import info.nightscout.androidaps.plugins.pump.common.hw.rileylink.defs.RileyLinkPumpDevice
import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.utils.alertDialogs.OKDialog
import info.nightscout.androidaps.interfaces.ResourceHelper
import info.nightscout.shared.logging.AAPSLogger import info.nightscout.shared.logging.AAPSLogger
import info.nightscout.shared.logging.LTag import info.nightscout.shared.logging.LTag
import info.nightscout.shared.sharedPreferences.SP import info.nightscout.shared.sharedPreferences.SP
@ -225,16 +228,20 @@ class RileyLinkBLEConfigActivity : DaggerAppCompatActivity() {
binding.rileyLinkBleConfigButtonScanStop.visibility = View.VISIBLE binding.rileyLinkBleConfigButtonScanStop.visibility = View.VISIBLE
} }
scanning = true scanning = true
bleScanner?.startScan(filters, settings, bleScanCallback) if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
aapsLogger.debug(LTag.PUMPBTCOMM, "startLeDeviceScan: Scanning Start") bleScanner?.startScan(filters, settings, bleScanCallback)
Toast.makeText(this@RileyLinkBLEConfigActivity, R.string.riley_link_ble_config_scan_scanning, Toast.LENGTH_SHORT).show() aapsLogger.debug(LTag.PUMPBTCOMM, "startLeDeviceScan: Scanning Start")
Toast.makeText(this@RileyLinkBLEConfigActivity, R.string.riley_link_ble_config_scan_scanning, Toast.LENGTH_SHORT).show()
}
} }
private fun stopLeDeviceScan() { private fun stopLeDeviceScan() {
if (scanning) { if (scanning) {
scanning = false scanning = false
if (bluetoothAdapter?.isEnabled == true && bluetoothAdapter?.state == BluetoothAdapter.STATE_ON) if (bluetoothAdapter?.isEnabled == true && bluetoothAdapter?.state == BluetoothAdapter.STATE_ON)
bleScanner?.stopScan(bleScanCallback) if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_SCAN) == PackageManager.PERMISSION_GRANTED) {
bleScanner?.stopScan(bleScanCallback)
}
aapsLogger.debug(LTag.PUMPBTCOMM, "stopLeDeviceScan: Scanning Stop") aapsLogger.debug(LTag.PUMPBTCOMM, "stopLeDeviceScan: Scanning Stop")
Toast.makeText(this, R.string.riley_link_ble_config_scan_finished, Toast.LENGTH_SHORT).show() Toast.makeText(this, R.string.riley_link_ble_config_scan_finished, Toast.LENGTH_SHORT).show()
handler.removeCallbacks(stopScanAfterTimeoutRunnable) handler.removeCallbacks(stopScanAfterTimeoutRunnable)
@ -268,7 +275,7 @@ class RileyLinkBLEConfigActivity : DaggerAppCompatActivity() {
override fun getItem(i: Int): Any = leDevices[i] override fun getItem(i: Int): Any = leDevices[i]
override fun getItemId(i: Int): Long = i.toLong() override fun getItemId(i: Int): Long = i.toLong()
@SuppressLint("InflateParams") @SuppressLint("InflateParams", "MissingPermission")
override fun getView(i: Int, v: View?, viewGroup: ViewGroup): View { override fun getView(i: Int, v: View?, viewGroup: ViewGroup): View {
var view = v var view = v
val viewHolder: ViewHolder val viewHolder: ViewHolder