Ejemplo n.º 1
0
        public void PivExhaustion()
        {
            SecurityContext context  = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null);
            SecurityContext context2 = SecurityContext.DeriveGroupContext(secret2, groupId2, clientId, AlgorithmValues.EdDSA, _clientSign1, null, null);

            for (int i = 0; i < 10; i++)
            {
                context.Sender.IncrementSequenceNumber();
            }

            context.Sender.MaxSequenceNumber = 10;
            context.OscoreEvents            += ClientEventHandler;

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 20
            };

            Response r = client.Get();

            Assert.IsTrue(trigger.WaitOne(1000));
            Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _clientCallbackCode);

            _clientEventChoice = 1;
            client.Timeout     = 1000 * 60;
            r = client.Get();
            Assert.AreEqual(OscoreEvent.EventCode.UnknownGroupIdentifier, _callbackCode);
        }
Ejemplo n.º 2
0
        public void GetUnicastV6()
        {
            Uri        uri;
            CoapClient client;
            Response   response;

            IPAddress[] addresses = Dns.GetHostAddresses("localhost");
            IPAddress   addr      = null;

            foreach (IPAddress a in addresses)
            {
                if (a.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    addr = a;
                    break;
                }
            }

            uri = new Uri($"coap://[{addr}]:{_serverPort}/{UnicastTarget}");

            client   = new CoapClient(uri);
            response = client.Get();
            Assert.IsNotNull(response);
            Assert.AreEqual(UnicastResponse, response.ResponseText);
        }
Ejemplo n.º 3
0
        public void TestMulticastIPv6_Offset()
        {
            Uri             uri;
            CoapClient      client;
            List <Response> responseList = new List <Response>();
            AutoResetEvent  trigger      = new AutoResetEvent(false);

            if (!SupportsIPV6())
            {
                Assert.Inconclusive("System does not support IP v6");
            }


            uri    = new Uri($"coap://[{multicastAddress2}]:{_serverPort + PortJump}/{MulticastTarget}");
            client = new CoapClient(uri);
            client.UseNONs();
            client.GetAsync(r => {
                responseList.Add(r);
                trigger.Set();
            });

            Assert.IsTrue(trigger.WaitOne(2 * 1000));

            Console.WriteLine($"response count = {responseList.Count}");
            Assert.IsTrue(responseList.Count == 1);
            foreach (Response r in responseList)
            {
                Assert.AreEqual(StatusCode.Content, r.StatusCode);
                Assert.AreEqual(MulticastResponse, r.ResponseText);
            }
        }
Ejemplo n.º 4
0
        public void TestMulticastV4_Offset()
        {
            Uri        uri;
            CoapClient client;

            //  Check that multicast returns on multicast

            List <Response> responseList = new List <Response>();
            AutoResetEvent  trigger      = new AutoResetEvent(false);

            uri    = new Uri($"coap://{multicastAddress}:{_serverPort + PortJump}/{MulticastTarget}");
            client = new CoapClient(uri);
            client.UseNONs();
            client.GetAsync(r => {
                responseList.Add(r);
                trigger.Set();
            });

            trigger.WaitOne(1000);

            Assert.IsTrue(responseList.Count == 1);
            foreach (Response r in responseList)
            {
                Assert.AreEqual(StatusCode.Content, r.StatusCode);
                Assert.AreEqual(MulticastResponse, r.ResponseText);
            }
        }
