Example #1
0
        public ArraySegment <byte> Encode(MqttBasePacket packet)
        {
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }

            // Leave enough head space for max header size (fixed + 4 variable remaining length = 5 bytes)
            _packetWriter.Reset(5);
            _packetWriter.Seek(5);

            var fixedHeader     = EncodePacket(packet, _packetWriter);
            var remainingLength = (uint)(_packetWriter.Length - 5);

            var remainingLengthSize = MqttPacketWriter.GetLengthOfVariableInteger(remainingLength);

            var headerSize   = 1 + remainingLengthSize;
            var headerOffset = 5 - headerSize;

            // Position cursor on correct offset on beginning of array (has leading 0x0)
            _packetWriter.Seek(headerOffset);
            _packetWriter.Write(fixedHeader);
            _packetWriter.WriteVariableLengthInteger(remainingLength);

            var buffer = _packetWriter.GetBuffer();

            return(new ArraySegment <byte>(buffer, headerOffset, _packetWriter.Length - headerOffset));
        }
        private static byte EncodeUnsubscribePacket(MqttUnsubscribePacket packet, IMqttPacketWriter packetWriter)
        {
            if (packet.TopicFilters?.Any() != true)
            {
                throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2].");
            }

            ThrowIfPacketIdentifierIsInvalid(packet);

            packetWriter.Write(packet.PacketIdentifier.Value);

            var propertiesWriter = new MqttV500PropertiesWriter();

            if (packet.Properties != null)
            {
                propertiesWriter.WriteUserProperties(packet.Properties.UserProperties);
            }

            propertiesWriter.WriteTo(packetWriter);

            foreach (var topicFilter in packet.TopicFilters)
            {
                packetWriter.WriteWithLengthPrefix(topicFilter);
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Unsubscibe, 0x02));
        }
Example #3
0
        static byte EncodePublishPacket(MqttPublishPacket packet, IMqttPacketWriter packetWriter)
        {
            ValidatePublishPacket(packet);

            packetWriter.WriteWithLengthPrefix(packet.Topic);

            if (packet.QualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
            {
                if (!packet.PacketIdentifier.HasValue)
                {
                    throw new MqttProtocolViolationException("Publish packet has no packet identifier.");
                }

                packetWriter.Write(packet.PacketIdentifier.Value);
            }
            else
            {
                if (packet.PacketIdentifier > 0)
                {
                    throw new MqttProtocolViolationException("Packet identifier must be empty if QoS == 0 [MQTT-2.3.1-5].");
                }
            }

            if (packet.Payload?.Length > 0)
            {
                packetWriter.Write(packet.Payload, 0, packet.Payload.Length);
            }

            byte fixedHeader = 0;

            if (packet.Retain)
            {
                fixedHeader |= 0x01;
            }

            fixedHeader |= (byte)((byte)packet.QualityOfServiceLevel << 1);

            if (packet.Dup)
            {
                fixedHeader |= 0x08;
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Publish, fixedHeader));
        }
Example #4
0
        static byte EncodeUnsubAckPacket(MqttUnsubAckPacket packet, IMqttPacketWriter packetWriter)
        {
            if (!packet.PacketIdentifier.HasValue)
            {
                throw new MqttProtocolViolationException("UnsubAck packet has no packet identifier.");
            }

            packetWriter.Write(packet.PacketIdentifier.Value);
            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.UnsubAck));
        }
Example #5
0
        static byte EncodeSubAckPacket(MqttSubAckPacket packet, IMqttPacketWriter packetWriter)
        {
            if (!packet.PacketIdentifier.HasValue)
            {
                throw new MqttProtocolViolationException("SubAck packet has no packet identifier.");
            }

            packetWriter.Write(packet.PacketIdentifier.Value);

            if (packet.ReturnCodes?.Any() == true)
            {
                foreach (var packetSubscribeReturnCode in packet.ReturnCodes)
                {
                    packetWriter.Write((byte)packetSubscribeReturnCode);
                }
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.SubAck));
        }
Example #6
0
        public void WriteTo(IMqttPacketWriter packetWriter)
        {
            if (packetWriter == null)
            {
                throw new ArgumentNullException(nameof(packetWriter));
            }

            packetWriter.WriteVariableLengthInteger((uint)_packetWriter.Length);
            packetWriter.Write(_packetWriter);
        }
        private static byte EncodePubCompPacket(MqttPubCompPacket packet, IMqttPacketWriter packetWriter)
        {
            if (!packet.PacketIdentifier.HasValue)
            {
                throw new MqttProtocolViolationException("PubComp packet has no packet identifier.");
            }

            packetWriter.Write(packet.PacketIdentifier.Value);

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.PubComp));
        }
        static byte EncodePubRecPacket(MqttPubRecPacket packet, IMqttPacketWriter packetWriter)
        {
            if (packet.PacketIdentifier == 0)
            {
                throw new MqttProtocolViolationException("PubRec packet has no packet identifier.");
            }

            packetWriter.Write(packet.PacketIdentifier);

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.PubRec));
        }
