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="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="needconnectpermission">Application needs bluetooth permission</string>
<string name="request">Request</string>
<string name="open_navigation">Open navigation</string>
<string name="close_navigation">Close navigation</string>

View file

@ -1,8 +1,11 @@
package info.nightscout.androidaps.plugins.general.automation.triggers
import android.Manifest
import android.bluetooth.BluetoothManager
import android.content.Context
import android.content.pm.PackageManager
import android.widget.LinearLayout
import androidx.core.app.ActivityCompat
import com.google.common.base.Optional
import dagger.android.HasAndroidInjector
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.StaticLabel
import info.nightscout.androidaps.utils.JsonHelper
import info.nightscout.androidaps.utils.ToastUtils
import info.nightscout.shared.logging.LTag
import org.json.JSONObject
import java.util.*
import javax.inject.Inject
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
private fun devicesPaired(): 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
}

View file

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

View file

@ -43,11 +43,10 @@ class BlePreCheck @Inject constructor(
}
// change after SDK = 31+
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
if (ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH_CONNECT") != PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(context, "android.permission.BLUETOOTH_SCAN") != PackageManager.PERMISSION_GRANTED
if (ContextCompat.checkSelfPermission(context, Manifest.permission.BLUETOOTH_CONNECT) != 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("android.permission.BLUETOOTH_SCAN", "android.permission.BLUETOOTH_CONNECT"), PERMISSION_REQUEST_BLUETOOTH)
ActivityCompat.requestPermissions(activity, arrayOf(Manifest.permission.BLUETOOTH_SCAN, Manifest.permission.BLUETOOTH_CONNECT), PERMISSION_REQUEST_BLUETOOTH)
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_error">Error during last Autotune run</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">
<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;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.IBinder;
import android.os.SystemClock;
import androidx.core.app.ActivityCompat;
import java.io.IOException;
import java.util.Set;
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.Profile;
import info.nightscout.androidaps.interfaces.PumpSync;
import info.nightscout.shared.logging.AAPSLogger;
import info.nightscout.shared.logging.LTag;
import info.nightscout.androidaps.interfaces.ResourceHelper;
import info.nightscout.androidaps.plugins.bus.RxBus;
import info.nightscout.androidaps.plugins.general.overview.events.EventNewNotification;
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.FabricPrivacy;
import info.nightscout.androidaps.utils.ToastUtils;
import info.nightscout.androidaps.interfaces.ResourceHelper;
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 io.reactivex.rxjava3.disposables.CompositeDisposable;
@ -191,30 +195,32 @@ public abstract class AbstractDanaRExecutionService extends DaggerService {
protected void getBTSocketForSelectedPump() {
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) {
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bluetoothAdapter != null) {
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
if (bondedDevices != null)
for (BluetoothDevice device : bondedDevices) {
if (mDevName.equals(device.getName())) {
mBTDevice = device;
try {
mRfcommSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException e) {
aapsLogger.error("Error creating socket: ", e);
if (bondedDevices != null)
for (BluetoothDevice device : bondedDevices) {
if (mDevName.equals(device.getName())) {
mBTDevice = device;
try {
mRfcommSocket = mBTDevice.createRfcommSocketToServiceRecord(SPP_UUID);
} catch (IOException 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 {
ToastUtils.INSTANCE.showToastInUiThread(context.getApplicationContext(),
rh.gs(R.string.nobtadapter));
}
if (mBTDevice == null) {
ToastUtils.INSTANCE.showToastInUiThread(context.getApplicationContext(),
rh.gs(R.string.devicenotfound));
ToastUtils.INSTANCE.errorToast(context, context.getString(R.string.needconnectpermission));
}
}

View file

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

View file

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

View file

@ -8,7 +8,7 @@
android:title="@string/danar_pump_settings"
app:initialExpandedChildrenCount="0">
<info.nightscout.androidaps.danar.BluetoothDevicePreference
<info.nightscout.androidaps.utils.ui.BluetoothDevicePreference
android:dialogTitle="@string/danar_bt_name_title"
android:key="@string/key_danar_bt_name"
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_SCAN" />
<application>
<activity
android:name="info.nightscout.androidaps.danars.activities.BLEScanActivity"

View file

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

View file

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

View file

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

View file

@ -1,9 +1,12 @@
package info.nightscout.androidaps.diaconn.service
import android.Manifest
import android.annotation.SuppressLint
import android.bluetooth.*
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.SystemClock
import androidx.core.app.ActivityCompat
import dagger.android.HasAndroidInjector
import info.nightscout.androidaps.activities.ErrorHelperActivity
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.extensions.notify
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.LTag
import info.nightscout.androidaps.plugins.bus.RxBus
import info.nightscout.androidaps.interfaces.ResourceHelper
import java.util.*
import java.util.concurrent.ScheduledFuture
import javax.inject.Inject
@ -66,6 +70,11 @@ class BLECommonService @Inject internal constructor(
@Synchronized
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 ")
if (bluetoothAdapter == null) {
aapsLogger.error("Unable to obtain a BluetoothAdapter.")
@ -98,6 +107,10 @@ class BLECommonService @Inject internal constructor(
@Synchronized
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")
// cancel previous scheduled disconnection to prevent closing upcoming connection
@ -117,6 +130,7 @@ class BLECommonService @Inject internal constructor(
SystemClock.sleep(2000)
}
@SuppressLint("MissingPermission")
@Synchronized
fun close() {
aapsLogger.debug(LTag.PUMPBTCOMM, "BluetoothAdapter close")
@ -159,6 +173,7 @@ class BLECommonService @Inject internal constructor(
}
}
@SuppressLint("MissingPermission")
@Synchronized
private fun writeCharacteristicNoResponse(characteristic: BluetoothGattCharacteristic, data: ByteArray) {
Thread(Runnable {
@ -197,6 +212,7 @@ class BLECommonService @Inject internal constructor(
return bluetoothGatt?.services
}
@SuppressLint("MissingPermission")
@Synchronized
private fun findCharacteristic() {
val gattServices = getSupportedGattServices() ?: return
@ -222,6 +238,7 @@ class BLECommonService @Inject internal constructor(
}
}
@SuppressLint("MissingPermission")
@Synchronized
private fun onConnectionStateChangeSynchronized(gatt: BluetoothGatt, newState: Int) {
aapsLogger.debug(LTag.PUMPBTCOMM, "onConnectionStateChange newState : $newState")

View file

@ -1,16 +1,19 @@
package info.nightscout.androidaps.plugins.pump.insight.connection_service;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Binder;
import android.os.IBinder;
import android.os.PowerManager;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import org.spongycastle.crypto.InvalidCipherTextException;
@ -23,8 +26,6 @@ import javax.inject.Inject;
import dagger.android.DaggerService;
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.ReadParameterBlockMessage;
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.DerivedKeys;
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;
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 recoveryTimer;
private DelayedActionThread timeoutTimer;
private BluetoothAdapter bluetoothAdapter;
@Nullable private BluetoothAdapter bluetoothAdapter;
private BluetoothDevice bluetoothDevice;
private BluetoothSocket bluetoothSocket;
private ConnectionEstablisher connectionEstablisher;
@ -258,10 +261,12 @@ public class InsightConnectionService extends DaggerService implements Connectio
@Override
public synchronized void onCreate() {
super.onCreate();
bluetoothAdapter = ((BluetoothManager)getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
pairingDataStorage = new PairingDataStorage(this);
state = pairingDataStorage.isPaired() ? InsightState.DISCONNECTED : InsightState.NOT_PAIRED;
wakeLock = ((PowerManager) getSystemService(POWER_SERVICE)).newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "AndroidAPS:InsightConnectionService");
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.BLUETOOTH_CONNECT) == PackageManager.PERMISSION_GRANTED) {
bluetoothAdapter = ((BluetoothManager) getApplicationContext().getSystemService(Context.BLUETOOTH_SERVICE)).getAdapter();
pairingDataStorage = new PairingDataStorage(this);
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) {
@ -426,6 +431,7 @@ public class InsightConnectionService extends DaggerService implements Connectio
}
private synchronized void connect() {
if (bluetoothAdapter == null) return;
if (bluetoothDevice == null)
bluetoothDevice = bluetoothAdapter.getRemoteDevice(pairingDataStorage.getMacAddress());
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.")
bleSelector.removeDevice(bluetoothDevice!!)
} else {
val remoteDevice = bluetoothAdapter!!.getRemoteDevice(deviceAddress)
val remoteDevice = bluetoothAdapter?.getRemoteDevice(deviceAddress)
if (remoteDevice != null) {
bleSelector.removeDevice(remoteDevice)
}
@ -184,7 +184,7 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
}
private fun prepareForScanning() {
bleScanner = bluetoothAdapter!!.bluetoothLeScanner
bleScanner = bluetoothAdapter?.bluetoothLeScanner
settings = bleSelector.getScanSettings()
filters = bleSelector.getScanFilters()
}
@ -243,7 +243,7 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
binding.pumpBleConfigButtonScanStop.visibility = View.VISIBLE
}
scanning = true
bleScanner!!.startScan(filters, settings, bleScanCallback)
bleScanner?.startScan(filters, settings, bleScanCallback)
aapsLogger.debug(LTag.PUMPBTCOMM, "startLeDeviceScan: Scanning Start")
bleSelector.onStartLeDeviceScan(this@PumpBLEConfigActivity)
}
@ -251,7 +251,7 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
private fun stopLeDeviceScan(manualStop: Boolean) {
if (scanning) {
scanning = false
bleScanner!!.stopScan(bleScanCallback)
bleScanner?.stopScan(bleScanCallback)
aapsLogger.debug(LTag.PUMPBTCOMM, "stopLeDeviceScan: Scanning Stop")
bleSelector.onStopLeDeviceScan(this@PumpBLEConfigActivity)
handler.removeCallbacks(stopScanAfterTimeoutRunnable)
@ -320,8 +320,8 @@ class PumpBLEConfigActivity : DaggerAppCompatActivity() {
if (currentlySelectedAddress == device.address) {
deviceName += " (" + resources.getString(R.string.ble_config_scan_selected) + ")"
}
holder.deviceName!!.text = deviceName
holder.deviceAddress!!.text = device.address
holder.deviceName?.text = deviceName
holder.deviceAddress?.text = device.address
return v!!
}
}

View file

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