Example #1
0
        public CoapConnection(Uri m2mUrl, X509Certificate?certificate = null)
        {
            _iotApiUrl = m2mUrl;

            // TODO: certificate

            _pnClient         = new CoapClient(m2mUrl);
            _pnClient.Timeout = 300 * 1000;
        }
Example #2
0
        private void TestSimpleGet(Uri uri)
        {
            Console.WriteLine("Test simple GET to " + uri);

            CoapClient client = new CoapClient(uri);

            client.EndPoint = _clientEndpoint;

            Response response = client.Get();

            Console.WriteLine("Client received response " + response.PayloadString);
            Assert.AreEqual(_currentResponseText, response.PayloadString);

            _serverSurveillant.WaitUntilDeduplicatorShouldBeEmpty();
            _serverSurveillant.AssertMapsEmpty();
            _clientSurveillant.AssertMapsEmpty();
        }
Example #3
0
        private void TestBlockwise(Uri uri)
        {
            Console.WriteLine("Test blockwise POST to " + uri);

            CoapClient client = new CoapClient(uri);

            client.EndPoint = _clientEndpoint;

            String ten = "123456789.";

            _currentRequestText = ten + ten + ten;
            Response response = client.Post(_currentRequestText, MediaType.TextPlain);

            Console.WriteLine("Client received response " + response.PayloadString);
            Assert.AreEqual(_currentResponseText, response.PayloadString);

            _serverSurveillant.WaitUntilDeduplicatorShouldBeEmpty();
            _serverSurveillant.AssertMapsEmpty();
            _clientSurveillant.AssertMapsEmpty();
        }
Example #4
0
        private void TestObserve(Uri uri)
        {
            Console.WriteLine("Test observe relation with a reactive cancelation to " + uri);

            ManualResetEvent mre = new ManualResetEvent(false);

            CoapClient client = new CoapClient(uri);

            client.EndPoint = _clientEndpoint;

            Int32 notificationCounter    = 0;
            CoapObserveRelation relation = null;

            relation = client.Observe(response =>
            {
                notificationCounter++;
                Console.WriteLine("Client received notification " + notificationCounter + ": " + response.PayloadString);

                if (notificationCounter == HOW_MANY_NOTIFICATION_WE_WAIT_FOR)
                {
                    Console.WriteLine("Client forgets observe relation to " + uri);
                    SpinWait.SpinUntil(() => relation != null);
                    relation.ProactiveCancel();
                }
                else if (notificationCounter == HOW_MANY_NOTIFICATION_WE_WAIT_FOR + 1)
                {
                    mre.Set();
                }
            }, reason => Assert.Fail(reason.ToString()));

            // Wait until we have received all the notifications and canceled the relation
            Thread.Sleep(HOW_MANY_NOTIFICATION_WE_WAIT_FOR * OBS_NOTIFICATION_INTERVALL + 3000);

            Boolean success = mre.WaitOne(100);

            Assert.IsTrue(success, "Client has not received all expected responses");

            _serverSurveillant.WaitUntilDeduplicatorShouldBeEmpty();
            _serverSurveillant.AssertMapsEmpty();
            _clientSurveillant.AssertMapsEmpty();
        }
Example #5
0
 private void SendUpdate()
 {
     if (!string.IsNullOrEmpty(_Location))
     {
         CoapClient coapClient = new CoapClient();
         coapClient.EndPoint = _EndPoint;
         Request request = new Request(Method.PUT);
         request.Destination = _ServerEndPoint;
         request.UriPath = _Location;
         request.UriQuery = "lt=35";
         coapClient.SendAsync(request);
     }
 }
Example #6
0
 public void Disconnect()
 {
     if (!string.IsNullOrEmpty(_Location))
     {
         CoapClient coapClient = new CoapClient();
         coapClient.EndPoint = _EndPoint;
         Request request = new Request(Method.DELETE);
         request.Destination = _ServerEndPoint;
         request.UriPath = _Location;
         coapClient.SendAsync(request);
         _Location = null;
     }
 }