Example #9
0
        static byte EncodeSubscribePacket(MqttSubscribePacket packet, IMqttPacketWriter packetWriter)
        {
            if (!packet.TopicFilters.Any())
            {
                throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.8.3-3].");
            }

            if (packet.PacketIdentifier == 0)
            {
                throw new MqttProtocolViolationException("Subscribe packet has no packet identifier.");
            }

            packetWriter.Write(packet.PacketIdentifier);

            if (packet.TopicFilters?.Count > 0)
            {
                foreach (var topicFilter in packet.TopicFilters)
                {
                    if (topicFilter.NoLocal)
                    {
                        throw new MqttProtocolViolationException("NoLocal is not supported in 3.1.1.");
                    }

                    if (topicFilter.RetainAsPublished)
                    {
                        throw new MqttProtocolViolationException("RetainAsPublished is not supported in 3.1.1.");
                    }

                    if (topicFilter.RetainHandling != MqttRetainHandling.SendAtSubscribe)
                    {
                        throw new MqttProtocolViolationException("RetainHandling is not supported in 3.1.1.");
                    }

                    packetWriter.WriteWithLengthPrefix(topicFilter.Topic);
                    packetWriter.Write((byte)topicFilter.QualityOfServiceLevel);
                }
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Subscribe, 0x02));
        }
Example #10
0
        private static byte EncodePubAckPacket(MqttPubAckPacket packet, IMqttPacketWriter packetWriter)
        {
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }
            if (packetWriter == null)
            {
                throw new ArgumentNullException(nameof(packetWriter));
            }

            if (!packet.PacketIdentifier.HasValue)
            {
                throw new MqttProtocolViolationException("PubAck packet has no packet identifier.");
            }

            if (!packet.ReasonCode.HasValue)
            {
                throw new MqttProtocolViolationException("PubAck packet must contain a reason code.");
            }

            packetWriter.Write(packet.PacketIdentifier.Value);

            var propertiesWriter = new MqttV500PropertiesWriter();

            if (packet.Properties != null)
            {
                propertiesWriter.WriteReasonString(packet.Properties.ReasonString);
                propertiesWriter.WriteUserProperties(packet.Properties.UserProperties);
            }

            if (packetWriter.Length > 0 || packet.ReasonCode.Value != MqttPubAckReasonCode.Success)
            {
                packetWriter.Write((byte)packet.ReasonCode.Value);
                propertiesWriter.WriteTo(packetWriter);
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.PubAck));
        }
Example #11
0
        private static byte EncodeAuthPacket(MqttAuthPacket packet, IMqttPacketWriter packetWriter)
        {
            packetWriter.Write((byte)packet.ReasonCode);

            var propertiesWriter = new MqttV500PropertiesWriter();

            if (packet.Properties != null)
            {
                propertiesWriter.WriteAuthenticationMethod(packet.Properties.AuthenticationMethod);
                propertiesWriter.WriteAuthenticationData(packet.Properties.AuthenticationData);
                propertiesWriter.WriteReasonString(packet.Properties.ReasonString);
                propertiesWriter.WriteUserProperties(packet.Properties.UserProperties);
            }

            propertiesWriter.WriteTo(packetWriter);

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Auth));
        }
Example #12
0
        private static byte EncodeDisconnectPacket(MqttDisconnectPacket packet, IMqttPacketWriter packetWriter)
        {
            if (!packet.ReasonCode.HasValue)
            {
                ThrowReasonCodeNotSetException();
            }

            packetWriter.Write((byte)packet.ReasonCode.Value);

            var propertiesWriter = new MqttV500PropertiesWriter();

            if (packet.Properties != null)
            {
                propertiesWriter.WriteServerReference(packet.Properties.ServerReference);
                propertiesWriter.WriteReasonString(packet.Properties.ReasonString);
                propertiesWriter.WriteSessionExpiryInterval(packet.Properties.SessionExpiryInterval);
                propertiesWriter.WriteUserProperties(packet.Properties.UserProperties);
            }

            propertiesWriter.WriteTo(packetWriter);

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Disconnect));
        }
