// TODO: Consider creating "CoapMessageDecodeResult" which has Message (null or set) and "DecodeResult" as INTERFACE with all possible errors (VersionInvalidDecodeResult) etc.
        public CoapMessage Decode(ArraySegment <byte> buffer)
        {
            using (var reader = new CoapMessageReader(buffer))
            {
                var version = reader.ReadBits(2);
                if (version != 0x1)
                {
                    throw new CoAPProtocolViolationException("Version is not set to 1.");
                }

                var type = reader.ReadBits(2);
                if (type > 2)
                {
                    throw new CoAPProtocolViolationException("Type is invalid.");
                }

                var tokenLength = reader.ReadBits(4);

                var code        = (byte)reader.ReadBits(8);
                var codeClass   = (byte)(code >> 5);
                var codeDetails = (byte)(0x1F & code);

                var id = reader.ReadByte() << 8;
                id |= reader.ReadByte();

                byte[] token = null;
                if (tokenLength > 0)
                {
                    token = reader.ReadBytes(tokenLength);
                }

                var options = DecodeOptions(reader);

                var payload = reader.ReadToEnd();

                var message = new CoapMessage
                {
                    Type    = (CoapMessageType)type,
                    Code    = new CoapMessageCode(codeClass, codeDetails),
                    Id      = (ushort)id,
                    Token   = token,
                    Options = options,
                    Payload = payload
                };

                return(message);
            }
        }
        public async Task <CoapMessage> ObserveAsync(CoapMessage message)
        {
            if (!message.Observe.HasValue)
            {
                //RST because GET needs to be observe/unobserve
                Trace.TraceWarning("{0} - CoAP observe received without Observe flag set on channel '{1}', returning RST", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), channel.Id);
                return(new CoapResponse(message.MessageId, ResponseMessageType.Reset, ResponseCodeType.EmptyMessage));
            }

            CoapUri             uri = new CoapUri(message.ResourceUri.ToString());
            ResponseMessageType rmt = message.MessageType == CoapMessageType.Confirmable ? ResponseMessageType.Acknowledgement : ResponseMessageType.NonConfirmable;

            if (!await adapter.CanSubscribeAsync(uri.Resource, channel.IsEncrypted))
            {
                //not authorized
                Trace.TraceWarning("{0} - CoAP observe not authorized on channel '{1}'", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), channel.Id);
                return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Unauthorized, message.Token));
            }

            if (!message.Observe.Value)
            {
                //unsubscribe
                Trace.TraceWarning("{0} - CoAP observe with value on channel '{1}', unsubscribing.", DateTime.UtcNow.ToString("yyyy-MM-ddTHH-MM-ss.fffff"), channel.Id);
                await adapter.UnsubscribeAsync(uri.Resource);

                coapObserved.Remove(uri.Resource);
            }
            else
            {
                //subscribe
                SubscriptionMetadata metadata = new SubscriptionMetadata()
                {
                    IsEphemeral = true,
                    Identity    = session.Identity,
                    Indexes     = session.Indexes
                };

                string subscriptionUriString = await adapter.SubscribeAsync(uri.Resource, metadata);


                if (!coapObserved.ContainsKey(uri.Resource)) //add resource to observed list
                {
                    coapObserved.Add(uri.Resource, message.Token);
                }
            }

            return(new CoapResponse(message.MessageId, rmt, ResponseCodeType.Valid, message.Token));
        }
        /// <summary>
        /// Executes an action on the resource.
        /// </summary>
        /// <param name="Request">Request message.</param>
        public virtual void Execute(CoapMessage Request)
        {
            if (!string.IsNullOrEmpty(this.name))
            {
                Log.Informational("Executing action.", this.name, Request.From.ToString());
            }

            try
            {
                this.OnExecute?.Invoke(this, new CoapRequestEventArgs(Request));
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
            }
        }
        public void TestMessageToUri()
        {
            _message = new CoapMessage
            {
                Options = new List <CoapOption>
                {
                    new Options.UriHost("example.net"),
                    new Options.UriPath(".well-known"),
                    new Options.UriPath("core"),
                }
            };
            var expected = new Uri("coap://example.net/.well-known/core");
            var actual   = _message.GetUri();

            Assert.AreEqual(expected, actual);
        }
