Merge pull request #21 from 0pen-dash/andrei/activateNewPod

dash ble: add a separate method for activating a new pod
This commit is contained in:
Andrei Vereha 2021-03-14 15:41:27 +01:00 committed by GitHub
commit 3c3132ad17
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
14 changed files with 121 additions and 85 deletions

View file

@ -50,8 +50,12 @@ class OmnipodDashManagerImpl @Inject constructor(
private val observeConnectToPod: Observable<PodEvent>
get() = Observable.defer {
bleManager.connect()
} // TODO add retry
} // TODO are these reasonable values?
private val observePairNewPod: Observable<PodEvent>
get() = Observable.defer {
bleManager.pairNewPod()
}
private fun observeSendProgramBolusCommand(
units: Double,
@ -172,7 +176,7 @@ class OmnipodDashManagerImpl @Inject constructor(
override fun activatePodPart1(lowReservoirAlertTrigger: AlertTrigger.ReservoirVolumeTrigger?): Observable<PodEvent> {
return Observable.concat(
observePodReadyForActivationPart1,
observeConnectToPod,
observePairNewPod,
observeActivationPart1Commands(lowReservoirAlertTrigger)
).doOnComplete(ActivationProgressUpdater(ActivationProgress.PHASE_1_COMPLETED))
// TODO these would be common for any observable returned in a public function in this class
@ -407,15 +411,13 @@ class OmnipodDashManagerImpl @Inject constructor(
when (event) {
is PodEvent.AlreadyConnected -> {
podStateManager.bluetoothAddress = event.bluetoothAddress
podStateManager.uniqueId = event.uniqueId
}
is PodEvent.BluetoothConnected -> {
podStateManager.bluetoothAddress = event.address
podStateManager.bluetoothAddress = event.bluetoothAddress
}
is PodEvent.Connected -> {
podStateManager.uniqueId = event.uniqueId
}
is PodEvent.CommandSent -> {
@ -427,7 +429,11 @@ class OmnipodDashManagerImpl @Inject constructor(
handleResponse(event.response)
}
else -> {
is PodEvent.Paired -> {
podStateManager.uniqueId = event.uniqueId.toLong()
}
else -> {
// Do nothing
}
}

View file

@ -31,7 +31,7 @@ data class Id(val address: ByteArray) {
companion object {
private 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())

View file

@ -13,5 +13,7 @@ interface OmnipodDashBleManager {
fun connect(): Observable<PodEvent>
fun pairNewPod(): Observable<PodEvent>
fun disconnect()
}

View file

@ -47,6 +47,10 @@ class OmnipodDashBleManagerImpl @Inject constructor(
private var msgIO: MessageIO? = null
private var gatt: BluetoothGatt? = null
private var status: ConnectionStatus = ConnectionStatus.IDLE
private val myId = Id.fromInt(CONTROLLER_ID)
private val uniqueId = podState.uniqueId
private val podId = uniqueId?.let(Id::fromLong)
?: myId.increment() // pod not activated
@Throws(
FailedToConnectException::class,
@ -59,6 +63,7 @@ class OmnipodDashBleManagerImpl @Inject constructor(
DescriptorNotFoundException::class,
CouldNotConfirmDescriptorWriteException::class
)
private fun connect(podDevice: BluetoothDevice): BleIO {
val incomingPackets: Map<CharacteristicType, BlockingQueue<ByteArray>> =
mapOf(
@ -90,7 +95,6 @@ class OmnipodDashBleManagerImpl @Inject constructor(
val keys = sessionKeys
val mIO = msgIO
if (keys == null || mIO == null) {
// TODO handle reconnects
throw Exception("Not connected")
}
emitter.onNext(PodEvent.CommandSending(cmd))
@ -106,8 +110,8 @@ class OmnipodDashBleManagerImpl @Inject constructor(
val session = Session(
aapsLogger = aapsLogger,
msgIO = mIO,
myId = Id.fromInt(CONTROLLER_ID),
podId = Id.fromInt(CONTROLLER_ID).increment(),
myId = myId,
podId = podId,
sessionKeys = keys,
enDecrypt = enDecrypt
)
@ -142,76 +146,98 @@ class OmnipodDashBleManagerImpl @Inject constructor(
)
override fun connect(): Observable<PodEvent> = Observable.create { emitter ->
// TODO: when we are already connected,
// emit PodEvent.AlreadyConnected, complete the observable and return from this method
try {
if (podState.bluetoothAddress == null) {
aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation")
val podScanner = PodScanner(aapsLogger, bluetoothAdapter)
emitter.onNext(PodEvent.Scanning)
val podAddress = podScanner.scanForPod(
PodScanner.SCAN_FOR_SERVICE_UUID,
PodScanner.POD_ID_NOT_ACTIVATED
).scanResult.device.address
// For tests: this.podAddress = "B8:27:EB:1D:7E:BB";
podState.bluetoothAddress = podAddress
}
emitter.onNext(PodEvent.BluetoothConnecting)
val podAddress = podState.bluetoothAddress ?: throw FailedToConnectException("Lost connection")
val podAddress =
podState.bluetoothAddress
?: throw FailedToConnectException("Missing bluetoothAddress, activate the pod first")
// check if already connected
val podDevice = bluetoothAdapter.getRemoteDevice(podAddress)
val connectionState = bluetoothManager.getConnectionState(podDevice, BluetoothProfile.GATT)
aapsLogger.debug(LTag.PUMPBTCOMM, "GATT connection state: $connectionState")
emitter.onNext(PodEvent.BluetoothConnected(podAddress))
if (connectionState == BluetoothProfile.STATE_CONNECTED) {
podState.uniqueId ?: throw FailedToConnectException("Already connection and uniqueId is missing")
emitter.onNext(PodEvent.AlreadyConnected(podAddress, podState.uniqueId ?: 0))
emitter.onNext(PodEvent.AlreadyConnected(podAddress))
emitter.onComplete()
return@create
}
emitter.onNext(PodEvent.BluetoothConnecting)
if (msgIO != null) {
disconnect()
}
val bleIO = connect(podDevice)
val mIO = MessageIO(aapsLogger, bleIO)
val myId = Id.fromInt(CONTROLLER_ID)
val podId = myId.increment()
var msgSeq = 1.toByte()
val ltkExchanger = LTKExchanger(aapsLogger, mIO, myId, podId, Id.fromLong(PodScanner.POD_ID_NOT_ACTIVATED))
if (podState.ltk == null) {
emitter.onNext(PodEvent.Pairing)
val pairResult = ltkExchanger.negotiateLTK()
podState.ltk = pairResult.ltk
podState.uniqueId = podId.toLong()
msgSeq = pairResult.msgSeq
podState.eapAkaSequenceNumber = 1
if (BuildConfig.DEBUG) {
aapsLogger.info(LTag.PUMPCOMM, "Got LTK: ${pairResult.ltk.toHex()}")
}
}
val ltk: ByteArray = podState.ltk!!
msgIO = mIO
emitter.onNext(PodEvent.BluetoothConnected(podAddress))
emitter.onNext(PodEvent.EstablishingSession)
val eapSqn = podState.increaseEapAkaSequenceNumber()
val eapAkaExchanger = SessionEstablisher(aapsLogger, mIO, ltk, eapSqn, myId, podId, msgSeq)
val keys = eapAkaExchanger.negotiateSessionKeys()
podState.commitEapAkaSequenceNumber()
establishSession(1.toByte())
emitter.onNext(PodEvent.Connected)
if (BuildConfig.DEBUG) {
aapsLogger.info(LTag.PUMPCOMM, "CK: ${keys.ck.toHex()}")
aapsLogger.info(LTag.PUMPCOMM, "msgSequenceNumber: ${keys.msgSequenceNumber}")
aapsLogger.info(LTag.PUMPCOMM, "Nonce: ${keys.nonce}")
emitter.onComplete()
} catch (ex: Exception) {
disconnect()
emitter.tryOnError(ex)
}
}
private fun establishSession(msgSeq: Byte) {
val mIO = msgIO ?: throw FailedToConnectException("connection lost")
val ltk: ByteArray = podState.ltk ?: throw FailedToConnectException("Missing LTK, activate the pod first")
val uniqueId = podState.uniqueId
val podId = uniqueId?.let { Id.fromLong(uniqueId) }
?: myId.increment() // pod not activated
val eapSqn = podState.increaseEapAkaSequenceNumber()
val eapAkaExchanger = SessionEstablisher(aapsLogger, mIO, ltk, eapSqn, myId, podId, msgSeq)
val keys = eapAkaExchanger.negotiateSessionKeys()
podState.commitEapAkaSequenceNumber()
if (BuildConfig.DEBUG) {
aapsLogger.info(LTag.PUMPCOMM, "CK: ${keys.ck.toHex()}")
aapsLogger.info(LTag.PUMPCOMM, "msgSequenceNumber: ${keys.msgSequenceNumber}")
aapsLogger.info(LTag.PUMPCOMM, "Nonce: ${keys.nonce}")
}
sessionKeys = keys
}
override fun pairNewPod(): Observable<PodEvent> = Observable.create { emitter ->
try {
if (podState.ltk != null) {
emitter.onNext(PodEvent.AlreadyPaired)
emitter.onComplete()
return@create
}
sessionKeys = keys
aapsLogger.info(LTag.PUMPBTCOMM, "starting new pod activation")
emitter.onNext(PodEvent.Scanning)
val podScanner = PodScanner(aapsLogger, bluetoothAdapter)
val podAddress = podScanner.scanForPod(
PodScanner.SCAN_FOR_SERVICE_UUID,
PodScanner.POD_ID_NOT_ACTIVATED
).scanResult.device.address
podState.bluetoothAddress = podAddress
emitter.onNext(PodEvent.BluetoothConnecting)
val podDevice = bluetoothAdapter.getRemoteDevice(podAddress)
val bleIO = connect(podDevice)
val mIO = MessageIO(aapsLogger, bleIO)
msgIO = mIO
emitter.onNext(PodEvent.BluetoothConnected(podAddress))
emitter.onNext(PodEvent.Connected(podId.toLong()))
emitter.onNext(PodEvent.Pairing)
val ltkExchanger = LTKExchanger(aapsLogger, mIO, myId, podId, Id.fromLong(PodScanner.POD_ID_NOT_ACTIVATED))
val pairResult = ltkExchanger.negotiateLTK()
emitter.onNext(PodEvent.Paired(podId))
podState.updateFromPairing(podId, pairResult)
if (BuildConfig.DEBUG) {
aapsLogger.info(LTag.PUMPCOMM, "Got LTK: ${pairResult.ltk.toHex()}")
}
emitter.onNext(PodEvent.EstablishingSession)
establishSession(pairResult.msgSeq)
emitter.onNext(PodEvent.Connected)
emitter.onComplete()
} catch (ex: Exception) {
disconnect()

View file

@ -36,5 +36,4 @@ open class BleCommand(val data: ByteArray) {
override fun hashCode(): Int {
return data.contentHashCode()
}
}

View file

@ -123,6 +123,6 @@ class BleIO(
companion object {
private const val DEFAULT_IO_TIMEOUT_MS = 10000
private const val DEFAULT_IO_TIMEOUT_MS = 60000
}
}

View file

@ -8,7 +8,6 @@ import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.exceptio
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.BleIO
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.CharacteristicType
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.io.PayloadJoiner
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.CommandType
import info.nightscout.androidaps.utils.extensions.toHex
class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) {
@ -22,19 +21,12 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) {
return
}
throw UnexpectedCommandException(actual)
}
fun sendMessage(msg: MessagePacket):MessagePacket? {
fun sendMessage(msg: MessagePacket) {
bleIO.flushIncomingQueues()
bleIO.sendAndConfirmPacket(CharacteristicType.CMD, BleCommandRTS().data)
val expectCTS = bleIO.receivePacket(CharacteristicType.CMD)
if (expectCTS.isEmpty()) {
throw UnexpectedCommandException(BleCommand(expectCTS))
}
//if (expectCTS[0] == BleCommandType.RTS.value) {
//the pod is trying to send something, after we sent RTS, let's read it
//}
expectCommandType(BleCommand(expectCTS), BleCommandCTS())
val payload = msg.asByteArray()
aapsLogger.debug(LTag.PUMPBTCOMM, "Sending message: ${payload.toHex()}")
@ -48,11 +40,10 @@ class MessageIO(private val aapsLogger: AAPSLogger, private val bleIO: BleIO) {
val expectSuccess = bleIO.receivePacket(CharacteristicType.CMD)
expectCommandType(BleCommand(expectSuccess), BleCommandSuccess())
// TODO: handle NACKS/FAILS/etc
return null
}
// TODO: use higher timeout when receiving the first packet in a message
fun receiveMessage( firstCmd: ByteArray? = null): MessagePacket {
fun receiveMessage(firstCmd: ByteArray? = null): MessagePacket {
var expectRTS = firstCmd
if (expectRTS == null) {
expectRTS = bleIO.receivePacket(CharacteristicType.CMD)

View file

@ -11,7 +11,7 @@ class StringLengthPrefixEncoding {
companion object {
private val LENGTH_BYTES = 2
private const val LENGTH_BYTES = 2
fun parseKeys(keys: Array<String>, payload: ByteArray): Array<ByteArray> {
val ret = Array<ByteArray>(keys.size, { ByteArray(0) })

View file

@ -236,8 +236,9 @@ internal class LTKExchanger(private val aapsLogger: AAPSLogger, private val msgI
private val PDM_CONF_MAGIC_PREFIX = "KC_2_U".toByteArray()
private val POD_CONF_MAGIC_PREFIX = "KC_2_V".toByteArray()
private const val GET_POD_STATUS_HEX_COMMAND =
"ffc32dbd08030e0100008a" // TODO for now we are assuming this command is build out of constant parameters, use a proper command builder for that.
private const val GET_POD_STATUS_HEX_COMMAND = "ffc32dbd08030e0100008a"
// TODO for now we are assuming this command is build out of constant parameters,
// use a proper command builder for that.
private const val SP1 = "SP1="
private const val SP2 = ",SP2="

View file

@ -35,10 +35,8 @@ class Session(
val msg = getCmdMessage(cmd)
aapsLogger.debug(LTag.PUMPBTCOMM, "Sending command(wrapped): ${msg.payload.toHex()}")
val reply = msgIO.sendMessage(msg)
if (reply != null) { // TODO : this means the last ACK was not received, send it again?
aapsLogger.debug(LTag.PUMPBTCOMM, "Received a message with payload instead of CTS: ${reply.payload.toHex()} in packet $reply")
}
msgIO.sendMessage(msg)
val responseMsg = msgIO.receiveMessage()
val decrypted = enDecrypt.decrypt(responseMsg)
aapsLogger.debug(LTag.PUMPBTCOMM, "Received response: $decrypted")
@ -67,7 +65,7 @@ class Session(
payload = ByteArray(0),
eqos = 0,
ack = true,
ackNumber = (response.sequenceNumber.toInt()+1).toByte()
ackNumber = response.sequenceNumber.inc()
)
return enDecrypt.encrypt((msg))
}

View file

@ -1,19 +1,21 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.event
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.command.base.Command
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.Response
sealed class PodEvent {
/* BT connection events */
class AlreadyConnected(val bluetoothAddress: String, val uniqueId: Long) : PodEvent()
class AlreadyConnected(val bluetoothAddress: String) : PodEvent()
object AlreadyPaired : PodEvent()
object Scanning : PodEvent()
object BluetoothConnecting : PodEvent()
class BluetoothConnected(val address: String) : PodEvent()
class BluetoothConnected(val bluetoothAddress: String) : PodEvent()
object Pairing : PodEvent()
object Paired : PodEvent()
class Paired(val uniqueId: Id) : PodEvent()
object EstablishingSession : PodEvent()
class Connected(val uniqueId: Long) : PodEvent()
object Connected : PodEvent()
/* Message exchange events */
class CommandSending(val command: Command) : PodEvent()

View file

@ -1,5 +1,7 @@
package info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.state
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair.PairResult
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.*
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse
@ -54,6 +56,7 @@ interface OmnipodDashPodStateManager {
fun updateFromVersionResponse(response: VersionResponse)
fun updateFromSetUniqueIdResponse(response: SetUniqueIdResponse)
fun updateFromAlarmStatusResponse(response: AlarmStatusResponse)
fun updateFromPairing(uniqueId: Id, pairResult: PairResult)
fun reset()
data class TempBasal(val startTime: Long, val rate: Double, val durationInMinutes: Short) : Serializable

View file

@ -6,6 +6,8 @@ import info.nightscout.androidaps.logging.LTag
import info.nightscout.androidaps.plugins.bus.RxBusWrapper
import info.nightscout.androidaps.plugins.pump.omnipod.dash.EventOmnipodDashPumpValuesChanged
import info.nightscout.androidaps.plugins.pump.omnipod.dash.R
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.Id
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.comm.pair.PairResult
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.definition.*
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.AlarmStatusResponse
import info.nightscout.androidaps.plugins.pump.omnipod.dash.driver.pod.response.DefaultStatusResponse
@ -248,6 +250,12 @@ class OmnipodDashPodStateManagerImpl @Inject constructor(
rxBus.send(EventOmnipodDashPumpValuesChanged())
}
override fun updateFromPairing(uniqueId: Id, pairResult: PairResult) {
podState.eapAkaSequenceNumber = 1
podState.ltk = pairResult.ltk
podState.uniqueId = uniqueId.toLong()
}
override fun reset() {
podState = PodState()
store()

View file

@ -20,7 +20,7 @@ class EnDecryptTest {
Hex.decode("dda23c090a0a0a0a"),
0
),
Hex.decode("ba1283744b6de9fab6d9b77d95a71d6e"),
Hex.decode("ba1283744b6de9fab6d9b77d95a71d6e")
)
val encryptedMessage = Hex.decode(
"54571101070003400242000002420001" +
@ -43,7 +43,7 @@ class EnDecryptTest {
Hex.decode("dda23c090a0a0a0a"),
0
),
Hex.decode("ba1283744b6de9fab6d9b77d95a71d6e"),
Hex.decode("ba1283744b6de9fab6d9b77d95a71d6e")
)
val encryptedMessage = Hex.decode(
"54571101070003400242000002420001" +