|
| 1 | +import Logging |
| 2 | +import NIO |
| 3 | + |
| 4 | +class MQTTMessageHandler: ChannelDuplexHandler { |
| 5 | + typealias InboundIn = ByteBuffer |
| 6 | + typealias InboundOut = MQTTPacket |
| 7 | + typealias OutboundIn = MQTTPacket |
| 8 | + typealias OutboundOut = ByteBuffer |
| 9 | + |
| 10 | + let client: MQTTClient |
| 11 | + let pingreqHandler: PingreqHandler? |
| 12 | + var decoder: NIOSingleStepByteToMessageProcessor<ByteToMQTTMessageDecoder> |
| 13 | + |
| 14 | + init(_ client: MQTTClient, pingInterval: TimeAmount) { |
| 15 | + self.client = client |
| 16 | + if client.configuration.disablePing { |
| 17 | + self.pingreqHandler = nil |
| 18 | + } else { |
| 19 | + self.pingreqHandler = .init(client: client, timeout: pingInterval) |
| 20 | + } |
| 21 | + self.decoder = .init(.init(version: client.configuration.version)) |
| 22 | + } |
| 23 | + |
| 24 | + func channelActive(context: ChannelHandlerContext) { |
| 25 | + self.pingreqHandler?.start(context: context) |
| 26 | + context.fireChannelActive() |
| 27 | + } |
| 28 | + |
| 29 | + func channelInactive(context: ChannelHandlerContext) { |
| 30 | + self.pingreqHandler?.stop() |
| 31 | + context.fireChannelInactive() |
| 32 | + } |
| 33 | + |
| 34 | + func write(context: ChannelHandlerContext, data: NIOAny, promise: EventLoopPromise<Void>?) { |
| 35 | + let message = unwrapOutboundIn(data) |
| 36 | + self.client.logger.trace("MQTT Out", metadata: ["mqtt_message": .string("\(message)"), "mqtt_packet_id": .string("\(message.packetId)")]) |
| 37 | + var bb = context.channel.allocator.buffer(capacity: 0) |
| 38 | + do { |
| 39 | + try message.write(version: self.client.configuration.version, to: &bb) |
| 40 | + context.write(wrapOutboundOut(bb), promise: promise) |
| 41 | + } catch { |
| 42 | + promise?.fail(error) |
| 43 | + } |
| 44 | + self.pingreqHandler?.write() |
| 45 | + } |
| 46 | + |
| 47 | + func channelRead(context: ChannelHandlerContext, data: NIOAny) { |
| 48 | + let buffer = self.unwrapInboundIn(data) |
| 49 | + |
| 50 | + do { |
| 51 | + try self.decoder.process(buffer: buffer) { message in |
| 52 | + switch message.type { |
| 53 | + case .PUBLISH: |
| 54 | + let publishMessage = message as! MQTTPublishPacket |
| 55 | + // publish logging includes topic name |
| 56 | + self.client.logger.trace("MQTT In", metadata: [ |
| 57 | + "mqtt_message": .stringConvertible(publishMessage), |
| 58 | + "mqtt_packet_id": .stringConvertible(publishMessage.packetId), |
| 59 | + "mqtt_topicName": .string(publishMessage.publish.topicName), |
| 60 | + ]) |
| 61 | + self.respondToPublish(publishMessage) |
| 62 | + return |
| 63 | + |
| 64 | + case .CONNACK, .PUBACK, .PUBREC, .PUBCOMP, .SUBACK, .UNSUBACK, .PINGRESP, .AUTH: |
| 65 | + context.fireChannelRead(wrapInboundOut(message)) |
| 66 | + |
| 67 | + case .PUBREL: |
| 68 | + self.respondToPubrel(message) |
| 69 | + context.fireChannelRead(wrapInboundOut(message)) |
| 70 | + |
| 71 | + case .DISCONNECT: |
| 72 | + let disconnectMessage = message as! MQTTDisconnectPacket |
| 73 | + let ack = MQTTAckV5(reason: disconnectMessage.reason, properties: disconnectMessage.properties) |
| 74 | + context.fireErrorCaught(MQTTError.serverDisconnection(ack)) |
| 75 | + context.close(promise: nil) |
| 76 | + |
| 77 | + case .CONNECT, .SUBSCRIBE, .UNSUBSCRIBE, .PINGREQ: |
| 78 | + context.fireErrorCaught(MQTTError.unexpectedMessage) |
| 79 | + context.close(promise: nil) |
| 80 | + self.client.logger.error("Unexpected MQTT Message", metadata: ["mqtt_message": .string("\(message)")]) |
| 81 | + return |
| 82 | + } |
| 83 | + self.client.logger.trace("MQTT In", metadata: ["mqtt_message": .stringConvertible(message), "mqtt_packet_id": .stringConvertible(message.packetId)]) |
| 84 | + } |
| 85 | + } catch { |
| 86 | + context.fireErrorCaught(error) |
| 87 | + context.close(promise: nil) |
| 88 | + self.client.logger.error("Error processing MQTT message", metadata: ["mqtt_error": .string("\(error)")]) |
| 89 | + } |
| 90 | + } |
| 91 | + |
| 92 | + func updatePingreqTimeout(_ timeout: TimeAmount) { |
| 93 | + self.pingreqHandler?.updateTimeout(timeout) |
| 94 | + } |
| 95 | + |
| 96 | + /// Respond to PUBLISH message |
| 97 | + /// If QoS is `.atMostOnce` then no response is required |
| 98 | + /// If QoS is `.atLeastOnce` then send PUBACK |
| 99 | + /// If QoS is `.exactlyOnce` then send PUBREC, wait for PUBREL and then respond with PUBCOMP (in `respondToPubrel`) |
| 100 | + private func respondToPublish(_ message: MQTTPublishPacket) { |
| 101 | + guard let connection = client.connection else { return } |
| 102 | + switch message.publish.qos { |
| 103 | + case .atMostOnce: |
| 104 | + self.client.publishListeners.notify(.success(message.publish)) |
| 105 | + |
| 106 | + case .atLeastOnce: |
| 107 | + connection.sendMessageNoWait(MQTTPubAckPacket(type: .PUBACK, packetId: message.packetId)) |
| 108 | + .map { _ in return message.publish } |
| 109 | + .whenComplete { self.client.publishListeners.notify($0) } |
| 110 | + |
| 111 | + case .exactlyOnce: |
| 112 | + var publish = message.publish |
| 113 | + connection.sendMessage(MQTTPubAckPacket(type: .PUBREC, packetId: message.packetId)) { newMessage in |
| 114 | + guard newMessage.packetId == message.packetId else { return false } |
| 115 | + // if we receive a publish message while waiting for a PUBREL from broker then replace data to be published and retry PUBREC |
| 116 | + if newMessage.type == .PUBLISH, let publishMessage = newMessage as? MQTTPublishPacket { |
| 117 | + publish = publishMessage.publish |
| 118 | + throw MQTTError.retrySend |
| 119 | + } |
| 120 | + // if we receive anything but a PUBREL then throw unexpected message |
| 121 | + guard newMessage.type == .PUBREL else { throw MQTTError.unexpectedMessage } |
| 122 | + // now we have received the PUBREL we can process the published message. PUBCOMP is sent by `respondToPubrel` |
| 123 | + return true |
| 124 | + } |
| 125 | + .map { _ in return publish } |
| 126 | + .whenComplete { result in |
| 127 | + // do not report retrySend error |
| 128 | + if case .failure(let error) = result, case MQTTError.retrySend = error { |
| 129 | + return |
| 130 | + } |
| 131 | + self.client.publishListeners.notify(result) |
| 132 | + } |
| 133 | + } |
| 134 | + } |
| 135 | + |
| 136 | + /// Respond to PUBREL message by sending PUBCOMP. Do this separate from `responeToPublish` as the broker might send |
| 137 | + /// multiple PUBREL messages, if the client is slow to respond |
| 138 | + private func respondToPubrel(_ message: MQTTPacket) { |
| 139 | + guard let connection = client.connection else { return } |
| 140 | + _ = connection.sendMessageNoWait(MQTTPubAckPacket(type: .PUBCOMP, packetId: message.packetId)) |
| 141 | + } |
| 142 | +} |
0 commit comments