Ejemplo n.º 5
0
        public async Task TestReceiveMulticastMessagFromMulticastEndpoint()
        {
            // Arrange
            var mockClientEndpoint = new Mock <MockEndpoint> {
                CallBase = true
            };

            var messageReceived = new TaskCompletionSource <bool>();

            var expected = new CoapMessage
            {
                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>")
            };

            mockClientEndpoint.Setup(c => c.IsMulticast).Returns(true);
            mockClientEndpoint
            .Setup(c => c.MockSendAsync(It.IsAny <CoapPacket>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);
            mockClientEndpoint
            .SetupSequence(c => c.MockReceiveAsync(It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new CoapPacket {
                Payload = expected.ToBytes()
            }))
            .Throws(new CoapEndpointException("Endpoint closed"));


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

                ct.Token.Register(() => messageReceived.TrySetCanceled());

                try
                {
                    while (true)
                    {
                        var received = await client.ReceiveAsync(ct.Token);

                        messageReceived.TrySetResult(received.Message?.IsMulticast ?? false);
                    }
                }
                catch (CoapEndpointException)
                {
                    Debug.WriteLine($"Caught CoapEndpointException", nameof(TestReceiveMulticastMessagFromMulticastEndpoint));
                }

                await messageReceived.Task;
            }

            // Assert
            Assert.IsTrue(messageReceived.Task.IsCompleted, "Took too long to receive message");
            Assert.IsTrue(messageReceived.Task.Result, "Message is not marked as Multicast");
        }
Ejemplo n.º 6
0
        public void CancelReceiveAsync()
        {
            // Arrange
            var endpoint = new CoapUdpEndPoint(IPAddress.Loopback);

            var  safetyCt = new CancellationTokenSource(MaxTaskTimeout);
            var  testCt   = new CancellationTokenSource(TimeSpan.FromSeconds(1));
            Task receiveTask1;
            Task receiveTask2;
            Task receiveTask3;

            // Ack
            using (var client = new CoapClient(endpoint))
            {
                receiveTask1 = client.ReceiveAsync(testCt.Token);
                receiveTask2 = client.ReceiveAsync(testCt.Token);
                receiveTask3 = client.ReceiveAsync(testCt.Token);

                Task.Run(() =>
                {
                    // Assert
                    Assert.ThrowsAsync <TaskCanceledException>(
                        async() => await receiveTask1, $"{nameof(CoapClient.ReceiveAsync)} did not throw an {nameof(OperationCanceledException)} when the CancelationToken was canceled.");
                    Assert.ThrowsAsync <TaskCanceledException>(
                        async() => await receiveTask2, $"{nameof(CoapClient.ReceiveAsync)} did not throw an {nameof(OperationCanceledException)} when the CancelationToken was canceled.");
                    Assert.ThrowsAsync <TaskCanceledException>(
                        async() => await receiveTask3, $"{nameof(CoapClient.ReceiveAsync)} did not throw an {nameof(OperationCanceledException)} when the CancelationToken was canceled.");
                }, safetyCt.Token).Wait();
            }

            Assert.That(testCt.IsCancellationRequested, Is.True, "The test's CancellationToken should have timed out.");
            Assert.That(safetyCt.IsCancellationRequested, Is.False, "The test's safety CancellationToken timed out");
        }
Ejemplo n.º 7
0
        public void MutiTierTest()
        {
            CoapClient client = new CoapClient(new Uri($"coap://localhost:{_port}/ps"));
            Response   resp   = client.Get();

            Assert.AreEqual(StatusCode.Content, resp.StatusCode);
            Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType);
            List <WebLink> links = LinkFormat.Parse(resp.PayloadString).ToList();

            Assert.AreEqual(0, links.Count);

            resp = client.Post($"<middle>;ct={MediaType.ApplicationLinkFormat}", MediaType.ApplicationLinkFormat);
            Assert.AreEqual(StatusCode.Created, resp.StatusCode);
            Assert.AreEqual("ps/middle", resp.LocationPath);

            client.UriPath = "/ps/middle";
            resp           = client.Post($"<topic1>;ct={MediaType.TextPlain}", MediaType.ApplicationLinkFormat);
            Assert.AreEqual(StatusCode.Created, resp.StatusCode);
            Assert.AreEqual("ps/middle/topic1", resp.LocationPath);

            resp = client.Post($"<topic2>;ct={MediaType.ApplicationCbor}", MediaType.ApplicationLinkFormat);
            Assert.AreEqual(StatusCode.Created, resp.StatusCode);
            Assert.AreEqual("ps/middle/topic2", resp.LocationPath);

            client.UriPath = "";
            resp           = client.Get();
            Assert.AreEqual(StatusCode.Content, resp.StatusCode);
            Assert.AreEqual(MediaType.ApplicationLinkFormat, resp.ContentType);
            links = LinkFormat.Parse(resp.PayloadString).ToList();
            Assert.AreEqual(3, links.Count);
            string[] linkStrings = resp.PayloadString.Split(',');

            Assert.Contains("</ps/middle/topic2>;ct=60;obs", linkStrings);
            Assert.Contains("</ps/middle/topic1>;ct=0;obs", linkStrings);;
        }