Example #13
0
        static byte EncodeUnsubscribePacket(MqttUnsubscribePacket packet, IMqttPacketWriter packetWriter)
        {
            if (!packet.TopicFilters.Any())
            {
                throw new MqttProtocolViolationException("At least one topic filter must be set [MQTT-3.10.3-2].");
            }

            if (!packet.PacketIdentifier.HasValue)
            {
                throw new MqttProtocolViolationException("Unsubscribe packet has no packet identifier.");
            }

            packetWriter.Write(packet.PacketIdentifier.Value);

            if (packet.TopicFilters?.Any() == true)
            {
                foreach (var topicFilter in packet.TopicFilters)
                {
                    packetWriter.WriteWithLengthPrefix(topicFilter);
                }
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Unsubscibe, 0x02));
        }
Example #14
0
        protected virtual byte EncodeConnectPacket(MqttConnectPacket packet, IMqttPacketWriter packetWriter)
        {
            ValidateConnectPacket(packet);

            packetWriter.WriteWithLengthPrefix("MQIsdp");
            packetWriter.Write(3); // Protocol Level 3

            byte connectFlags = 0x0;

            if (packet.CleanSession)
            {
                connectFlags |= 0x2;
            }

            if (packet.WillMessage != null)
            {
                connectFlags |= 0x4;
                connectFlags |= (byte)((byte)packet.WillMessage.QualityOfServiceLevel << 3);

                if (packet.WillMessage.Retain)
                {
                    connectFlags |= 0x20;
                }
            }

            if (packet.Password != null && packet.Username == null)
            {
                throw new MqttProtocolViolationException("If the User Name Flag is set to 0, the Password Flag MUST be set to 0 [MQTT-3.1.2-22].");
            }

            if (packet.Password != null)
            {
                connectFlags |= 0x40;
            }

            if (packet.Username != null)
            {
                connectFlags |= 0x80;
            }

            packetWriter.Write(connectFlags);
            packetWriter.Write(packet.KeepAlivePeriod);
            packetWriter.WriteWithLengthPrefix(packet.ClientId);

            if (packet.WillMessage != null)
            {
                packetWriter.WriteWithLengthPrefix(packet.WillMessage.Topic);
                packetWriter.WriteWithLengthPrefix(packet.WillMessage.Payload);
            }

            if (packet.Username != null)
            {
                packetWriter.WriteWithLengthPrefix(packet.Username);
            }

            if (packet.Password != null)
            {
                packetWriter.WriteWithLengthPrefix(packet.Password);
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Connect));
        }
Example #15
0
        private static byte EncodeConnectPacket(MqttConnectPacket packet, IMqttPacketWriter packetWriter)
        {
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }
            if (packetWriter == null)
            {
                throw new ArgumentNullException(nameof(packetWriter));
            }

            if (string.IsNullOrEmpty(packet.ClientId) && !packet.CleanSession)
            {
                throw new MqttProtocolViolationException("CleanSession must be set if ClientId is empty [MQTT-3.1.3-7].");
            }

            packetWriter.WriteWithLengthPrefix("MQTT");
            packetWriter.Write(5); // [3.1.2.2 Protocol Version]

            byte connectFlags = 0x0;

            if (packet.CleanSession)
            {
                connectFlags |= 0x2;
            }

            if (packet.WillMessage != null)
            {
                connectFlags |= 0x4;
                connectFlags |= (byte)((byte)packet.WillMessage.QualityOfServiceLevel << 3);

                if (packet.WillMessage.Retain)
                {
                    connectFlags |= 0x20;
                }
            }

            if (packet.Password != null && packet.Username == null)
            {
                throw new MqttProtocolViolationException("If the User Name Flag is set to 0, the Password Flag MUST be set to 0 [MQTT-3.1.2-22].");
            }

            if (packet.Password != null)
            {
                connectFlags |= 0x40;
            }

            if (packet.Username != null)
            {
                connectFlags |= 0x80;
            }

            packetWriter.Write(connectFlags);
            packetWriter.Write(packet.KeepAlivePeriod);

            var propertiesWriter = new MqttV500PropertiesWriter();

            if (packet.Properties != null)
            {
                propertiesWriter.WriteSessionExpiryInterval(packet.Properties.SessionExpiryInterval);
                propertiesWriter.WriteAuthenticationMethod(packet.Properties.AuthenticationMethod);
                propertiesWriter.WriteAuthenticationData(packet.Properties.AuthenticationData);
                propertiesWriter.WriteRequestProblemInformation(packet.Properties.RequestProblemInformation);
                propertiesWriter.WriteRequestResponseInformation(packet.Properties.RequestResponseInformation);
                propertiesWriter.WriteReceiveMaximum(packet.Properties.ReceiveMaximum);
                propertiesWriter.WriteTopicAliasMaximum(packet.Properties.TopicAliasMaximum);
                propertiesWriter.WriteMaximumPacketSize(packet.Properties.MaximumPacketSize);
                propertiesWriter.WriteUserProperties(packet.Properties.UserProperties);
            }

            propertiesWriter.WriteTo(packetWriter);

            packetWriter.WriteWithLengthPrefix(packet.ClientId);

            if (packet.WillMessage != null)
            {
                var willPropertiesWriter = new MqttV500PropertiesWriter();
                willPropertiesWriter.WritePayloadFormatIndicator(packet.WillMessage.PayloadFormatIndicator);
                willPropertiesWriter.WriteMessageExpiryInterval(packet.WillMessage.MessageExpiryInterval);
                willPropertiesWriter.WriteTopicAlias(packet.WillMessage.TopicAlias);
                willPropertiesWriter.WriteResponseTopic(packet.WillMessage.ResponseTopic);
                willPropertiesWriter.WriteCorrelationData(packet.WillMessage.CorrelationData);
                willPropertiesWriter.WriteSubscriptionIdentifiers(packet.WillMessage.SubscriptionIdentifiers);
                willPropertiesWriter.WriteContentType(packet.WillMessage.ContentType);
                willPropertiesWriter.WriteUserProperties(packet.WillMessage.UserProperties);

                // This is a special case!
                willPropertiesWriter.WriteWillDelayInterval(packet.Properties?.WillDelayInterval);

                willPropertiesWriter.WriteTo(packetWriter);

                packetWriter.WriteWithLengthPrefix(packet.WillMessage.Topic);
                packetWriter.WriteWithLengthPrefix(packet.WillMessage.Payload);
            }

            if (packet.Username != null)
            {
                packetWriter.WriteWithLengthPrefix(packet.Username);
            }

            if (packet.Password != null)
            {
                packetWriter.WriteWithLengthPrefix(packet.Password);
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Connect));
        }
