Beispiel #1
0
 public PiraeusCoapClient(CoapConfig config, IChannel channel, SecurityTokenType tokenType, string securityToken, ICoapRequestDispatch dispatcher = null)
     : this(config, channel, dispatcher)
 {
     this.tokenType     = tokenType;
     this.securityToken = securityToken;
     usedToken          = false;
 }
Beispiel #2
0
        public CoapProtocolAdapter(PiraeusConfig config, IAuthenticator authenticator, IChannel channel, ILogger logger, HttpContext context = null)
        {
            this.context = context;
            this.logger  = logger;
            CoapConfigOptions options    = config.ObserveOption && config.NoResponseOption ? CoapConfigOptions.Observe | CoapConfigOptions.NoResponse : config.ObserveOption ? CoapConfigOptions.Observe : config.NoResponseOption ? CoapConfigOptions.NoResponse : CoapConfigOptions.None;
            CoapConfig        coapConfig = new CoapConfig(authenticator, config.CoapAuthority, options, config.AutoRetry,
                                                          config.KeepAliveSeconds, config.AckTimeoutSeconds, config.AckRandomFactor,
                                                          config.MaxRetransmit, config.NStart, config.DefaultLeisure, config.ProbingRate, config.MaxLatencySeconds);

            coapConfig.IdentityClaimType = config.ClientIdentityNameClaimType;
            coapConfig.Indexes           = config.GetClientIndexes();

            InitializeAuditor(config);

            Channel                = channel;
            Channel.OnClose       += Channel_OnClose;
            Channel.OnError       += Channel_OnError;
            Channel.OnOpen        += Channel_OnOpen;
            Channel.OnReceive     += Channel_OnReceive;
            Channel.OnStateChange += Channel_OnStateChange;
            session                = new CoapSession(coapConfig, context);

            if (Channel.State != ChannelState.Open)
            {
                Channel.OpenAsync().GetAwaiter();
                Channel.ReceiveAsync();
            }
        }
Beispiel #3
0
 public Host()
 {
     _conf = new CoapConfig();
     _conf.DefaultBlockSize = 32;
     _conf.MaxMessageSize   = 32;
     _endpoint = new CoAPEndPoint(_conf);
     _endpoint.Start();
     Running = false;
 }
Beispiel #4
0
 public Host(string ip)
 {
     this._ip = IPAddress.Parse(ip);
     _conf    = new CoapConfig();
     _conf.DefaultBlockSize = 32;
     _conf.MaxMessageSize   = 32;
     _endpoint = new CoAPEndPoint(_conf);
     _endpoint.Start();
     Running = false;
 }
Beispiel #5
0
        public void SetupServer()
        {
            Com.AugustCellars.CoAP.Log.LogManager.Level = Com.AugustCellars.CoAP.Log.LogLevel.Debug;
            _config = new CoapConfig();
            _config.OSCOAP_DefaultBlockSize = 32;
            _config.OSCOAP_MaxMessageSize   = 32;
            _config.AckTimeout = 60 * 60 * 1000;

            CreateServer();
            _clientEndpoint = new CoAPEndPoint(_config);
            _clientEndpoint.Start();
        }
        private void CreateServer()
        {
            _config = new CoapConfig {
                NonTimeout = 10             // 10 ms
            };

            _resource  = new ObserveTests2.ObserveResource(target1);
            _resource2 = new ObserveTests2.ObserveResource(target2);
            _server    = new CoapServer(_config);
            _server.Add(_resource);
            _server.Add(_resource2);
            IEndPoint endpoint = Pump.AddEndPoint("server #1", MockMessagePump.ServerAddress, _config, new Type[] { typeof(ObserveLayer), typeof(TokenLayer), typeof(ReliabilityLayer) });

            _server.AddEndPoint(endpoint);
            _server.Start();
        }