Ejemplo n.º 8
0
        public void CancelReceiveAsync()
        {
            // Arrange
            var endpoint = new NonDisposableEndpoint();

            var  safetyCt = new CancellationTokenSource(MaxTaskTimeout);
            var  testCt   = new CancellationTokenSource(MaxTaskTimeout / 2);
            Task receiveTask1;
            Task receiveTask2;
            Task receiveTask3;

            // Ack
            using (var client = new CoapClient(endpoint))
            {
                receiveTask1 = client.ReceiveAsync(testCt.Token);
                receiveTask2 = client.ReceiveAsync(testCt.Token);
                receiveTask3 = client.ReceiveAsync(testCt.Token);

                Task.Run(() =>
                {
                    // Assert
                    Assert.ThrowsAsync <TaskCanceledException>(
                        async() => await receiveTask1, $"{nameof(CoapClient.ReceiveAsync)} did not throw an {nameof(CoapEndpointException)} when {nameof(CoapClient)} was disposed.");
                    Assert.ThrowsAsync <TaskCanceledException>(
                        async() => await receiveTask2, $"{nameof(CoapClient.ReceiveAsync)} did not throw an {nameof(CoapEndpointException)} when {nameof(CoapClient)} was disposed.");
                    Assert.ThrowsAsync <TaskCanceledException>(
                        async() => await receiveTask3, $"{nameof(CoapClient.ReceiveAsync)} did not throw an {nameof(CoapEndpointException)} when {nameof(CoapClient)} was disposed.");
                }, safetyCt.Token).Wait();
            }

            Assert.That(testCt.IsCancellationRequested, Is.True, "The test's CancellationToken should have timed out.");
            Assert.That(safetyCt.IsCancellationRequested, Is.False, "The test's safety CancellationToken timed out");
        }
Ejemplo n.º 9
0
        public void TestCancelWithNotify()
        {
            //  Check what happens with out of order delivery

            Uri        uri    = new Uri($"coap://localhost:{_serverPort}/{target1}");
            CoapClient client = new CoapClient(uri);

            AutoResetEvent trigger      = new AutoResetEvent(false);
            Response       nextResponse = null;
            int            lastObserve  = -1;

            _expected = "No Content Yet";
            CoapObserveRelation obs1 = client.Observe(response => {
                nextResponse = response;
                trigger.Set();
            });

            Assert.IsFalse(obs1.Canceled);

            Assert.IsTrue(trigger.WaitOne(1000));
            Assert.IsTrue(Code.IsSuccess(nextResponse.Code));
            Assert.AreEqual(_expected, nextResponse.ResponseText);
            Assert.IsTrue(nextResponse.HasOption(OptionType.Observe));
            Assert.IsTrue(nextResponse.Observe.HasValue);
            int oNumber = nextResponse.Observe.Value;

            Assert.IsTrue(oNumber > lastObserve);
            lastObserve = oNumber;

            _resource.Changed();
            Assert.IsTrue(trigger.WaitOne(1000));
            Assert.IsTrue(Code.IsSuccess(nextResponse.Code));
            Assert.AreEqual(_expected, nextResponse.ResponseText);
            Assert.IsTrue(nextResponse.HasOption(OptionType.Observe));
            Assert.IsTrue(nextResponse.Observe.HasValue);
            oNumber = nextResponse.Observe.Value;
            Assert.IsTrue(oNumber > lastObserve);
            lastObserve = oNumber;

            _resource.Changed();
            Assert.IsTrue(trigger.WaitOne(1000));
            Assert.IsTrue(Code.IsSuccess(nextResponse.Code));
            Assert.AreEqual(_expected, nextResponse.ResponseText);
            Assert.IsTrue(nextResponse.HasOption(OptionType.Observe));
            Assert.IsTrue(nextResponse.Observe.HasValue);
            oNumber = nextResponse.Observe.Value;
            Assert.IsTrue(oNumber > lastObserve);
            lastObserve = oNumber;

            _resource.Canceled(true);
            Assert.IsTrue(trigger.WaitOne(1000));
            Assert.IsTrue(!Code.IsSuccess(nextResponse.Code));
            Assert.AreEqual(null, nextResponse.ResponseText);
            Assert.IsFalse(nextResponse.HasOption(OptionType.Observe));

            _resource.Changed();
            Assert.IsFalse(trigger.WaitOne(1000));

            client = null;
        }
        public void PostTo()
        {
            CoapClient c = new CoapClient(Program.Host)
            {
                UriPath  = "/.well-known/core",
                UriQuery = "ep=node1",
                Timeout  = 5000,
                EndPoint = EndPoints.First()
            };

            Response r = c.Post(new byte[] { }, MediaType.ApplicationLinkFormat);

            if (r == null)
            {
                Console.WriteLine("No response received");
            }
            else
            {
                if (r.StatusCode != StatusCode.Changed)
                {
                    Console.WriteLine("Incorrect response");
                }

                Console.WriteLine(Utils.ToString(r));
            }
        }
Ejemplo n.º 11
0
        static void RunTest5_4_1()
        {
            CoapClient request = new CoapClient(Program.Host + "/oscore/hello/1")
            {
                Timeout = 2000
            };

            Response response = request.Post(new byte[] { 0x4a }, MediaType.TextPlain);

            if (response == null)
            {
                Console.WriteLine("Failed to receive response");
                return;
            }

            if (response.StatusCode != StatusCode.Changed)
            {
                Console.WriteLine($"Content type should be 2.04 not {response.StatusCode}");
            }

            if (response.PayloadSize != 1 || response.Payload[0] != 0x4a)
            {
                Console.WriteLine("Payload for the package is wrong - should be 0x4a");
            }

            Console.WriteLine($"Response Message:\n{Utils.ToString(response)}");
        }
Ejemplo n.º 12
0
        public async Task TestClientRequest()
        {
            // Arrange
            var mockClientEndpoint = new Mock <MockEndpoint>()
            {
                CallBase = true
            };

            mockClientEndpoint
            .Setup(c => c.MockSendAsync(It.IsAny <CoapPacket>(), It.IsAny <CancellationToken>()))
            .Returns(Task.CompletedTask);

            // Act
            using (var client = new CoapClient(mockClientEndpoint.Object))
            {
                var ct = new CancellationTokenSource(MaxTaskTimeout);
                await client.SendAsync(new CoapMessage
                {
                    Type = CoapMessageType.NonConfirmable,
                    Code = CoapMessageCode.None
                }, ct.Token);
            }

            // Assert
            mockClientEndpoint.Verify(cep => cep.SendAsync(It.IsAny <CoapPacket>(), It.IsAny <CancellationToken>()));
        }
        static void RunTest15(string[] cmds)
        {
            //  Do it as a third party.
            CoapClient cl = new CoapClient(Program.Host)
            {
                UriPath = ResourceLookup,
                Timeout = 20 * 1000
            };
            Response r1 = cl.Get(MediaType.ApplicationLinkFormat);

            if (r1 == null)
            {
                Console.WriteLine("No response message retrieved");
                return;
            }

            if (r1.StatusCode != StatusCode.Content)
            {
                Console.WriteLine("Incorrect return code");
            }

            if (r1.StatusCode < StatusCode.BadRequest)
            {
                if (r1.ContentFormat != MediaType.ApplicationLinkFormat)
                {
                    Console.WriteLine("Incorrect Media Type");
                }
            }

            Console.WriteLine(Utils.ToString(r1));
        }
        static void RunTest4(string[] cmds)
        {
            //  Do it as a third party.
            CoapClient cl = new CoapClient(Program.Host)
            {
                UriPath  = ResourceRegister,
                UriQuery = "ep=node2",
                Timeout  = 20 * 1000
            };
            Response r1 = cl.Post(
                "</temp>;rt=\"temperature\";ct=0," +
                "</light>;rt=\"light-lux\";ct=0," +
                "</t>;anchor=\"sensors/temp\";rel=\"alternate\"," +
                "<http://www.example.com/sensors/t123>;anchor=\"sensors/temp\";rel=\"describedby\"",
                MediaType.ApplicationLinkFormat);

            if (r1 == null)
            {
                Console.WriteLine("No response message retrieved");
                return;
            }

            Test4Location = r1.LocationPath;
            return;
        }
