Skip to content

Commit

Permalink
Merge pull request #588 from NordicSemiconductor/bugfix/packet-merger
Browse files Browse the repository at this point in the history
Bugfix: Packet mergers in sample apps
  • Loading branch information
philips77 authored Sep 11, 2024
2 parents 1eec99b + 88e832d commit 33071ca
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 16 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -6,37 +6,38 @@ import java.nio.ByteBuffer

class PacketMerger : DataMerger {
private var expectedSize = 0
private var receivedDataSize = 0

/**
* A method that merges the last packet into the output message. All bytes from the lastPacket
* are simply copied to the output stream until null is returned.
* A method that merges the last packet into the output message.
* If its a fist packet, the first two bytes of the packet contain a header which includes the expected size
* of the message to be received. The remaining bytes of the packet contain the message, which is copied to the output stream.
* For all subsequent packets, the message bytes are simply copied to the output stream
* until the size of the packet received matches the expected size of the message delivered through header file.
*
* @param output the stream for the output message, initially empty.
* @param lastPacket the data received in the last read/notify/indicate operation.
* @param index an index of the packet, 0-based.
* @return True, if the message is complete, false if more data are expected.
* @return True, if the message is complete, false if more data are expected.
*/
override fun merge(output: DataStream, lastPacket: ByteArray?, index: Int): Boolean {
if (lastPacket == null)
return false

if (index == 0) {
receivedDataSize = 0
}

val buffer = ByteBuffer.wrap(lastPacket)
receivedDataSize += buffer.remaining()

if (index == 0) {
expectedSize = buffer.short.toInt()
}

if (buffer.remaining() == expectedSize) {
ByteArray(expectedSize)
.apply { buffer.get(this) }
.also { output.write(it) }
.let { return true }
} else {
ByteArray(buffer.remaining())
.apply { buffer.get(this) }
.also { output.write(it) }
.let { return false }
}
ByteArray(buffer.remaining())
.apply { buffer.get(this) }
.also { output.write(it) }
return receivedDataSize - 2 >= expectedSize
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class HeaderBasedPacketMerger: DataMerger {
if (lastPacket == null)
return false

if (index == 0) {
receivedDataSize = 0
}

val buffer = ByteBuffer.wrap(lastPacket)
receivedDataSize += buffer.remaining()

Expand All @@ -33,7 +37,7 @@ class HeaderBasedPacketMerger: DataMerger {
ByteArray(buffer.remaining())
.apply { buffer.get(this) }
.also { output.write(it) }
return receivedDataSize - 2 == expectedSize
return receivedDataSize - 2 >= expectedSize
}

}

0 comments on commit 33071ca

Please sign in to comment.