Exemplo n.º 1
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;
        }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
0
        public DeviceController(long id, IkeaTradfriDriver driver, bool loadAutomatically = true)
        {
            this._id    = id;
            _coapClient = driver.Client;
            if (loadAutomatically)
            {
                GetTradFriDevice();
            }

            _coapClient.Observe(driver.HandleObserveResponse);
        }
        /// <summary>
        /// Observes a device and gets update notifications
        /// </summary>
        /// <param name="callback">Action to take for each device update</param>
        /// <param name="error">Action to take on internal error</param>
        /// <returns></returns>
        public CoapObserveRelation ObserveDevice(CoapClient cc, TradfriDevice device, Action <TradfriDevice> callback, Action <CoapClient.FailReason> error = null)
        {
            Action <Response> update = delegate(Response response)
            {
                OnDeviceObservationUpdate(device, response, callback);
            };

            return(cc.Observe(
                       $"/{(int)TradfriConstRoot.Devices}/{device.ID}",
                       update,
                       error
                       ));
        }
Exemplo n.º 5
0
        public void CheckOnTime()
        {
            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;

            _config.NotificationCheckIntervalTime = 500;
            int count = 0;

            for (int i = 0; i < 20; i++)
            {
                Thread.Sleep(100);
                _expected = $"Content for {i}";
                _resource.UpdateContent(_expected);
                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;

                Console.WriteLine($"lastObserve = {lastObserve},  type = {nextResponse.Type}");
                count += (nextResponse.Type == MessageType.CON) ? 1 : 0;
            }

            Assert.IsTrue(count > 0);
        }
Exemplo n.º 6
0
        static void RunTest7()
        {
            CoapClient request = new CoapClient(Program.Host + "/oscore/observe2")
            {
                Timeout       = 2000,
                OscoreContext = _oscoreContext
            };

            int count = 0;

            request.Observe(response =>
            {
                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.Observe))
                {
                    Console.WriteLine("Should have an observe in the response");
                }

                Console.WriteLine($"Response Message:\n{Utils.ToString(response)}");

                count += 1;
                if (count >= 2)
                {
                    request.Observe().ProactiveCancel();
                }
            });
        }
Exemplo n.º 7
0
        static void RunTest5()
        {
            CoapClient request = new CoapClient(Program.Host + "/oscore/hello/1")
            {
                Timeout       = 2000,
                OscoreContext = _oscoreContext
            };

            request.Observe(response =>
            {
                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.Observe))
                {
                    Console.WriteLine("Should not have an observe in the response");
                }

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

                Console.WriteLine($"Response Message:\n{Utils.ToString(response)}");
            });
        }
Exemplo n.º 8
0
        public void ServerIvExhaustion()
        {
            SecurityContext context = SecurityContext.DeriveGroupContext(secret, groupId1, clientId, AlgorithmValues.EdDSA, _clientSign1,
                                                                         new byte[][] { serverId }, new OneKey[] { _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;

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

            serverContext.Sender.MaxSequenceNumber = 10;

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

            _serverEventChoice = 0;
            Response r = client.Get();

            Assert.IsNotNull(r);
            Assert.AreEqual("/abc", r.PayloadString);

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

            Assert.AreEqual(OscoreEvent.EventCode.PivExhaustion, _callbackCode);
        }
Exemplo n.º 9
0
        public void TestOutOfOrder()
        {
            //  Check what happens with out of order delivery

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

            _expected = "No Content Yet";
            CoapObserveRelation obs1 = client.Observe(response => {
                Assert.AreEqual(_expected, response.ResponseText);
                Assert.IsTrue(response.HasOption(OptionType.Observe));
                Assert.IsTrue(response.Observe.HasValue);
                int oNumber = response.Observe.Value;
                Assert.IsTrue(oNumber > lastObserve);
                lastObserve = oNumber;
            });

            Assert.IsFalse(obs1.Canceled);

            Thread.Sleep(100);
            _resource.Changed();

            _resource2.ObserveNo = lastObserve + 3;
        }
Exemplo n.º 10
0
 public static CoapObserveRelation Observe(this CoapClient _client, string url, Action <Response> callback, Action <CoapClient.FailReason> error = null)
 {
     _client.UriPath = url;
     return(_client.Observe(callback, error));
 }
Exemplo n.º 11
0
        public void Reregister()
        {
            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));

            int oNumber = -1;

            for (int i = 0; i < 20; i++)
            {
                _expected = $"Content for {i}";
                _resource.UpdateContent(_expected);
                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;

                Console.WriteLine($"lastObserve = {lastObserve},  type = {nextResponse.Type}");
            }

            Request request = Request.NewGet();

            request.URI = uri;
            request.MarkObserve();
            request.Token = nextResponse.Token;

            client.Send(request);

            for (int i = 0; i < 20; i++)
            {
                _expected = $"Content for {i}";
                _resource.UpdateContent(_expected);
                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;

                Console.WriteLine($"lastObserve = {lastObserve},  type = {nextResponse.Type}");
            }
        }