Beispiel #5
0
        public bool TryHandleReceivedMessage(CoapMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

            if (_awaiters.TryRemove(message.Id, out var awaiter))
            {
                awaiter.Complete(message);
                return(true);
            }

            // TODO: Distinguish between observed messages and out of date responses (CancellationToken etc.)
            return(false);
        }
Beispiel #6
0
        public static byte[] ConvertToHttp(EventMessage message)
        {
            if (message.Protocol == ProtocolType.MQTT)
            {
                MqttMessage mqtt = MqttMessage.DecodeMessage(message.Message);
                return(mqtt.Payload);
            }

            if (message.Protocol == ProtocolType.COAP)
            {
                CoapMessage coap = CoapMessage.DecodeMessage(message.Message);
                return(coap.Payload);
            }

            return(message.Message);
        }
        public async Task <ArraySegment <byte> > ReceiveFullPayload(CancellationToken cancellationToken)
        {
            var receivedBlock2Option      = _firstResponseMessage.Options.First(o => o.Number == CoapMessageOptionNumber.Block2);
            var receivedBlock2OptionValue = _blockValueDecoder.Decode(((CoapMessageOptionUintValue)receivedBlock2Option.Value).Value);

            _logger.Trace(nameof(CoapClientBlockTransferReceiver), "Received Block2 {0}.", FormatBlock2OptionValue(receivedBlock2OptionValue));

            var requestMessage = new CoapMessage
            {
                Type    = CoapMessageType.Confirmable,
                Code    = _requestMessage.Code,
                Token   = _requestMessage.Token,
                Options = new List <CoapMessageOption>(_requestMessage.Options)
            };

            var requestBlock2Option = new CoapMessageOption(CoapMessageOptionNumber.Block2, new CoapMessageOptionUintValue(0));

            requestMessage.Options.Add(requestBlock2Option);

            // Crate a buffer which is pre sized to at least 4 blocks.
            using (var buffer = new MemoryBuffer(receivedBlock2OptionValue.Size * 4))
            {
                buffer.Write(_firstResponseMessage.Payload);

                while (receivedBlock2OptionValue.HasFollowingBlocks)
                {
                    // Patch Block1 so that we get the next chunk.
                    // TODO: Move custom size to client connect options!
                    //receivedBlock2OptionValue.Size = 1024;
                    receivedBlock2OptionValue.Number++;

                    // TODO: Avoid setting value. Create new instead.
                    requestBlock2Option.Value = new CoapMessageOptionUintValue(_blockValueEncoder.Encode(receivedBlock2OptionValue));

                    var response = await _client.RequestAsync(requestMessage, cancellationToken).ConfigureAwait(false);

                    receivedBlock2Option      = response.Options.First(o => o.Number == CoapMessageOptionNumber.Block2);
                    receivedBlock2OptionValue = _blockValueDecoder.Decode(((CoapMessageOptionUintValue)receivedBlock2Option.Value).Value);

                    _logger.Trace(nameof(CoapClientBlockTransferReceiver), "Received Block2 {0}.", FormatBlock2OptionValue(receivedBlock2OptionValue));

                    buffer.Write(response.Payload);
                }

                return(buffer.GetBuffer());
            }
        }
        public async Task TestRetransmissionAttempts()
        {
            // Arrange
            var requestMessage = new CoapMessage
            {
                Id      = 0x1234,
                Type    = CoapMessageType.Confirmable,
                Code    = CoapMessageCode.Get,
                Options = new System.Collections.Generic.List <CoapOption>
                {
                    new Options.UriPath("test")
                }
            };

            var mockClientEndpoint = new Mock <MockEndpoint> {
                CallBase = true
            };

            mockClientEndpoint
            .SetupSequence(c => c.MockReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.Delay(500).ContinueWith(_ => new CoapPacket
            {
                Payload = new CoapMessage
                {
                    Id   = 0x1234,
                    Type = CoapMessageType.Acknowledgement
                }.ToBytes()
            }))
            .Throws(new CoapEndpointException("Endpoint closed"));

            // Act
            using (var mockClient = new CoapClient(mockClientEndpoint.Object))
            {
                var ct = new CancellationTokenSource(MaxTaskTimeout);

                mockClient.RetransmitTimeout     = TimeSpan.FromMilliseconds(200);
                mockClient.MaxRetransmitAttempts = 3;

                await mockClient.SendAsync(requestMessage, ct.Token);
            }

            // Assert
            mockClientEndpoint.Verify(
                cep => cep.SendAsync(It.Is <CoapPacket>(p => p.Payload.SequenceEqual(requestMessage.ToBytes())), It.IsAny <CancellationToken>()),
                Times.Exactly(2));
        }
        public void TestMessageFromUriSpecialChars()
        {
            _message.FromUri("coap://\u307B\u3052.example/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF");

            var expectedOptions = new List <CoapOption>
            {
                new Options.UriHost("xn--18j4d.example"),
                new Options.UriPath("\u3053\u3093\u306b\u3061\u306f"),
            };

            Assert.AreEqual(expectedOptions, _message.Options);

            // Test again but using static CreateFromUri method
            var message = CoapMessage.CreateFromUri("coap://\u307B\u3052.example/%E3%81%93%E3%82%93%E3%81%AB%E3%81%A1%E3%81%AF");

            Assert.AreEqual(expectedOptions, message.Options);
        }
Beispiel #10
0
 public void EnsureAuthentication(CoapMessage message, bool force = false)
 {
     if (!IsAuthenticated || force)
     {
         CoapUri coapUri = new CoapUri(message.ResourceUri.ToString());
         if (!Authenticate(coapUri.TokenType, coapUri.SecurityToken))
         {
             throw new SecurityException("CoAP session not authenticated.");
         }
         else
         {
             IdentityDecoder decoder = new IdentityDecoder(Config.IdentityClaimType, context, Config.Indexes);
             Identity = decoder.Id;
             Indexes  = decoder.Indexes;
         }
     }
 }
Beispiel #11
0
        internal void RemoteUpdate(CoapMessage Request)
        {
            if (!string.IsNullOrEmpty(this.name))
            {
                Log.Informational("Parameter updated.", this.name, Request.From.ToString(),
                                  new KeyValuePair <string, object>("Value", this.Value));
            }

            try
            {
                this.OnRemoteUpdate?.Invoke(this, new CoapRequestEventArgs(Request));
            }
            catch (Exception ex)
            {
                Log.Critical(ex);
            }
        }
Beispiel #12
0
        public void TestMulticastMessagFromMulticastEndpoint()
        {
            // Arrange
            var mockclientEndpoint = new Mock <ICoapEndpoint>();
            var mockPayload        = new Mock <CoapPayload>();

            var messageReceived = new TaskCompletionSource <bool>();

            var expected = new CoapMessage
            {
                Type    = CoapMessageType.NonConfirmable,
                Code    = CoapMessageCode.Get,
                Options = new System.Collections.Generic.List <CoapOption>
                {
                    new CoAPConnector.Options.ContentFormat(CoAPConnector.Options.ContentFormatType.ApplicationLinkFormat)
                },
                Payload = Encoding.UTF8.GetBytes("</.well-known/core>")
            };

            mockPayload
            .Setup(p => p.Payload)
            .Returns(() => expected.Serialise());

            mockclientEndpoint.Setup(c => c.IsMulticast).Returns(true);
            mockclientEndpoint
            .Setup(c => c.SendAsync(It.IsAny <CoapPayload>()))
            .Returns(Task.CompletedTask);
            mockclientEndpoint
            .SetupSequence(c => c.ReceiveAsync())
            .Returns(Task.FromResult(mockPayload.Object))
            .Throws(new CoapEndpointException("Endpoint closed"));


            // Ack
            using (var m_client = new Coapclient(mockclientEndpoint.Object))
            {
                m_client.OnMessageReceived += (s, e) => messageReceived.SetResult(e?.m_Message?.IsMulticast ?? false);
                m_client.Listen(); // enable loop back thingy

                messageReceived.Task.Wait(m_MaxTaskTimeout);
            }

            // Assert
            Assert.True(messageReceived.Task.IsCompleted, "Took too long to receive message");
            Assert.True(messageReceived.Task.Result, "Message is not marked as Multicast");
        }