Ejemplo n.º 15
0
        static void ProductCall()
        {
            // Create a new client
            var client = new CoapClient();

            // Set the Uri to visit
            client.Uri = new Uri("coap://127.0.0.1:5683/products");

            // Build the data
            MemoryStream stream = new MemoryStream();

            // Example product
            dynamic product = new JObject();

            product.name  = "Example Product";
            product.price = 120.35;

            // Get JSON object from example product
            var response = client.Post(product.ToString(), MediaType.ApplicationJson);

            Console.WriteLine("Wrote product: {0}", product.ToString());

            // Get the response
            Console.WriteLine("Response from GET: {0}", response.PayloadString);
            Console.ReadLine();
        }
Ejemplo n.º 16
0
        public void ServerNewSenderGroup()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1,
                                                                         new byte[][] { serverId, serverId2 }, new OneKey[] { _serverSign1, _serverSign1 });
            SecurityContext serverContext = SecurityContext.DeriveGroupContext(secret, groupId1, serverId, AlgorithmValues.EdDSA, _serverSign1,
                                                                               new byte[][] { clientId2, clientId }, new OneKey[] { _clientSign2, _clientSign1 });

            _server.SecurityContexts.Add(serverContext);
            serverContext.OscoreEvents += ServerEventHandler;

            serverContext.Sender.SequenceNumber = 10;

            serverContext.Sender.MaxSequenceNumber = 10;

            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = context,
                Timeout       = 60 * 1000
            };

            _serverEventChoice = 4;
            client.Observe(o => { Assert.AreEqual("/abc", o.PayloadString); });

            Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _callbackCode);
        }
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="_cc">existing coap client</param>
 /// <param name="loadAutomatically">Load GatewayInfo object automatically (default: true)</param>
 public GatewayController(CoapClient _cc, bool loadAutomatically = true)
 {
     cc = _cc;
     if (loadAutomatically)
     {
         GetGatewayInfo();
     }
 }
Ejemplo n.º 18
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="coapClient">existing coap client</param>
 /// <param name="loadAutomatically">Load GatewayInfo object automatically (default: true)</param>
 public GatewayController(CoapClient coapClient, bool loadAutomatically = true)
 {
     _coapClient = coapClient;
     if (loadAutomatically)
     {
         GetGatewayInfo();
     }
 }
Ejemplo n.º 19
0
        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();
        }
        private static void CleanAll(string[] cmds)
        {
            CoapClient            c = new CoapClient(Program.Host);
            IEnumerable <WebLink> d = c.Discover("rt=core.rd*", MediaType.ApplicationLinkFormat);

            string endpointRegister = null;
            string endpointLookup   = null;
            string groupRegister    = null;
            string groupLookup      = null;
            string resourceLookup   = null;

            foreach (WebLink w in d)
            {
                foreach (string s in w.Attributes.GetResourceTypes())
                {
                    switch (s)
                    {
                    case "core.rd":
                        endpointRegister = w.Uri;
                        break;

                    case "core.rd-lookup-res":
                        resourceLookup = w.Uri;
                        break;

                    case "core.rd-group":
                        groupRegister = w.Uri;
                        break;

                    case "core.rd-lookup-gp":
                        groupLookup = w.Uri;
                        break;

                    case "core.rd-lookup-ep":
                        endpointLookup = w.Uri;
                        break;
                    }
                }
            }

            if (groupLookup != null)
            {
                d = c.Discover(groupLookup, null, MediaType.ApplicationLinkFormat);
                foreach (WebLink w in d)
                {
                    c.UriPath = w.Uri;
                    c.Delete();
                }
            }

            d = c.Discover(endpointLookup, null, MediaType.ApplicationLinkFormat);
            foreach (WebLink w in d)
            {
                c.UriPath = w.Uri;
                c.Delete();
            }
        }