Beispiel #7
0
        public CoapSession(CoapConfig config, HttpContext context = null)
        {
            Config       = config;
            this.context = context;

            CoapReceiver        = new Receiver(config.ExchangeLifetime.TotalMilliseconds);
            CoapSender          = new Transmitter(config.ExchangeLifetime.TotalMilliseconds, config.MaxTransmitSpan.TotalMilliseconds, config.MaxRetransmit);
            CoapSender.OnRetry += Transmit_OnRetry;

            if (config.KeepAlive.HasValue)
            {
                keepaliveTimestamp      = DateTime.UtcNow.AddSeconds(config.KeepAlive.Value);
                keepaliveTimer          = new Timer(config.KeepAlive.Value * 1000);
                keepaliveTimer.Elapsed += KeepaliveTimer_Elapsed;
                keepaliveTimer.Start();
            }
        }
        private void CreateServer()
        {
            _config            = new CoapConfig();
            _config.NonTimeout = 10; // 10 ms

            CoAPEndPoint endpoint = new CoAPEndPoint(0, _config);

            _resource  = new ObserveResource(target1);
            _resource2 = new ObserveResource(target2);
            _server    = new CoapServer(_config);
            _server.Add(_resource);
            _server.Add(_resource2);

            _server.AddEndPoint(endpoint);
            _server.Start();
            _serverPort = ((System.Net.IPEndPoint)endpoint.LocalEndPoint).Port;
        }
Beispiel #9
0
        public PiraeusCoapClient(CoapConfig config, IChannel channel, ICoapRequestDispatch dispatcher = null)
        {
            this.config = config;
            pingId      = new List <ushort>();
            session     = new CoapSession(config);

            observers                   = new Dictionary <string, string>();
            this.dispatcher             = dispatcher;
            this.channel                = channel;
            this.channel.OnClose       += Channel_OnClose;
            this.channel.OnError       += Channel_OnError;
            this.channel.OnOpen        += Channel_OnOpen;
            this.channel.OnStateChange += Channel_OnStateChange;
            this.channel.OnReceive     += Channel_OnReceive;
            session.OnRetry            += Session_OnRetry;
            session.OnKeepAlive        += Session_OnKeepAlive;
            session.IsAuthenticated     = true;
            usedToken                   = true;
            queue = new Queue <byte[]>();
        }
