Skip to content

Instantly share code, notes, and snippets.

@CristianMG
Created July 20, 2023 06:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CristianMG/9eae9dafbf6ef74594e0561fccadfb5a to your computer and use it in GitHub Desktop.
Save CristianMG/9eae9dafbf6ef74594e0561fccadfb5a to your computer and use it in GitHub Desktop.
Bluetooth write
suspend fun Peripheral.write(
characteristic: Characteristic,
data: ByteArray,
mtuSize: Int
): ByteArray =
observe(characteristic) {
if (data.size > (mtuSize - 3) ) {
Napier.d("data size is bigger than mtu, chunk it and write it")
data.chunkAndEach(mtuSize - 3) {
if(it.size == (mtuSize - 3)) {
write(characteristic, it, WriteType.WithoutResponse)
} else {
write(characteristic, it, WriteType.WithResponse)
}
}
} else {
Napier.d("data size is smaller than maxWriteSize,write it directly")
write(characteristic, data, WriteType.WithResponse)
}
}
.transformWhile {
Napier.d(
"takeWhile: size:${it.size}" + " Cadena: " + it.decodeToString(
throwOnInvalidSequence = true
)
)
emit(it)
!it.isMtuSizeReached(mtuSize)
}.fold(byteArrayOf()) { initial, value ->
val concat = initial.plus(value)
concat
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment