public async Task Read_BlockWiseCoapMessage_WithExtentionMethod(
            [Values(16, 32, 64, 128, 256, 512, 1024)] int blockSize,
            [Range(1, 2)] int blocks,
            [Values] bool lastHalfblock)
        {
            // Arrange
            int totalBytes  = (blocks * blockSize) + (lastHalfblock ? blockSize / 2 : 0);
            int totalBlocks = ((totalBytes - 1) / blockSize) + 1;

            var baseRequest = new CoapMessage
            {
                Code = CoapMessageCode.Get,
                Type = CoapMessageType.Confirmable,
            };

            baseRequest.SetUri("/status", UriComponents.Path);

            var baseResponse = new CoapMessage
            {
                Code = CoapMessageCode.Content,
                Type = CoapMessageType.Acknowledgement,
            };

            var helper = new BlockWiseTestHelper
            {
                BlockSize  = blockSize,
                TotalBytes = totalBytes
            };

            var mockClientEndpoint = new Mock <MockBlockwiseEndpoint>(baseResponse, blockSize, totalBytes)
            {
                CallBase = true
            };

            helper.AssertReadResponseCorrespondance(mockClientEndpoint, 1)
            .AssertInitialRequest(mockClientEndpoint);

            byte[] result;
            // Act
            using (var client = new CoapClient(mockClientEndpoint.Object))
            {
                var ct = new CancellationTokenSource(MaxTaskTimeout);

                client.SetNextMessageId(1);

                var identifier = await client.SendAsync(baseRequest, ct.Token);

                var response = await client.GetResponseAsync(identifier, ct.Token);

                result = response.GetCompletedBlockWisePayload(client, baseRequest);
            }

            // Assert
            Assert.That(result, Is.EqualTo(BlockWiseTestHelper.ByteRange(0, totalBytes)), "Incorrect payload read");

            mockClientEndpoint.Verify();
        }
        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 #3
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);
        }
Beispiel #4
0
        public IObservable <Message> SendMessage(Message message, ICoapEndpoint endpoint)
        {
            if (message is null)
            {
                return(Observable.Empty <Message>());
            }

            var coapMessage    = message.ToCoapMessage();
            var messageContext = coapMessage.CreateBlockWiseContext(_coapClient);

            return(Observable.Create <Message>(observer =>
            {
                var cts = new CancellationTokenSource();
                Task.Run(async() =>
                {
                    try
                    {
                        if (coapMessage.IsBlockWise())
                        {
                            using (var writer = new CoapBlockStreamWriter(messageContext, endpoint))
                                await message.PayloadStream.CopyToAsync(writer, writer.BlockSize);
                        }
                        else
                        {
                            var id = await _coapClient.SendAsync(coapMessage, endpoint, cts.Token);
                            messageContext = new CoapBlockWiseContext(_coapClient, coapMessage, await _coapClient.GetResponseAsync(id, cts.Token));
                        }

                        var response = messageContext.Response.ToMessage();

                        if (messageContext.Response.IsBlockWise())
                        {
                            var memoryStream = new MemoryStream();

                            using (var reader = new CoapBlockStreamReader(messageContext, endpoint))
                                reader.CopyTo(memoryStream);

                            response.Payload = memoryStream.ToArray();
                        }

                        observer.OnNext(response);

                        observer.OnCompleted();
                    }
                    catch (Exception ex)
                    {
                        observer.OnError(ex);
                    }
                });

                return cts.Cancel;
            }));
        }