Beispiel #10
0
        static void Main(string[] args)
        {
            CoapConfig _config = new CoapConfig();

            _config.DefaultBlockSize = 32;
            _config.MaxMessageSize   = 32;

            CoapServer   server   = new CoapServer(_config);
            CoAPEndPoint endpoint = new CoAPEndPoint(CoapConstants.DefaultPort, _config);

            server.AddEndPoint(endpoint);

            server.Add(new Temp("/sensors/temp"));
            server.Add(new Humidity("/sensors/humidity"));
            server.Add(new Vcc3("/sensors/vcc3"));
            server.Add(new Storage("/data/buffer"));
            server.Add(new Light("/sensors/light"));
            server.Add(new Hops("/info/hops"));

            try
            {
                server.Start();

                Console.Write("CoAP server [{0}] is listening on", server.Config.Version);

                foreach (var item in server.EndPoints)
                {
                    Console.Write(" ");
                    Console.Write(item.LocalEndPoint);
                }
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
        private void CreateServer()
        {
            CoapConfig config = new CoapConfig();

            CoAPEndPoint endpoint = new CoAPEndPoint(0, config);

            _resource = new MulticastResource(MulticastTarget, MulticastResponse);
            _server   = new CoapServer();
            _server.Add(_resource);

            _server.AddEndPoint(endpoint);
            _server.Start();
            _serverPort = ((IPEndPoint)endpoint.LocalEndPoint).Port;

            endpoint.AddMulticastAddress(new IPEndPoint(multicastAddress3, _serverPort));
            endpoint.AddMulticastAddress(new IPEndPoint(multicastAddress4, _serverPort));
            endpoint.AddMulticastAddress(new IPEndPoint(multicastAddress, _serverPort + PortJump));
            endpoint.AddMulticastAddress(new IPEndPoint(multicastAddress2, _serverPort + PortJump));

            Resource r2 = new UnicastResource(UnicastTarget, UnicastResponse);

            _server.Add(r2);
        }
        public void ObserveTest3()
        {
            CoapConfig clientConfig = new CoapConfig()
            {
                MaxRetransmit = 0
            };

            LogManager.Level = LogLevel.Debug;

            Pump = new MockMessagePump();

            IEndPoint clientEndpoint = Pump.AddEndPoint("Client1", MockMessagePump.ClientAddress, clientConfig, new Type[] { typeof(ObserveLayer), typeof(TokenLayer), typeof(ReliabilityLayer) });

            clientEndpoint.Start();

            CreateServer();
            _config.NonTimeout = 100;  // Change this value up - at 10 it cleans up the NON before the RST has a chance to get back.

            CoapClient coapClient = new CoapClient {
                EndPoint = clientEndpoint,
                Uri      = new Uri($"coap://{MockMessagePump.ServerAddress}{_resource.Uri}"),
                Timeout  = 0
            };

            Response lastResponse = null;
            int      count        = 1;

            _resource.UpdateContent($"First string {count - 1}");

            AutoResetEvent      trigger  = new AutoResetEvent(false);
            CoapObserveRelation relation = coapClient.ObserveAsync(
                (r) => {
                lastResponse = r;
                trigger.Set();
            });

            int  emptyCount = 0;
            bool dataSent   = false;

            byte[] tokenBytes = relation.Request.Token;

            while (true)
            {
                Thread.Sleep(1);
                if (Pump.Queue.Count > 0)
                {
                    MockQueueItem item = Pump.Queue.Peek();
                    switch (item.ItemType)
                    {
                    case MockQueueItem.QueueType.NetworkSend:
                        if (item.Request != null)
                        {
                            Debug.WriteLine($"Request: {item.Request}");
                            if (tokenBytes == null)
                            {
                                tokenBytes = relation.Request.Token;
                            }

                            Assert.IsTrue(item.Request.HasOption(OptionType.Observe));
                            Assert.AreEqual(0, item.Request.Observe);
                            CollectionAssert.AreEqual(tokenBytes, item.Request.Token);
                        }
                        else if (item.Response != null)
                        {
                            Debug.WriteLine($"Response: {item.Response}");
                            Assert.IsTrue(item.Response.HasOption(OptionType.Observe));
                            Assert.AreEqual(count, item.Response.Observe);
                            CollectionAssert.AreEqual(tokenBytes, item.Response.Token);
                            dataSent = true;
                        }
                        else
                        {
                            Debug.WriteLine($"RST: {item.EmptyMessage}");
                            emptyCount += 1;
                            dataSent    = true;
                        }

                        break;
                    }

                    Pump.Pump();
                }
                else if (dataSent)
                {
                    dataSent = false;
                    if (count >= 3)
                    {
                        Assert.IsNull(lastResponse);
                    }
                    else
                    {
                        Assert.IsTrue(trigger.WaitOne(10 * 1000));
                        Assert.IsNotNull(lastResponse);
                        Assert.IsTrue(lastResponse.HasOption(OptionType.Observe));
                        Assert.AreEqual(count, lastResponse.Observe);
                        lastResponse = null;
                    }

                    if (count < 5)
                    {
                        _resource.UpdateContent($"New string {count}");
                        count += 1;
                        if (count == 3)
                        {
                            relation.ReactiveCancel();
                        }
                    }
                    else
                    {
                        break;
                    }
                }
                else if (count == 5)
                {
                    break;
                }
                else if (emptyCount != 0)
                {
                    _resource.UpdateContent($"New string {count}");
                    count += 1;
                }
            }

            Assert.AreEqual(1, emptyCount);
            Assert.AreEqual(5, count);
        }
Beispiel #13
0
        static void Main(string[] args)
        {
            ICoapConfig config      = null;
            KeySet      allKeys     = null;
            string      interopTest = null;

            LogManager.Level    = LogLevel.All;
            LogManager.Instance = new FileLogManager(Console.Out);

            for (int i = 0; i < args.Length; i++)
            {
                String[] s = args[i].Split('=');
                if (s.Length == 1)
                {
                    Array.Resize(ref s, 2);
                }

                switch (s[0])
                {
                case "--generate":
                    GenerateKeys(s[1]);
                    break;

                case "--loadkeys":
                    allKeys = LoadKeys(s[1]);
                    break;

                case "--config":
                    if (s[1] == null)
                    {
                        PrintCommandLine();
                    }
                    config = new CoapConfig();
                    config.Load(s[1]);
                    break;

                case "--demon":
                    AsDemon = true;
                    break;

                case "--ipAddr":
                case "--ipaddress":
                    if (s[1] == null)
                    {
                        PrintCommandLine();
                    }
                    IPAddress ip;
                    if (!IPAddress.TryParse(s[1], out ip))
                    {
                        Console.WriteLine("Invalid ip-address");
                        PrintCommandLine();
                    }

                    ServerEndPoint = new IPEndPoint(ip, 0);

                    break;

                case "--interop-test":
                    if (s[1] == null)
                    {
                        PrintCommandLine();
                    }
                    interopTest = s[1];
                    break;

                default:
                    PrintCommandLine();
                    break;
                }
            }

            if (interopTest != null)
            {
                RunInteropTests(interopTest, config, ServerEndPoint);
            }

            if (allKeys == null)
            {
                allKeys = LoadKeys(null);
            }


            CoapServer server1 = SetupServer(config, ServerEndPoint, CoapConfig.Default.DefaultPort, DtlsSignKeys, DtlsValidateKeys);
            CoapServer server2 = SetupServer(config, ServerEndPoint, 5685, DtlsSignKeys, DtlsValidateKeys);

            if (AsDemon)
            {
                ExitEvent.WaitOne();
            }
            else
            {
                Console.WriteLine("Press key to exit");
                Console.ReadKey();
            }

            server1.Stop();
            server2.Stop();
        }
Beispiel #14
0
 public static IEndPoint CreateEndPoint(ISpec spec)
 {
     CoapConfig config = new CoapConfig();
     config.DefaultPort = spec.DefaultPort;
     config.Spec = spec;
     CoAPEndPoint ep = new CoAPEndPoint(config);
     ep.Start();
     return ep;
 }
        public void ObserveTest2()
        {
            CoapConfig clientConfig = new CoapConfig()
            {
                NotificationReregistrationBackoff = 0
            };

            Pump = new MockMessagePump();

            IEndPoint clientEndpoint = Pump.AddEndPoint("Client1", MockMessagePump.ClientAddress, clientConfig, new Type[] { typeof(ObserveLayer) });

            clientEndpoint.Start();

            CreateServer();

            CoapClient coapClient = new CoapClient {
                EndPoint = clientEndpoint,
                Uri      = new Uri($"coap://{MockMessagePump.ServerAddress}{_resource.Uri}"),
                Timeout  = 0
            };

            Response lastResponse    = null;
            int      count           = 1;
            int      clientObserveNo = 0;

            _resource.UpdateContent($"First string {count - 1}");

            AutoResetEvent      trigger  = new AutoResetEvent(false);
            CoapObserveRelation relation = coapClient.ObserveAsync(
                (r) => {
                lastResponse = r;
                trigger.Set();
            });

            AutoResetEvent reregistered = new AutoResetEvent(false);

            relation.Request.Reregistering += (a, b) => {
                reregistered.Set();
            };

            bool dataSent = false;

            byte[] tokenBytes = relation.Request.Token;

            while (true)
            {
                Thread.Sleep(1);
                if (Pump.Queue.Count > 0)
                {
                    MockQueueItem item = Pump.Queue.Peek();
                    switch (item.ItemType)
                    {
                    case MockQueueItem.QueueType.NetworkSend:
                        if (item.Request != null)
                        {
                            if (tokenBytes == null)
                            {
                                tokenBytes = relation.Request.Token;
                            }

                            Assert.IsTrue(item.Request.HasOption(OptionType.Observe));
                            Assert.AreEqual(clientObserveNo, item.Request.Observe);
                            CollectionAssert.AreEqual(tokenBytes, item.Request.Token);
                            clientObserveNo += 1;
                        }
                        else if (item.Response != null)
                        {
                            if (count < 4)
                            {
                                Assert.IsTrue(item.Response.HasOption(OptionType.Observe));
                                Assert.AreEqual(count, item.Response.Observe);
                            }
                            else
                            {
                                // Assert.IsFalse(item.Response.HasOption(OptionType.Observe));
                            }

                            CollectionAssert.AreEqual(tokenBytes, item.Response.Token);
                            dataSent = true;
                        }
                        else
                        {
                            Assert.Fail();
                        }

                        break;
                    }

                    Pump.Pump();
                }
                else if (dataSent)
                {
                    dataSent = false;
                    if (count > 4)
                    {
                        Assert.IsNull(lastResponse);
                    }
                    else
                    {
                        Assert.IsTrue(trigger.WaitOne(1000));
                        Assert.IsNotNull(lastResponse);
                        if (count == 4)
                        {
                            Assert.IsFalse(lastResponse.HasOption(OptionType.Observe));
                        }
                        else
                        {
                            Assert.IsTrue(lastResponse.HasOption(OptionType.Observe));
                            Assert.AreEqual(count, lastResponse.Observe);
                        }

                        lastResponse = null;
                    }

                    if (count < 5)
                    {
                        if (count == 3)
                        {
                            relation.ProactiveCancel();
                            _resource.UpdateContent($"New string {count}");
                        }
                        else
                        {
                            _resource.UpdateContent($"New string {count}");
                        }
                        count += 1;
                    }
                    else
                    {
                        break;
                    }
                }
                else if (count == 5)
                {
                    break;
                }
            }

            Assert.AreEqual(2, clientObserveNo);
            Assert.AreEqual(5, count);

            //  Total # of seconds is MaxAge = 1 + backoff = 0 + random(2, 15)
            Assert.IsFalse(reregistered.WaitOne(17 * 1000));
        }
        public void ObserveTest1()
        {
            CoapConfig clientConfig = new CoapConfig();

            Pump = new MockMessagePump();

            IEndPoint clientEndpoint = Pump.AddEndPoint("Client1", MockMessagePump.ClientAddress, clientConfig, new Type[] { typeof(ObserveLayer) });

            clientEndpoint.Start();

            CreateServer();

            CoapClient coapClient = new CoapClient {
                EndPoint = clientEndpoint,
                Uri      = new Uri($"coap://{MockMessagePump.ServerAddress}{_resource.Uri}"),
                Timeout  = 0
            };

            Response lastResponse = null;
            int      count        = 1;

            _resource.UpdateContent($"First string {count-1}");

            AutoResetEvent      trigger  = new AutoResetEvent(false);
            CoapObserveRelation relation = coapClient.ObserveAsync(
                (r) => {
                lastResponse = r;
                trigger.Set();
            });

            byte[] tokenBytes = relation.Request.Token;
            bool   dataSent   = false;

            while (true)
            {
                Thread.Sleep(1);
                if (Pump.Queue.Count > 0)
                {
                    MockQueueItem item = Pump.Queue.Peek();
                    switch (item.ItemType)
                    {
                    case MockQueueItem.QueueType.NetworkSend:
                        if (item.Request != null)
                        {
                            if (tokenBytes == null)
                            {
                                tokenBytes = relation.Request.Token;
                            }

                            Assert.IsTrue(item.Request.HasOption(OptionType.Observe));
                            Assert.AreEqual(0, item.Request.Observe);
                            CollectionAssert.AreEqual(tokenBytes, item.Request.Token);
                        }
                        else if (item.Response != null)
                        {
                            Assert.IsTrue(item.Response.HasOption(OptionType.Observe));
                            Assert.AreEqual(count, item.Response.Observe);
                            CollectionAssert.AreEqual(tokenBytes, item.Response.Token);
                            dataSent = true;
                        }
                        else
                        {
                            Assert.Fail();
                        }

                        break;
                    }

                    Pump.Pump();
                }
                else if (dataSent)
                {
                    Assert.IsTrue(trigger.WaitOne(1000));
                    Assert.IsTrue(lastResponse.HasOption(OptionType.Observe));
                    Assert.AreEqual(count, lastResponse.Observe);
                    dataSent     = false;
                    lastResponse = null;

                    if (count < 5)
                    {
                        _resource.UpdateContent($"New string {count}");
                        count += 1;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            Assert.AreEqual(5, count);
        }
        public void ObserveTest13()
        {
            CoapConfig clientConfig = new CoapConfig()
            {
                NotificationReregistrationBackoff = 0
            };

            Pump = new MockMessagePump();

            IEndPoint clientEndpoint = Pump.AddEndPoint("Client1", MockMessagePump.ClientAddress, clientConfig, new Type[] { typeof(ObserveLayer) });

            clientEndpoint.Start();

            CreateServer();

            CoapClient coapClient = new CoapClient
            {
                EndPoint = clientEndpoint,
                Uri      = new Uri($"coap://{MockMessagePump.ServerAddress}{_resource.Uri}"),
                Timeout  = 0
            };

            Response lastResponse = null;
            int      count        = 1;

            _resource.UpdateContent($"First string {count - 1}");

            AutoResetEvent      trigger  = new AutoResetEvent(false);
            CoapObserveRelation relation = coapClient.ObserveAsync(
                (r) => {
                lastResponse = r;
                trigger.Set();
            });

            AutoResetEvent reregistered = new AutoResetEvent(false);

            relation.Request.Reregistering += (a, b) => {
                reregistered.Set();
                b.RefreshRequest.IsCancelled = true;
            };


            byte[] tokenBytes = relation.Request.Token;
            bool   dataSent   = false;
            int    requestNo  = 0;
            int    observerNo = 1;

            while (true)
            {
                Thread.Sleep(1);
                if (Pump.Queue.Count > 0)
                {
                    MockQueueItem item = Pump.Queue.Peek();
                    switch (item.ItemType)
                    {
                    case MockQueueItem.QueueType.NetworkSend:
                        if (item.Request != null)
                        {
                            if (tokenBytes == null)
                            {
                                tokenBytes = relation.Request.Token;
                            }

                            Assert.IsTrue(item.Request.HasOption(OptionType.Observe));
                            Assert.AreEqual(0, item.Request.Observe);
                            CollectionAssert.AreEqual(tokenBytes, item.Request.Token);

                            switch (requestNo)
                            {
                            case 0:
                                Assert.IsFalse(item.Request.HasOption(OptionType.ETag));
                                break;

                            case 1:
                            case 2:
                                Assert.AreEqual(4, item.Request.ETags.ToArray().Length);
                                break;
                            }

                            requestNo += 1;
                            Debug.WriteLine($"Request: {item.Request}");
                        }
                        else if (item.Response != null)
                        {
                            Assert.IsTrue(item.Response.HasOption(OptionType.Observe));
                            Assert.AreEqual(observerNo, item.Response.Observe);
                            CollectionAssert.AreEqual(tokenBytes, item.Response.Token);
                            dataSent = true;
                            Debug.WriteLine($"Response: {item.Response} {item.Response.Observe}");
                        }
                        else
                        {
                            Assert.Fail();
                        }

                        break;
                    }

                    Pump.Pump();
                }
                else if (dataSent)
                {
                    Assert.IsTrue(trigger.WaitOne(1000));
                    Assert.IsTrue(lastResponse.HasOption(OptionType.Observe));
                    Assert.AreEqual(observerNo, lastResponse.Observe);
                    dataSent     = false;
                    lastResponse = null;

                    if (count == 4)
                    {
                        relation.UpdateETags(new byte[][] { new byte[] { 1 }, new byte[] { 3 }, new byte[] { 5 }, new byte[] { 7 } });
                        count += 1;
                    }
                    else if (count == 8)
                    {
                        Assert.IsTrue(reregistered.WaitOne(20 * 1000));
                        count += 1;
                    }

                    if (count == 9)
                    {
                        count += 1;
                        _resource.UpdateContent($"New string {count}");
                        observerNo += 1;
                        count      += 1;
                    }
                    else if (count < 12)
                    {
                        _resource.UpdateContent($"New string {count}");
                        count      += 1;
                        observerNo += 1;
                    }
                    else
                    {
                        break;
                    }
                }
            }
            Assert.AreEqual(12, count);
        }