Ejemplo n.º 21
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="_id">group id</param>
 /// <param name="_cc">existing coap client</param>
 /// <param name="loadAutomatically">Load group object automatically (default: true)</param>
 public GroupController(long _id, CoapClient _cc, bool loadAutomatically = true)
 {
     id = _id;
     cc = _cc;
     if (loadAutomatically)
     {
         GetTradFriGroup();
     }
 }
Ejemplo n.º 22
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="id">group id</param>
 /// <param name="coapClent">existing coap client</param>
 /// <param name="loadAutomatically">Load group object automatically (default: true)</param>
 public GroupController(long id, CoapClient coapClent, bool loadAutomatically = true)
 {
     this._id   = id;
     _coapClent = coapClent;
     if (loadAutomatically)
     {
         GetTradfriGroup();
     }
 }
Ejemplo n.º 23
0
        private static async Task TestGet_ApiCoap()
        {
            var client = new CoapClient();

            client.Uri = new Uri("coap://localhost:5683/helloworld");
            var res = client.Get();

            Console.WriteLine(res.ResponseText);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="_id">group id</param>
 /// <param name="_cc">existing coap client</param>
 /// <param name="loadAutomatically">Load group object automatically (default: true)</param>
 public SmartTaskController(long _id, CoapClient _cc, bool loadAutomatically = true)
 {
     id = _id;
     cc = _cc;
     if (loadAutomatically)
     {
         GetTradFriSmartTask();
     }
 }
Ejemplo n.º 25
0
 /// <summary>
 /// ctor
 /// </summary>
 /// <param name="id">group id</param>
 /// <param name="coapClient">existing coap client</param>
 /// <param name="loadAutomatically">Load group object automatically (default: true)</param>
 public SmartTaskController(long id, CoapClient coapClient, bool loadAutomatically = true)
 {
     this._id         = id;
     this._coapClient = coapClient;
     if (loadAutomatically)
     {
         GetTradfriSmartTask();
     }
 }
Ejemplo n.º 26
0
        public void Write_BlockWiseCoapMessage_BlockSizeTooLarge(int initialBlockSize, int reducetoBlockSize, int blocks, bool lastHalfblock)
        {
            Assume.That(reducetoBlockSize < initialBlockSize, "Ignoring invalid test input");

            // Arrange
            var totalBytes  = (blocks * initialBlockSize) + (lastHalfblock ? initialBlockSize / 2 : 0);
            var totalBlocks = ((totalBytes - 1) / reducetoBlockSize) + 1;

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

            var baseResponseMessage = new CoapMessage
            {
                Code = CoapMessageCode.Continue,
                Type = CoapMessageType.Acknowledgement,
            };

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

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

            mockClientEndpoint.Object.Mode = MockBlockwiseEndpointMode.RequestTooLarge;

            helper.AssertLargeBlockSizeGetsSent(mockClientEndpoint, initialBlockSize, reducetoBlockSize)
            .AssertWriteRequestCorrespondance(mockClientEndpoint);

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

                client.SetNextMessageId(1);
                using (var writer = new CoapBlockStreamWriter(client, baseRequest)
                {
                    BlockSize = initialBlockSize
                })
                {
                    writer.Write(BlockWiseTestHelper.ByteRange(0, totalBytes), 0, totalBytes);

                    writer.Flush();
                };
            }

            // Assert
            mockClientEndpoint.Verify();
        }
