commonMain.mqtt.packets.mqttv5.MQTT5Pubrec.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of kmqtt-common-jvm Show documentation
Show all versions of kmqtt-common-jvm Show documentation
Kotlin Multiplatform MQTT client & embeddable and standalone broker
package mqtt.packets.mqttv5
import mqtt.MQTTException
import mqtt.packets.MQTTControlPacketType
import mqtt.packets.MQTTDeserializer
import mqtt.packets.mqtt.MQTTPubrec
import socket.streams.ByteArrayInputStream
import socket.streams.ByteArrayOutputStream
public class MQTT5Pubrec(
packetId: UInt,
public val reasonCode: ReasonCode = ReasonCode.SUCCESS,
public val properties: MQTT5Properties = MQTT5Properties()
) : MQTTPubrec(packetId), MQTT5Packet {
override fun resizeIfTooBig(maximumPacketSize: UInt): Boolean {
if (size() > maximumPacketSize) {
properties.reasonString = null
}
if (size() > maximumPacketSize) {
properties.userProperty.clear()
}
return size() <= maximumPacketSize
}
override fun toByteArray(): UByteArray {
if (reasonCode !in validReasonCodes)
throw IllegalArgumentException("Invalid reason code")
val outStream = ByteArrayOutputStream()
outStream.write2BytesInt(packetId)
outStream.writeByte(reasonCode.value.toUInt())
outStream.write(properties.serializeProperties(validProperties))
return outStream.wrapWithFixedHeader(MQTTControlPacketType.PUBREC, 0)
}
public companion object : MQTTDeserializer {
private val validProperties = listOf(
Property.REASON_STRING,
Property.USER_PROPERTY
)
private val validReasonCodes = listOf(
ReasonCode.SUCCESS,
ReasonCode.NO_MATCHING_SUBSCRIBERS,
ReasonCode.UNSPECIFIED_ERROR,
ReasonCode.IMPLEMENTATION_SPECIFIC_ERROR,
ReasonCode.NOT_AUTHORIZED,
ReasonCode.TOPIC_NAME_INVALID,
ReasonCode.PACKET_IDENTIFIER_IN_USE,
ReasonCode.QUOTA_EXCEEDED,
ReasonCode.PAYLOAD_FORMAT_INVALID
)
override fun fromByteArray(flags: Int, data: UByteArray): MQTT5Pubrec {
checkFlags(flags)
val inStream = ByteArrayInputStream(data)
val packetId = inStream.read2BytesInt()
return if (inStream.available() == 0) { // Reason code and properties omitted
MQTT5Pubrec(packetId)
} else {
val reasonCode =
ReasonCode.valueOf(inStream.readByte().toInt()) ?: throw MQTTException(
ReasonCode.MALFORMED_PACKET
)
if (reasonCode !in validReasonCodes)
throw MQTTException(ReasonCode.PROTOCOL_ERROR)
if (inStream.available() == 0) {
MQTT5Pubrec(packetId, reasonCode)
} else {
val properties = inStream.deserializeProperties(validProperties)
MQTT5Pubrec(packetId, reasonCode, properties)
}
}
}
}
}