Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
37 changes: 25 additions & 12 deletions Sources/MQTT/MQTTChannelHandler.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,32 +13,45 @@ final class MQTTChannelHandler: ChannelInboundHandler {

private let decoder: MQTTDecoder
weak var delegate: MQTTChannelHandlerDelegate?
private var packetData = Data()

init(decoder: MQTTDecoder = MQTTDecoder()) {
self.decoder = decoder
}

func channelRead(context _: ChannelHandlerContext, data: NIOAny) {
func channelRead(context: ChannelHandlerContext, data: NIOAny) {
defer { context.fireChannelRead(data) }

var buf = unwrapInboundIn(data)
if let bytes = buf.readBytes(length: buf.readableBytes) {
var data = Data(bytes)
do {
let packet = try decoder.decode(data: &data)
delegate?.didReceive(packet: packet)
} catch let error as DecodeError {
delegate?.didCatch(decodeError: error)
} catch {
// unhandled error
fatalError("Error while decoding packet data: \(error.localizedDescription)")
}
packetData.append(contentsOf: bytes)
}
}

func channelReadComplete(context: ChannelHandlerContext) {
defer { context.fireChannelReadComplete() }

var data = packetData
packetData = Data()

do {
let packet = try decoder.decode(data: &data)
delegate?.didReceive(packet: packet)
} catch let error as DecodeError {
delegate?.didCatch(decodeError: error)
} catch {
// unhandled error
fatalError("Error while decoding packet data: \(error.localizedDescription)")
}
}

func channelActive(context: ChannelHandlerContext) {
defer { context.fireChannelActive() }
delegate?.channelActive(channel: context.channel)
}

func channelInactive(context _: ChannelHandlerContext) {
func channelInactive(context: ChannelHandlerContext) {
defer { context.fireChannelInactive() }
delegate?.channelInactive()
}
}