Example #16
0
        private static byte EncodePublishPacket(MqttPublishPacket packet, IMqttPacketWriter packetWriter)
        {
            if (packet == null)
            {
                throw new ArgumentNullException(nameof(packet));
            }
            if (packetWriter == null)
            {
                throw new ArgumentNullException(nameof(packetWriter));
            }

            if (packet.QualityOfServiceLevel == 0 && packet.Dup)
            {
                throw new MqttProtocolViolationException("Dup flag must be false for QoS 0 packets [MQTT-3.3.1-2].");
            }

            packetWriter.WriteWithLengthPrefix(packet.Topic);

            if (packet.QualityOfServiceLevel > MqttQualityOfServiceLevel.AtMostOnce)
            {
                if (!packet.PacketIdentifier.HasValue)
                {
                    throw new MqttProtocolViolationException("Publish packet has no packet identifier.");
                }

                packetWriter.Write(packet.PacketIdentifier.Value);
            }
            else
            {
                if (packet.PacketIdentifier > 0)
                {
                    throw new MqttProtocolViolationException("Packet identifier must be 0 if QoS == 0 [MQTT-2.3.1-5].");
                }
            }

            var propertiesWriter = new MqttV500PropertiesWriter();

            if (packet.Properties != null)
            {
                propertiesWriter.WritePayloadFormatIndicator(packet.Properties.PayloadFormatIndicator);
                propertiesWriter.WriteMessageExpiryInterval(packet.Properties.MessageExpiryInterval);
                propertiesWriter.WriteTopicAlias(packet.Properties.TopicAlias);
                propertiesWriter.WriteResponseTopic(packet.Properties.ResponseTopic);
                propertiesWriter.WriteCorrelationData(packet.Properties.CorrelationData);
                propertiesWriter.WriteSubscriptionIdentifiers(packet.Properties.SubscriptionIdentifiers);
                propertiesWriter.WriteContentType(packet.Properties.ContentType);
                propertiesWriter.WriteUserProperties(packet.Properties.UserProperties);
            }

            propertiesWriter.WriteTo(packetWriter);

            if (packet.Payload?.Length > 0)
            {
                packetWriter.Write(packet.Payload, 0, packet.Payload.Length);
            }

            byte fixedHeader = 0;

            if (packet.Retain)
            {
                fixedHeader |= 0x01;
            }

            fixedHeader |= (byte)((byte)packet.QualityOfServiceLevel << 1);

            if (packet.Dup)
            {
                fixedHeader |= 0x08;
            }

            return(MqttPacketWriter.BuildFixedHeader(MqttControlPacketType.Publish, fixedHeader));
        }