Beispiel #13
0
        public async Task TestClientResponseWithDelay()
        {
            // Arrange
            var mockClientEndpoint = new Mock <MockEndpoint> {
                CallBase = true
            };

            var expected = new CoapMessage
            {
                Id      = 0x1234,
                Type    = CoapMessageType.Acknowledgement,
                Code    = CoapMessageCode.Content,
                Options = new System.Collections.Generic.List <CoapOption>
                {
                    new Options.ContentFormat(Options.ContentFormatType.ApplicationLinkFormat)
                },
                Payload = Encoding.UTF8.GetBytes("</.well-known/core>")
            };

            mockClientEndpoint
            .SetupSequence(c => c.MockReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.Delay(500).ContinueWith(t => new CoapPacket {
                Payload = expected.ToBytes()
            }))
            .Throws(new CoapEndpointException("Endpoint closed"));

            // Ack
            using (var client = new CoapClient(mockClientEndpoint.Object))
            {
                var ct = new CancellationTokenSource(MaxTaskTimeout);

                client.RetransmitTimeout     = TimeSpan.FromMilliseconds(200);
                client.MaxRetransmitAttempts = 3;
                client.SetNextMessageId(0x1234);

                // Sned message
                var messageId = await client.GetAsync("coap://example.com/.well-known/core", ct.Token);

                // Receive msssage
                await client.GetResponseAsync(messageId, ct.Token);
            }

            // Assert
            mockClientEndpoint.Verify(x => x.ReceiveAsync(It.IsAny <CancellationToken>()), Times.AtLeastOnce);
        }
Beispiel #14
0
        internal byte[] BlockReceived(ClientBase Client, CoapMessage IncomingMessage)
        {
            if (this.payloadResponseStream is null)
            {
                this.payloadResponseStream = new MemoryStream();
            }

            if (IncomingMessage.Payload != null)
            {
                this.payloadResponseStream.Write(IncomingMessage.Payload, 0, IncomingMessage.Payload.Length);
            }

            if (IncomingMessage.Block2.More)
            {
                List <CoapOption> Options = new List <CoapOption>();

                if (!(this.options is null))
                {
                    foreach (CoapOption Option in this.options)
                    {
                        if (!(Option is CoapOptionBlock2))
                        {
                            Options.Add(Option);
                        }
                    }
                }

                Options.Add(new CoapOptionBlock2(IncomingMessage.Block2.Number + 1, false, IncomingMessage.Block2.Size));

                this.endpoint.Transmit(Client, this.destination, Client.IsEncrypted, null,
                                       this.messageType == CoapMessageType.ACK ? CoapMessageType.CON : this.messageType,
                                       this.messageCode, this.token, true, null, 0, this.blockSize, this.resource, this.callback, this.state,
                                       this.payloadResponseStream, this.credentials, Options.ToArray());

                return(null);
            }
            else
            {
                byte[] Result = this.payloadResponseStream.ToArray();
                this.payloadResponseStream.Dispose();
                this.payloadResponseStream = null;

                return(Result);
            }
        }
Beispiel #15
0
        public void Complete(CoapMessage message)
        {
            if (message == null)
            {
                throw new ArgumentNullException(nameof(message));
            }

#if NET452
            // To prevent deadlocks it is required to call the _TrySetResult_ method
            // from a new thread because the awaiting code will not(!) be executed in
            // a new thread automatically (due to await). Furthermore _this_ thread will
            // do it. But _this_ thread is also reading incoming packets -> deadlock.
            // NET452 does not support RunContinuationsAsynchronously
            Task.Run(() => _taskCompletionSource.TrySetResult(message));
#else
            _taskCompletionSource.TrySetResult(message);
#endif
        }
Beispiel #16
0
        public void TestMessageFromUri()
        {
            _message.FromUri("coap://example.net/.well-known/core");

            var expectedOptions = new List <CoapOption>
            {
                new Options.UriHost("example.net"),
                new Options.UriPath(".well-known"),
                new Options.UriPath("core"),
            };

            Assert.IsTrue(expectedOptions.SequenceEqual(_message.Options));

            // Test again but using static CreateFromUri method
            var message = CoapMessage.CreateFromUri("coap://example.net/.well-known/core");

            Assert.IsTrue(expectedOptions.SequenceEqual(message.Options));
        }
Beispiel #17
0
        internal void ResponseReceived(ClientBase Client, CoapMessage Response)
        {
            this.responseReceived = true;

            if (!(this.callback is null))
            {
                try
                {
                    this.callback(this.endpoint, new CoapResponseEventArgs(Client, this.endpoint,
                                                                           Response.Type != CoapMessageType.RST && (int)Response.Code >= 0x40 && (int)Response.Code <= 0x5f,
                                                                           this.state, Response, null));
                }
                catch (Exception ex)
                {
                    this.endpoint.Exception(ex);
                    Log.Critical(ex);
                }
            }
        }
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            session.IsAuthenticated = Channel.IsAuthenticated;
            logger?.LogDebugAsync($"CoAP protocol channel opening with session authenticated '{session.IsAuthenticated}'.").GetAwaiter();

            try
            {
                if (!Channel.IsAuthenticated && e.Message != null)
                {
                    CoapMessage msg     = CoapMessage.DecodeMessage(e.Message);
                    CoapUri     coapUri = new CoapUri(msg.ResourceUri.ToString());
                    session.IsAuthenticated = session.Authenticate(coapUri.TokenType, coapUri.SecurityToken);
                    logger?.LogDebugAsync($"CoAP protocol channel opening session authenticated '{session.IsAuthenticated}' by authenticator.").GetAwaiter();
                }

                if (session.IsAuthenticated)
                {
                    IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context, session.Config.Indexes);
                    session.Identity = decoder.Id;
                    session.Indexes  = decoder.Indexes;
                    logger?.LogDebugAsync($"CoAP protocol channel opening with session identity '{session.Identity}'.").GetAwaiter();

                    UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity, session.Config.IdentityClaimType, Channel.TypeId, "COAP", "Granted", DateTime.UtcNow);
                    userAuditor?.WriteAuditRecordAsync(record).Ignore();
                }
            }
            catch (Exception ex)
            {
                logger?.LogErrorAsync(ex, $"CoAP adapter opening channel '{Channel.Id}'.").GetAwaiter();
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }

            if (!session.IsAuthenticated && e.Message != null)
            {
                //close the channel
                logger?.LogWarningAsync("CoAP adpater closing due to unauthenticated user.");
                Channel.CloseAsync().Ignore();
            }
            else
            {
                dispatcher = new CoapRequestDispatcher(session, Channel, config, graphManager, this.logger);
            }
        }
        public void Encode_And_Decode_Payload_Length_12()
        {
            var optionBuilder = new CoapMessageOptionFactory();

            var message = new CoapMessage
            {
                Type    = CoapMessageType.Confirmable,
                Code    = CoapMessageCodes.Put,
                Id      = ushort.MaxValue,
                Payload = Encoding.UTF8.GetBytes("123456789012")
            };

            message.Options = new List <CoapMessageOption>
            {
                optionBuilder.CreateUriPort(5648)
            };

            Enocde_And_Decode_Internal(message);
        }
Beispiel #20
0
        public void TestclientResponseGet()
        {
            // Arrange
            var expected = new CoapMessage
            {
                Type    = CoapMessageType.Acknowledgement,
                Code    = CoapMessageCode.Content,
                Options = new System.Collections.Generic.List <CoapOption>
                {
                    new CoAPConnector.Options.ContentFormat(CoAPConnector.Options.ContentFormatType.ApplicationLinkFormat)
                },
                Payload = System.Text.Encoding.UTF8.GetBytes("</.well-known/core>")
            };

            var mockPayload = new Mock <CoapPayload>();

            mockPayload
            .Setup(p => p.Payload)
            .Returns(() => expected.Serialise());

            var mock = new Mock <ICoapEndpoint>();

            mock
            .Setup(c => c.SendAsync(It.IsAny <CoapPayload>()))
            // Copy the ID from the message sent out, to the message for the m_client to receive
            .Callback <CoapPayload>((p) => expected.Id = p.MessageId)
            .Returns(Task.CompletedTask);
            mock
            .SetupSequence(c => c.ReceiveAsync())
            .Returns(Task.FromResult(mockPayload.Object))
            .Throws(new CoapEndpointException("Endpoint closed"));

            // Act
            var api = getApi(mock);
            Dictionary <string, object> agr = new Dictionary <string, object>();
            string uri = "coap://example.com/.well-known/core";

            agr.Add("URI", uri);
            api.ReceiveAsync(agr).Wait();

            // Assert
            mock.Verify(x => x.ReceiveAsync(), Times.AtLeastOnce);
        }
Beispiel #21
0
        /// <summary>
        /// Executes the DELETE method on the resource.
        /// </summary>
        /// <param name="Request">CoAP Request</param>
        /// <param name="Response">CoAP Response</param>
        /// <exception cref="CoapException">If an error occurred when processing the method.</exception>
        public void DELETE(CoapMessage Request, CoapResponse Response)
        {
            if (this.state != Lwm2mState.Bootstrap)
            {
                if (this.IsFromBootstrapServer(Request))
                {
                    this.State = Lwm2mState.Bootstrap;
                }
                else
                {
                    Response.RST(CoapCode.Unauthorized);
                    return;
                }
            }

            Task T = this.DeleteBootstrapInfo();

            Response.ACK(CoapCode.Deleted);
        }
        public CoapMessage Convert(CoapRequest request)
        {
            if (request is null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            var message = new CoapMessage
            {
                Type    = CoapMessageType.Confirmable,
                Code    = GetMessageCode(request.Method),
                Options = new List <CoapMessageOption>()
            };

            message.Options.Add(_optionFactory.CreateUriPath(request.Uri));
            message.Options.Add(_optionFactory.CreateUriPort(5648));

            return(message);
        }
Beispiel #23
0
        public static CoapMessage ToCoapMessage(this OicMessage message)
        {
            var coapMessage = new CoapMessage
            {
                Payload = message.Content,
                Token   = BitConverter.GetBytes(message.RequestId),
            };

            if (message.ContentType != OicMessageContentType.None)
            {
                coapMessage.Options.Add(new CoAPNet.Options.ContentFormat(message.ContentType.ToCoapContentFormat()));
            }

            if (message.ToUri != null)
            {
                if (message.ToUri.IsAbsoluteUri)
                {
                    coapMessage.SetUri(new UriBuilder(message.ToUri)
                    {
                        Scheme = "coap"
                    }.Uri);
                }
                else
                {
                    coapMessage.SetUri(message.ToUri, UriComponents.PathAndQuery);
                }
            }

            if (message is OicRequest request)
            {
                coapMessage.Code = request.Operation.ToCoapMessageCode();
                foreach (var contentType in request.Accepts)
                {
                    coapMessage.Options.Add(new CoAPNet.Options.Accept(contentType.ToCoapContentFormat()));
                }
            }
            else if (message is OicResponse response)
            {
                coapMessage.Code = response.ResposeCode.ToCoapMessageCode();
            }

            return(coapMessage);
        }
Beispiel #24
0
        public async Task TestClientResponse()
        {
            // Arrange
            var mockClientEndpoint = new Mock <MockEndpoint> {
                CallBase = true
            };

            var expected = new CoapMessage
            {
                Id      = 0x1234,
                Type    = CoapMessageType.Acknowledgement,
                Code    = CoapMessageCode.Content,
                Options = new System.Collections.Generic.List <CoapOption>
                {
                    new Options.ContentFormat(Options.ContentFormatType.ApplicationLinkFormat)
                },
                Payload = Encoding.UTF8.GetBytes("</.well-known/core>")
            };

            mockClientEndpoint
            .SetupSequence(c => c.MockReceiveAsync())
            .Returns(Task.FromResult(new CoapPacket {
                Payload = expected.Serialise()
            }))
            .Throws(new CoapEndpointException("disposed"));

            // Ack
            using (var client = new CoapClient(mockClientEndpoint.Object))
            {
                var ct = new CancellationTokenSource(MaxTaskTimeout);

                client.SetNextMessageId(0x1234);
                // Sned message
                var messageId = await client.GetAsync("coap://example.com/.well-known/core", ct.Token);

                // Receive msssage
                await client.GetResponseAsync(messageId, ct.Token).ConfigureAwait(false);
            }

            // Assert
            mockClientEndpoint.Verify(x => x.ReceiveAsync(), Times.AtLeastOnce);
        }
        void Enocde_And_Decode_Internal(CoapMessage message)
        {
            var messageEncoder = new CoapMessageEncoder();
            var messageBuffer  = messageEncoder.Encode(message);

            var messageDecoder = new CoapMessageDecoder(new CoapNetLogger());
            var decodedMessage = messageDecoder.Decode(messageBuffer);

            Assert.AreEqual(message.Type, decodedMessage.Type);
            Assert.AreEqual(message.Code, decodedMessage.Code);
            CollectionAssert.AreEqual(message.Token, decodedMessage.Token);
            CollectionAssert.AreEqual(message.Options, decodedMessage.Options);

            if (message.Payload.Array == null && message.Payload.Array == null)
            {
                return;
            }

            CollectionAssert.AreEqual(message.Payload.ToArray(), decodedMessage.Payload.ToArray());
        }
        public void Encode_And_Decode_Full()
        {
            var optionBuilder = new CoapMessageOptionFactory();

            var message = new CoapMessage
            {
                Type    = CoapMessageType.Confirmable,
                Code    = CoapMessageCodes.Post,
                Id      = 0x5876,
                Token   = new byte[] { 1, 2, 3, 4 },
                Payload = Encoding.UTF8.GetBytes("payloadOver13chars")
            };

            message.Options = new List <CoapMessageOption>
            {
                optionBuilder.CreateUriPort(5648)
            };

            Enocde_And_Decode_Internal(message);
        }
        public void Encode_And_Decode_No_Payload()
        {
            var optionBuilder = new CoapMessageOptionFactory();

            var message = new CoapMessage
            {
                Type    = CoapMessageType.Acknowledgement,
                Code    = CoapMessageCodes.Get,
                Id      = 0x5876,
                Token   = new byte[] { 1, 2, 3, 4 },
                Payload = null
            };

            message.Options = new List <CoapMessageOption>
            {
                optionBuilder.CreateUriPort(50)
            };

            Enocde_And_Decode_Internal(message);
        }
        public void Encode_And_Decode_No_Token()
        {
            var optionBuilder = new CoapMessageOptionFactory();

            var message = new CoapMessage
            {
                Type    = CoapMessageType.NonConfirmable,
                Code    = CoapMessageCodes.Put,
                Id      = 0x5876,
                Token   = null,
                Payload = null
            };

            message.Options = new List <CoapMessageOption>
            {
                optionBuilder.CreateUriPort(66000)
            };

            Enocde_And_Decode_Internal(message);
        }
Beispiel #29
0
        private void Channel_OnOpen(object sender, ChannelOpenEventArgs e)
        {
            session.IsAuthenticated = Channel.IsAuthenticated;

            try
            {
                if (!Channel.IsAuthenticated && e.Message != null)
                {
                    CoapMessage msg     = CoapMessage.DecodeMessage(e.Message);
                    CoapUri     coapUri = new CoapUri(msg.ResourceUri.ToString());
                    session.IsAuthenticated = session.Authenticate(coapUri.TokenType, coapUri.SecurityToken);
                }

                if (session.IsAuthenticated)
                {
                    IdentityDecoder decoder = new IdentityDecoder(session.Config.IdentityClaimType, context, session.Config.Indexes);
                    session.Identity = decoder.Id;
                    session.Indexes  = decoder.Indexes;

                    UserAuditRecord record = new UserAuditRecord(Channel.Id, session.Identity, session.Config.IdentityClaimType, Channel.TypeId, "COAP", "Granted", DateTime.UtcNow);
                    userAuditor?.WriteAuditRecordAsync(record).Ignore();
                }
            }
            catch (Exception ex)
            {
                logger?.LogError(ex, $"CoAP adapter opening channel '{Channel.Id}'.");
                OnError?.Invoke(this, new ProtocolAdapterErrorEventArgs(Channel.Id, ex));
            }

            if (!session.IsAuthenticated && e.Message != null)
            {
                //close the channel
                logger?.LogInformation($"CoAP adapter user not authenticated; must close channel '{Channel.Id}'.");
                Channel.CloseAsync().Ignore();
            }
            else
            {
                dispatcher = new CoapRequestDispatcher(session, Channel);
            }
        }
Beispiel #30
0
        public async Task TestSendMulticastMessagToExplicitMulticastEndpoint()
        {
            // Arrange
            var mockClientEndpoint = new Mock <MockEndpoint> {
                CallBase = true
            };

            mockClientEndpoint
            .Setup(e => e.SendAsync(It.IsAny <CoapPacket>(), It.IsAny <CancellationToken>()))
            .CallBase()
            .Verifiable("Message was not sent via multicast endpoint");

            var destEndpoint = new CoapEndpoint {
                IsMulticast = true
            };

            var message = new CoapMessage
            {
                IsMulticast = true,
                Type        = CoapMessageType.NonConfirmable,
                Code        = CoapMessageCode.Get,
                Options     = new System.Collections.Generic.List <CoapOption>
                {
                    new Options.ContentFormat(Options.ContentFormatType.ApplicationLinkFormat)
                },
                Payload = Encoding.UTF8.GetBytes("</.well-known/core>")
            };


            // Ack
            using (var client = new CoapClient(mockClientEndpoint.Object))
            {
                var ct = new CancellationTokenSource(MaxTaskTimeout);

                await client.SendAsync(message, destEndpoint, ct.Token);
            }

            // Assert
            Mock.Verify(mockClientEndpoint);
        }