BLEComm: Synchronize read and writes better

This commit is contained in:
jbr7rr 2023-06-20 12:00:04 +02:00
parent 2302711cdf
commit bc8876b6dd

View file

@ -99,6 +99,7 @@ class BLEComm @Inject internal constructor(
private var mWritePackets: WriteCommandPackets? = null private var mWritePackets: WriteCommandPackets? = null
private var mWriteSequenceNumber: Int = 0 private var mWriteSequenceNumber: Int = 0
private var mReadPacket: ReadDataPacket? = null private var mReadPacket: ReadDataPacket? = null
private val readLock = Any()
private var mDeviceSN: Long = 0 private var mDeviceSN: Long = 0
private var mCallback: BLECommCallback? = null private var mCallback: BLECommCallback? = null
@ -268,14 +269,16 @@ class BLEComm @Inject internal constructor(
if (characteristic.getUuid() == UUID.fromString(READ_UUID)) { if (characteristic.getUuid() == UUID.fromString(READ_UUID)) {
mCallback?.onNotification(value) mCallback?.onNotification(value)
} else if (characteristic.getUuid() == UUID.fromString(WRITE_UUID)) { } else if (characteristic.getUuid() == UUID.fromString(WRITE_UUID)) {
if (mReadPacket == null) { synchronized(readLock) {
mReadPacket = ReadDataPacket(value) if (mReadPacket == null) {
} else { mReadPacket = ReadDataPacket(value)
mReadPacket?.addData(value) } else {
} mReadPacket?.addData(value)
if (mReadPacket?.allDataReceived() == true) { }
mReadPacket?.getData()?.let { mCallback?.onIndication(it) } if (mReadPacket?.allDataReceived() == true) {
mReadPacket = null mReadPacket?.getData()?.let { mCallback?.onIndication(it) }
mReadPacket = null
}
} }
} }
} }
@ -456,6 +459,7 @@ class BLEComm @Inject internal constructor(
mBluetoothGatt?.writeCharacteristic(characteristic) mBluetoothGatt?.writeCharacteristic(characteristic)
} }
}, WRITE_DELAY_MILLIS) }, WRITE_DELAY_MILLIS)
SystemClock.sleep(WRITE_DELAY_MILLIS)
} }
private val uartWriteBTGattChar: BluetoothGattCharacteristic private val uartWriteBTGattChar: BluetoothGattCharacteristic