Ejemplo n.º 27
0
        //  Use Security Context A
        static void RunTest3()
        {
            CoapClient request = new CoapClient(Program.Host + "/oscore/hello/2?first=1")
            {
                Timeout       = 2000,
                OscoreContext = _oscoreContext
            };

            Response response = request.Get();

            if (response == null)
            {
                Console.WriteLine("Failed to receive response");
                return;
            }

            if (response.StatusCode != StatusCode.Content)
            {
                Console.WriteLine("Content type should be 2.05 not ${response.StatusCode}");
            }

            if (response.HasOption(OptionType.ContentType))
            {
                if (response.ContentType != MediaType.TextPlain)
                {
                    Console.WriteLine($"Content type is set to {response.ContentType} and not 0");
                }
            }
            else
            {
                Console.WriteLine("Content Type is missing");
            }

            if (response.HasOption(OptionType.ETag))
            {
                if (response.ETags.Count() != 1)
                {
                    Console.WriteLine("Number of ETags is incorrect");
                }
                if (!response.ContainsETag(new byte[] { 0x2b }))
                {
                    Console.WriteLine("Missing ETag = 0x2b");
                }
            }
            else
            {
                Console.WriteLine("ETag is missing");
            }

            if (!response.PayloadString.Equals("Hello World!"))
            {
                Console.WriteLine("Content value is wrong");
            }

            Console.WriteLine($"Response Message:\n{Utils.ToString(response)}");
        }
Ejemplo n.º 28
0
        static async Task ReceiveAsync(CoapClient client, CancellationToken token)
        {
            while (!token.IsCancellationRequested)
            {
                // Wait indefinitely until any message is received.
                var response = await client.ReceiveAsync(token);

                Console.WriteLine($"Received a response from {response.Endpoint}\n{Encoding.UTF8.GetString(response.Message.Payload)}");
            }
        }
Ejemplo n.º 29
0
        public void Ocoap_Get()
        {
            CoapClient client = new CoapClient($"coap://localhost:{_serverPort}/abc")
            {
                OscoreContext = SecurityContext.DeriveContext(_Secret, null, _ClientId, _ServerId)
            };
            Response r = client.Get();

            Assert.AreEqual("/abc", r.PayloadString);
        }
Ejemplo n.º 30
0
        static async Task Main(string[] args)
        {
            var host     = "localhost";
            var port     = Coap.PortDTLS;
            var identity = new BasicTlsPskIdentity("user", Encoding.UTF8.GetBytes("password"));


            // Create a new client using a DTLS endpoint with the remote host and Identity
            var client = new CoapClient(new CoapDtlsClientEndPoint(host, port, new ExamplePskDtlsClient(identity)));
            // Create a cancelation token that cancels after 1 minute
            var cancellationTokenSource = new CancellationTokenSource(TimeSpan.FromMinutes(1));

            // Capture the Control + C event
            Console.CancelKeyPress += (s, e) =>
            {
                Console.WriteLine("Exiting");
                cancellationTokenSource.Cancel();

                // Prevent the Main task from being destroyed prematurely.
                e.Cancel = true;
            };

            Console.WriteLine("Press <Ctrl>+C to exit");

            try
            {
                // Create a simple GET request
                var message = new CoapMessage
                {
                    Code = CoapMessageCode.Get,
                    Type = CoapMessageType.Confirmable,
                };

                // Get the /hello resource from localhost.
                message.SetUri($"coaps://{host}:{port}/hello");

                Console.WriteLine($"Sending a {message.Code} {message.GetUri().GetComponents(UriComponents.PathAndQuery, UriFormat.Unescaped)} request");
                await client.SendAsync(message, cancellationTokenSource.Token);

                // Wait for the server to respond.
                var response = await client.ReceiveAsync(cancellationTokenSource.Token);

                // Output our response
                Console.WriteLine($"Received a response from {response.Endpoint}\n{Encoding.UTF8.GetString(response.Message.Payload)}");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Exception caught: {ex}");
            }
            finally
            {
                Console.WriteLine($"Press <Enter> to exit");
                Console.Read();
            }
        }