Example #7
0
        public bool ConnectToServer()
        {
            bool result = false;
            //now register to server
            foreach (SecurityResource item in _SecurityResources.Children)
            {
                Console.Write(item.ServerURI);
                Console.Write(") .. ");
                Uri uri = new Uri(item.ServerURI);
                foreach (System.Net.IPAddress address in System.Net.Dns.GetHostAddresses(uri.DnsSafeHost))
                {
                    bool secure =false;
                    int port = 5683;
                    if (string.Compare(uri.Scheme, "coaps", true) == 0)
                    {
                        secure = true;
                        port = 5684;
                    }
                    if (uri.Port > 0)
                        port = uri.Port;
                    if (_Channel.Secure != secure)
                    {
                        _Channel.Stop();
                        _Channel.Secure = secure;
                        _Channel.Start();
                    }
                    CoapClient coapClient = new CoapClient();
                    coapClient.EndPoint = _EndPoint;
                    Request request = new Request(Method.POST);
                    request.Destination = new System.Net.IPEndPoint(address, port);
                    request.UriPath = "/rd";
                    request.UriQuery = string.Concat("ep=test",Environment.MachineName,"&lt=35");
                    StringBuilder payLoad = new StringBuilder();
                    foreach (IResource objectType in _Root.Children)
                    {
                        if (objectType.Visible)
                        {
                            bool instances = false;
                            foreach (IResource instance in objectType.Children)
                            {
                                if (payLoad.Length > 0)
                                    payLoad.Append(',');
                                payLoad.Append('<');
                                payLoad.Append('/');
                                payLoad.Append(objectType.Name);
                                payLoad.Append('/');
                                payLoad.Append(instance.Name);
                                payLoad.Append('>');
                                instances = true;
                            }
                            if (!instances)
                            {
                                if (payLoad.Length > 0)
                                    payLoad.Append(',');
                                payLoad.Append('<');
                                payLoad.Append('/');
                                payLoad.Append(objectType.Name);
                                payLoad.Append('>');
                            }
                        }
                    }
                    request.PayloadString = payLoad.ToString();
                    request.ContentType = (int)MediaType.ApplicationLinkFormat;
                    Response response = coapClient.Send(request);
                    if (response != null && response.StatusCode == StatusCode.Created)
                    {
                        string location = response.LocationPath;

                        int position = location.LastIndexOf('/');
                        if (position > 0)
                        {
                            ClientID = location.Substring(position + 1);
                        }

                        result = true;
                        _ServerEndPoint = request.Destination;
                        _Location = location;
                        _Timer.Start();
                        break;
                    }
                }
            }
            return result;
        }
Example #8
0
        //System.Net.IPAddress.Parse("fe80::18be:e89d:e85f:278%12") //15685
        public bool Bootstrap(string url)
        {
            bool result = false;
            _Timer.Stop();
            Uri uri = new Uri(url);
            foreach (System.Net.IPAddress address in System.Net.Dns.GetHostAddresses(uri.DnsSafeHost))
            {
                CoapClient coapClient = new CoapClient();
                coapClient.EndPoint = _EndPoint;
                Request request = new Request(Method.POST);
                int port = 5683;
                if (string.Compare(uri.Scheme, "coaps", true) ==0)
                    port = 5684;
                if (uri.Port > 0)
                    port = uri.Port;
                request.Destination = new System.Net.IPEndPoint(address, port);
                request.UriPath = "/bs";
                request.UriQuery = "ep=test";
                Response response = coapClient.Send(request);
                if (response != null && response.StatusCode == StatusCode.Changed)
                {
                    result = _BootsrapComplete.Wait(30000);
                    break;
                }
            }

            return result;
        }
Example #9
0
        private void ProcessRequests()
        {
            while (!_Terminate)
            {
                _TriggerProcessRequests.Reset();
                while (_NewClients.Count > 0)
                {
                    LWM2MClient client = null;
                    try
                    {
                        lock (_NewClients)
                        {
                            if (_NewClients.Count > 0)
                                client = _NewClients.Dequeue();
                        }
                        if (client != null)
                        {
                            if ((client.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) || (client.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6))
                            {
                                Server server = BusinessLogicFactory.Servers.GetServer();
                                System.Net.IPEndPoint ipEndPoint = client.Address as System.Net.IPEndPoint;
                                CoapClient coapClient = new CoapClient();
                                coapClient.EndPoint = client.EndPoint;
                                coapClient.Timeout = REQUEST_TIMEOUT;
                                ushort objectInstanceID = 1;
                                foreach (Model.Security item in server.EndPoints)
                                {
                                    Request request = new Request(Method.PUT);
                                    request.ContentType = TlvConstant.CONTENT_TYPE_TLV;// (int)MediaType.ApplicationOctetStream;
                                    request.Destination = client.Address;
                                    request.UriPath = "/0";
                                    request.Payload = SerialiseObject(item, objectInstanceID);
                                    objectInstanceID++;
                                    coapClient.SendAsync(request, (response) =>
                                        {
                                            if (response != null && response.StatusCode == StatusCode.Changed)
                                            {
                                                request = new Request(Method.PUT);
                                                request.ContentType = TlvConstant.CONTENT_TYPE_TLV;//(int)MediaType.ApplicationOctetStream;
                                                request.Destination = client.Address;
                                                request.UriPath = "/1";
                                                request.Payload = SerialiseObject(server, 1);
                                                coapClient.SendAsync(request, (response2) =>
                                                    {
                                                        if (response2 != null && response2.StatusCode == StatusCode.Changed)
                                                        {
                                                            request = new Request(Method.POST);
                                                            request.Destination = client.Address;
                                                            request.UriPath = "/bs";
                                                            coapClient.SendAsync(request);
                                                        }
                                                    });
                                            }
                                        }
                                    );
                                }

                            }
                        }
                    }
                    catch(Exception ex)
                    {
                        ApplicationEventLog.WriteEntry("Flow", ex.ToString(), System.Diagnostics.EventLogEntryType.Error);
                    }
                }
                if (!_Terminate)
                    _TriggerProcessRequests.WaitOne();
            }
        }