Exemplo n.º 12
0
        static void Main(string[] args)
        {
            Com.AugustCellars.CoAP.Log.LogManager.Level = LogLevel.None;
            ;
            String Server = "192.168.53.55:5684";

            OneKey userKey = new OneKey();

            userKey.Add(CoseKeyKeys.KeyType, GeneralValues.KeyType_Octet);
            //userKey.Add(CoseKeyParameterKeys.Octet_k, CBORObject.FromObject(Encoding.UTF8.GetBytes("sesame")));
            // userKey.Add(CoseKeyKeys.KeyIdentifier, CBORObject.FromObject(Encoding.UTF8.GetBytes("password")));

            CoapClient client = new CoapClient(new Uri($"coaps://{Server}/.well-known/core"));



            CoAPEndPoint ep = new DTLSClientEndPoint(userKey);

            client.EndPoint = ep;
            ep.Start();

            //

            Response r1 = client.Get();

            Console.WriteLine("Links = " + r1.PayloadString);

            //
            //           string str = "<//15001/65536>;ct=0;obs,<//15001/65537>;ct=0;obs,<//15004/136834>;ct=0;obs,<//15005/136834/217609>;ct=0;obs,<//15005/136834/218326>;ct=0;obs,<//15005/136834/224384>;ct=0;obs,<//15005/136834>;ct=0;obs,<//15001>;ct=0;obs,<//15001/reset>;ct=0,<//status>;ct=0;obs,<//15005>;ct=0;obs,<//15004>;ct=0;obs,<//15004/add>;ct=0,<//15004/remove>;ct=0,<//15006>;ct=0;obs,<//15011/15012>;ct=0;obs,<//15011/9034>;ct=0,<//15011/9030>;ct=0,<//15011/9031>;ct=0,<//15011/9063>;ct=0,<//15011/9033>;ct=0,<//15010>;ct=0;obs";
            //           IEnumerable<WebLink> links = LinkFormat.Parse(str);
            //           foreach(var item in links) Console.WriteLine(item);
            //

            LogManager.Level = LogLevel.None;


            IEnumerable <WebLink> items = client.Discover();

            foreach (var node in items)
            {
                Console.WriteLine($"Resource = {node}");

                client.UriPath = node.Uri;

                if (false && node.Attributes.Observable)
                {
                    CoapClient c2 = new CoapClient()
                    {
                        EndPoint = client.EndPoint,
                        Uri      = client.Uri,
                        UriPath  = node.Uri
                    };
                    Console.WriteLine("Observe it");
                    CoapObserveRelation relation1 = c2.Observe(r => { EventIn(node.Uri, r); });
                }
                else
                {
                    Response response = client.Get();

                    Console.WriteLine("   Payload: " + response.PayloadString);
                    Console.WriteLine();
                }
            }

            client.Uri     = new Uri($"coaps://{Server}");
            client.UriPath = "/15004/166412";
            client.Get();
            Response rep = client.Put("{ \"5850\":1}");

            Thread.Sleep(3000);

            //rep = client.Get();
            Console.WriteLine(rep.PayloadString);

            client.UriPath = "/15001/65537";
            ;

            for (int i = 0; i < 10; i++)
            {
                Thread.Sleep(3000);
                client.Put("{ \"5851\":127}");

                Thread.Sleep(3000);
                client.Put("{ \"3311\":[{ \"5851\":0}]}");

                Thread.Sleep(3000);
                client.Put("{ \"3311\":[{ \"5851\":255}]}");
            }


            ep.Stop();
        }