This commit is contained in:
Andrei Vereha 2021-03-28 23:15:42 +02:00
parent 96b1b177a6
commit b630c4d21a
16 changed files with 96 additions and 64 deletions

View file

@ -46,11 +46,13 @@ data class Id(val address: ByteArray) {
companion object {
private const val PERIPHERAL_NODE_INDEX = 1 // TODO: understand the meaning of this value. It comes from preferences
private const val PERIPHERAL_NODE_INDEX =
1 // TODO: understand the meaning of this value. It comes from preferences
fun fromInt(v: Int): Id {
return Id(ByteBuffer.allocate(4).putInt(v).array())
}
fun fromLong(v: Long): Id {
return Id(ByteBuffer.allocate(8).putLong(v).array().copyOfRange(4, 8))
}

View file

@ -3,12 +3,10 @@ package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm
import android.bluetooth.BluetoothAdapter
import android.bluetooth.BluetoothManager
import android.content.Context
import android.os.Message
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.*
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair.LTKExchanger
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.scan.PodScanner
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.session.*
@ -18,7 +16,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.b
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state.OmnipodDashPodStateManager
import info.nightscout.androidaps.utils.extensions.toHex
import io.reactivex.Observable
import java.util.concurrent.TimeoutException
import java.util.concurrent.atomic.AtomicBoolean
import javax.inject.Inject
import javax.inject.Singleton
@ -29,7 +26,8 @@ class OmnipodDashBleManagerImpl @Inject constructor(
private val aapsLogger: AAPSLogger,
private val podState: OmnipodDashPodStateManager
) : OmnipodDashBleManager {
private val busy = AtomicBoolean(false);
private val busy = AtomicBoolean(false)
private val bluetoothManager: BluetoothManager =
context.getSystemService(Context.BLUETOOTH_SERVICE) as BluetoothManager
private val bluetoothAdapter: BluetoothAdapter = bluetoothManager.adapter

View file

@ -112,10 +112,12 @@ class BleCommCallbacks(
val writeConfirmation = when {
uuid == null || value == null ->
WriteConfirmationError("onWrite received Null: UUID=$uuid, value=${value.toHex()} status=$status")
status == BluetoothGatt.GATT_SUCCESS -> {
aapsLogger.debug(LTag.PUMPBTCOMM, "OnWrite value " + value.toHex())
WriteConfirmationSuccess(uuid.toString(), value)
}
else -> WriteConfirmationError("onDescriptorWrite status is not success: $status")
}

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.command
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType
import info.nightscout.androidaps.utils.extensions.toHex
import java.nio.ByteBuffer
@ -16,6 +15,7 @@ object BleCommandFail : BleCommand(BleCommandType.FAIL)
data class BleCommandNack(val idx: Byte) : BleCommand(BleCommandType.NACK, byteArrayOf(idx)) {
companion object {
fun parse(payload: ByteArray): BleCommand {
if (payload.size < 2) {
return BleCommandIncorrect("Incorrect NACK payload", payload)
@ -64,6 +64,7 @@ sealed class BleCommand(val data: ByteArray) {
}
companion object {
fun parse(payload: ByteArray): BleCommand {
if (payload.isEmpty()) {
return BleCommandIncorrect("Incorrect command: empty payload", payload)

View file

@ -1,3 +1,3 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions
class BusyException(): Exception("Bluetooth busy")
class BusyException : Exception("Bluetooth busy")

View file

@ -1,4 +1,3 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions
class CouldNotSendCommandException (val msg: String="Could not send command") : Exception(msg){
}
class CouldNotSendCommandException(val msg: String = "Could not send command") : Exception(msg)

View file

@ -8,20 +8,17 @@ import android.bluetooth.BluetoothGattDescriptor
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.BleCommCallbacks
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.WriteConfirmation
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.WriteConfirmationError
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.callbacks.WriteConfirmationSuccess
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptions.*
import info.nightscout.androidaps.utils.extensions.toHex
import java.util.concurrent.BlockingQueue
import java.util.concurrent.TimeUnit
import java.util.concurrent.TimeoutException
sealed class BleReceiveResult
data class BleReceivePayload(val payload: ByteArray) : BleReceiveResult()
data class BleReceiveError(val msg: String, val cause: Throwable? = null) : BleReceiveResult()
sealed class BleSendResult
object BleSendSuccess : BleSendResult()
@ -71,7 +68,8 @@ abstract class BleIO(
return when (val confirmation = bleCommCallbacks.confirmWrite(
payload, type.value,
DEFAULT_IO_TIMEOUT_MS)){
DEFAULT_IO_TIMEOUT_MS
)) {
is WriteConfirmationError ->
BleSendErrorConfirming(confirmation.msg)
is WriteConfirmationSuccess ->
@ -111,9 +109,11 @@ abstract class BleIO(
if (!wrote) {
throw ConnectException("Could not enable indications on descriptor")
}
val confirmation = bleCommCallbacks.confirmWrite(BluetoothGattDescriptor.ENABLE_INDICATION_VALUE,
val confirmation = bleCommCallbacks.confirmWrite(
BluetoothGattDescriptor.ENABLE_INDICATION_VALUE,
descriptor.uuid.toString(),
DEFAULT_IO_TIMEOUT_MS)
DEFAULT_IO_TIMEOUT_MS
)
return when (confirmation) {
is WriteConfirmationError ->
throw ConnectException(confirmation.msg)

View file

@ -29,6 +29,7 @@ class CmdBleIO(
bleCommCallbacks,
CharacteristicType.CMD
) {
init {
}
@ -38,7 +39,6 @@ class CmdBleIO(
fun hello() = sendAndConfirmPacket(BleCommandHello(OmnipodDashBleManagerImpl.CONTROLLER_ID).data)
fun expectCommandType(expected: BleCommand, timeoutMs: Long = DEFAULT_IO_TIMEOUT_MS): BleConfirmResult {
return when (val actual = receivePacket(timeoutMs)) {
is BleReceiveError -> BleConfirmError(actual.toString())

View file

@ -4,6 +4,7 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.
import java.nio.ByteBuffer
sealed class BlePacket {
abstract val payload: ByteArray
abstract fun toByteArray(): ByteArray
@ -173,7 +174,8 @@ data class LastBlePacket(
data class LastOptionalPlusOneBlePacket(
val index: Byte,
override val payload: ByteArray,
val size: Byte) : BlePacket() {
val size: Byte
) : BlePacket() {
override fun toByteArray(): ByteArray {
return byteArrayOf(index, size) + payload + ByteArray(MAX_SIZE - payload.size - 2)

View file

@ -1,6 +1,5 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair
import android.app.Notification
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id
@ -12,7 +11,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.Rand
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.util.X25519KeyGenerator
import info.nightscout.androidaps.utils.extensions.hexStringToByteArray
import info.nightscout.androidaps.utils.extensions.toHex
import info.nightscout.androidaps.utils.extensions.waitMillis
internal class LTKExchanger(
private val aapsLogger: AAPSLogger,

View file

@ -5,7 +5,6 @@ import android.bluetooth.BluetoothGatt
import android.bluetooth.BluetoothManager
import android.bluetooth.BluetoothProfile
import android.content.Context
import com.j256.ormlite.stmt.query.Not
import info.nightscout.androidaps.logging.AAPSLogger
import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.pump.omnipod.dash.BuildConfig
@ -21,7 +20,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.DataB
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.IncomingPackets
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.message.MessageIO
import info.nightscout.androidaps.utils.extensions.toHex
import info.nightscout.androidaps.utils.extensions.wait
sealed class ConnectionState
@ -50,10 +48,14 @@ class Connection(val podDevice: BluetoothDevice, private val aapsLogger: AAPSLog
private val discoverer = ServiceDiscoverer(aapsLogger, gattConnection, bleCommCallbacks)
private val discoveredCharacteristics = discoverer.discoverServices()
private val cmdBleIO = CmdBleIO(aapsLogger, discoveredCharacteristics[CharacteristicType.CMD]!!, incomingPackets
.cmdQueue, gattConnection, bleCommCallbacks)
private val dataBleIO = DataBleIO(aapsLogger, discoveredCharacteristics[CharacteristicType.DATA]!!, incomingPackets
.dataQueue, gattConnection, bleCommCallbacks)
private val cmdBleIO = CmdBleIO(
aapsLogger, discoveredCharacteristics[CharacteristicType.CMD]!!, incomingPackets
.cmdQueue, gattConnection, bleCommCallbacks
)
private val dataBleIO = DataBleIO(
aapsLogger, discoveredCharacteristics[CharacteristicType.DATA]!!, incomingPackets
.dataQueue, gattConnection, bleCommCallbacks
)
val msgIO = MessageIO(aapsLogger, cmdBleIO, dataBleIO)
var session: Session? = null
@ -82,7 +84,7 @@ class Connection(val podDevice: BluetoothDevice, private val aapsLogger: AAPSLog
gattConnection.disconnect()
}
fun waitForConnection(): ConnectionState {
private fun waitForConnection(): ConnectionState {
try {
bleCommCallbacks.waitForConnection(CONNECT_TIMEOUT_MS)
} catch (e: InterruptedException) {
@ -116,6 +118,7 @@ class Connection(val podDevice: BluetoothDevice, private val aapsLogger: AAPSLog
)
session = Session(aapsLogger, msgIO, myId, podID, sessionKeys = keys, enDecrypt = enDecrypt)
}
companion object {
private const val CONNECT_TIMEOUT_MS = 7000

View file

@ -50,7 +50,14 @@ sealed class EapAkaAttribute {
EapAkaAttributeType.AT_RAND ->
ret.add(EapAkaAttributeRand.parse(tail.copyOfRange(2, EapAkaAttributeRand.SIZE)))
EapAkaAttributeType.AT_CLIENT_ERROR_CODE ->
ret.add(EapAkaAttributeClientErrorCode.parse(tail.copyOfRange(2, EapAkaAttributeClientErrorCode.SIZE)))
ret.add(
EapAkaAttributeClientErrorCode.parse(
tail.copyOfRange(
2,
EapAkaAttributeClientErrorCode.SIZE
)
)
)
}
tail = tail.copyOfRange(size, tail.size)
}
@ -70,12 +77,14 @@ data class EapAkaAttributeRand(val payload: ByteArray) : EapAkaAttribute() {
}
companion object {
fun parse(payload: ByteArray): EapAkaAttribute {
if (payload.size < 2 + 16) {
throw MessageIOException("Could not parse RAND attribute: ${payload.toHex()}")
}
return EapAkaAttributeRand(payload.copyOfRange(2, 2 + 16))
}
const val SIZE = 20 // type, size, 2 reserved bytes, payload=16
}
}
@ -110,7 +119,12 @@ data class EapAkaAttributeRes(val payload: ByteArray) : EapAkaAttribute() {
}
override fun toByteArray(): ByteArray {
return byteArrayOf(EapAkaAttributeType.AT_RES.type, (SIZE / SIZE_MULTIPLIER).toByte(), 0, PAYLOAD_SIZE_BITS) + payload
return byteArrayOf(
EapAkaAttributeType.AT_RES.type,
(SIZE / SIZE_MULTIPLIER).toByte(),
0,
PAYLOAD_SIZE_BITS
) + payload
}
companion object {
@ -145,6 +159,7 @@ data class EapAkaAttributeCustomIV(val payload: ByteArray) : EapAkaAttribute() {
}
return EapAkaAttributeCustomIV(payload.copyOfRange(2, 2 + 4))
}
const val SIZE = 8 // type, size, 2 reserved bytes, payload=4
}
}
@ -156,7 +171,12 @@ data class EapAkaAttributeClientErrorCode(val payload: ByteArray) : EapAkaAttrib
}
override fun toByteArray(): ByteArray {
return byteArrayOf(EapAkaAttributeType.AT_CLIENT_ERROR_CODE.type, (SIZE / SIZE_MULTIPLIER).toByte(), 0, 0) + payload
return byteArrayOf(
EapAkaAttributeType.AT_CLIENT_ERROR_CODE.type,
(SIZE / SIZE_MULTIPLIER).toByte(),
0,
0
) + payload
}
companion object {

View file

@ -23,7 +23,6 @@ data class CommandReceiveSuccess(val result: Response): CommandReceiveResult()
data class CommandReceiveError(val msg: String) : CommandReceiveResult()
data class CommandAckError(val result: Response, val msg: String) : CommandReceiveResult()
class Session(
private val aapsLogger: AAPSLogger,
private val msgIO: MessageIO,
@ -45,10 +44,12 @@ class Session(
when (val sendResult = msgIO.sendMessage(msg)) {
is MessageSendSuccess ->
return CommandSendSuccess
is MessageSendErrorConfirming -> {
possiblyUnconfirmedCommand = true
aapsLogger.debug(LTag.PUMPBTCOMM, "Error confirming command: $sendResult")
}
is MessageSendErrorSending ->
aapsLogger.debug(LTag.PUMPBTCOMM, "Error sending command: $sendResult")
}
@ -89,7 +90,6 @@ class Session(
return CommandReceiveSuccess(response)
}
private fun parseResponse(decrypted: MessagePacket): Response {
val payload = parseKeys(arrayOf(RESPONSE_PREFIX), decrypted.payload)[0]

View file

@ -90,13 +90,20 @@ class SessionEstablisher(
private fun processChallengeResponse(challengeResponse: MessagePacket) {
val eapMsg = EapMessage.parse(aapsLogger, challengeResponse.payload)
if (eapMsg.identifier != identifier) {
aapsLogger.debug(LTag.PUMPBTCOMM, "EAP-AKA: got incorrect identifier ${eapMsg.identifier} expected: $identifier")
aapsLogger.debug(
LTag.PUMPBTCOMM,
"EAP-AKA: got incorrect identifier ${eapMsg.identifier} expected: $identifier"
)
throw SessionEstablishmentException("Received incorrect EAP identifier: ${eapMsg.identifier}")
}
if (eapMsg.attributes.size != 2) {
aapsLogger.debug(LTag.PUMPBTCOMM, "EAP-AKA: got message: $eapMsg")
if (eapMsg.attributes.size == 1 && eapMsg.attributes[0] is EapAkaAttributeClientErrorCode) {
throw SessionEstablishmentException("Received CLIENT_ERROR_CODE for EAP-AKA challenge: ${eapMsg.attributes[0].toByteArray().toHex()}")
throw SessionEstablishmentException(
"Received CLIENT_ERROR_CODE for EAP-AKA challenge: ${
eapMsg.attributes[0].toByteArray().toHex()
}"
)
}
throw SessionEstablishmentException("Expecting two attributes, got: ${eapMsg.attributes.size}")
}