Example #10
0
        public void TestSynchronousCall()
        {
            Uri        uri    = new Uri("coap://localhost:" + _serverPort + "/" + TARGET);
            CoapClient client = new CoapClient(uri);

            // Check that we get the right content when calling get()
            String resp1 = client.Get().ResponseText;

            Assert.AreEqual(CONTENT_1, resp1);

            String resp2 = client.Get().ResponseText;

            Assert.AreEqual(CONTENT_1, resp2);

            // Change the content to "two" and check
            String resp3 = client.Post(CONTENT_2).ResponseText;

            Assert.AreEqual(CONTENT_1, resp3);

            String resp4 = client.Get().ResponseText;

            Assert.AreEqual(CONTENT_2, resp4);

            // Observe the resource
            _expected = CONTENT_2;
            CoapObserveRelation obs1 = client.Observe(response =>
            {
                Interlocked.Increment(ref _notifications);
                String payload = response.ResponseText;
                Assert.AreEqual(_expected, payload);
                Assert.IsTrue(response.HasOption(OptionType.Observe));
            }, Fail);

            Assert.IsFalse(obs1.Canceled);

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

            Thread.Sleep(100);
            _expected = CONTENT_3;
            String resp5 = client.Post(CONTENT_3).ResponseText;

            Assert.AreEqual(CONTENT_2, resp5);

            // Try a put and receive a METHOD_NOT_ALLOWED
            StatusCode code6 = client.Put(CONTENT_4).StatusCode;

            Assert.AreEqual(StatusCode.MethodNotAllowed, code6);

            // Cancel observe relation of obs1 and check that it does no longer receive notifications
            Thread.Sleep(100);
            _expected = null; // The next notification would now cause a failure
            obs1.ReactiveCancel();
            Thread.Sleep(100);
            _resource.Changed();

            // Make another post
            Thread.Sleep(100);
            String resp7 = client.Post(CONTENT_4).ResponseText;

            Assert.AreEqual(CONTENT_3, resp7);

            // Try to use the builder and add a query
            UriBuilder ub = new UriBuilder("coap", "localhost", _serverPort, TARGET);

            ub.Query = QUERY_UPPER_CASE;

            String resp8 = new CoapClient(ub.Uri).Get().ResponseText;

            Assert.AreEqual(CONTENT_4.ToUpper(), resp8);

            // Check that we indeed received 5 notifications
            // 1 from origin GET request, 3 x from changed(), 1 from post()
            Thread.Sleep(100);
            Assert.AreEqual(5, _notifications);
            Assert.IsFalse(_failed);
        }
Example #11
0
        public void TestSynchronousCall()
        {
            Uri uri = new Uri("coap://localhost:" + _serverPort + "/" + TARGET);
            CoapClient client = new CoapClient(uri);

            // Check that we get the right content when calling get()
            String resp1 = client.Get().ResponseText;
            Assert.AreEqual(CONTENT_1, resp1);

            String resp2 = client.Get().ResponseText;
            Assert.AreEqual(CONTENT_1, resp2);

            // Change the content to "two" and check
            String resp3 = client.Post(CONTENT_2).ResponseText;
            Assert.AreEqual(CONTENT_1, resp3);

            String resp4 = client.Get().ResponseText;
            Assert.AreEqual(CONTENT_2, resp4);

            // Observe the resource
            _expected = CONTENT_2;
            CoapObserveRelation obs1 = client.Observe(response =>
                {
                    Interlocked.Increment(ref _notifications);
                    String payload = response.ResponseText;
                    Assert.AreEqual(_expected, payload);
                    Assert.IsTrue(response.HasOption(OptionType.Observe));
                }, Fail);
            Assert.IsFalse(obs1.Canceled);

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

            Thread.Sleep(100);
            _expected = CONTENT_3;
            String resp5 = client.Post(CONTENT_3).ResponseText;
            Assert.AreEqual(CONTENT_2, resp5);

            // Try a put and receive a METHOD_NOT_ALLOWED
            StatusCode code6 = client.Put(CONTENT_4).StatusCode;
            Assert.AreEqual(StatusCode.MethodNotAllowed, code6);

            // Cancel observe relation of obs1 and check that it does no longer receive notifications
            Thread.Sleep(100);
            _expected = null; // The next notification would now cause a failure
            obs1.ReactiveCancel();
            Thread.Sleep(100);
            _resource.Changed();

            // Make another post
            Thread.Sleep(100);
            String resp7 = client.Post(CONTENT_4).ResponseText;
            Assert.AreEqual(CONTENT_3, resp7);

            // Try to use the builder and add a query
            UriBuilder ub = new UriBuilder("coap", "localhost", _serverPort, TARGET);
            ub.Query = QUERY_UPPER_CASE;

            String resp8 = new CoapClient(ub.Uri).Get().ResponseText;
            Assert.AreEqual(CONTENT_4.ToUpper(), resp8);

            // Check that we indeed received 5 notifications
            // 1 from origin GET request, 3 x from changed(), 1 from post()
            Thread.Sleep(100);
            Assert.AreEqual(5, _notifications);
            Assert.IsFalse(_failed);
        }
Example #12
0
 private void Fail(CoapClient.FailReason reason)
 {
     _failed = true;
     Assert.Fail();
 }