public void SendResponse(Response response, Exchange exchange)
        {
            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ServerSendResponse, response, exchange);

            Queue.Enqueue(item);
            response.Session = exchange.Request.Session;
        }
        void IOutbox.SendResponse(Exchange exchange, Response response)
        {
            if (response.Type == MessageType.Unknown)
            {
                response.Type = MessageType.ACK;
            }

            if (response.Token == null)
            {
                response.Token = exchange.CurrentRequest.Token;
            }

            if (response.ID == -1)
            {
                response.ID = exchange.CurrentRequest.ID;
            }

            response.Source = MyAddress;

            Matcher.SendResponse(exchange, response);

            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ServerSendResponseNetwork, response);

            Pump.Queue.Enqueue(item);
        }
        public void SendRequest(Request request)
        {
            request.EndPoint = ClientEndpoint;
            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ClientSendRequest, request);

            Queue.Enqueue(item);
        }
        void IOutbox.SendRequest(Exchange exchange, Request request)
        {
            Matcher.SendRequest(exchange, request);
            request.Session = Session;

            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ClientSendRequestNetwork, request);

            Pump.Queue.Enqueue(item);
        }
        public void SendResponse(Exchange exchange, Response response)
        {
            response.Session     = exchange.Request.Session;
            response.Destination = exchange.Request.Source;
            response.Source      = MyAddress;
            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ServerSendResponse, response, exchange);

            item.Source = MyAddress;
            Pump.Queue.Enqueue(item);
        }
        void IOutbox.SendEmptyMessage(Exchange exchange, EmptyMessage message)
        {
            Matcher.SendEmptyMessage(exchange, message);

            if (!message.IsCancelled)
            {
                MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ClientSendEmptyMessageNetwork, message);
                item.Destination = message.Destination;
                item.Source      = MyAddress;
                Pump.Queue.Enqueue(item);
            }
        }
        private void Reject(Message message)
        {
            EmptyMessage rst = EmptyMessage.NewRST(message);

            if (!rst.IsCancelled)
            {
                MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ClientSendEmptyMessageNetwork, rst);
                item.Destination = message.Destination;
                item.Source      = MyAddress;
                Pump.Queue.Enqueue(item);
            }
        }
示例#8
0
        /// <inheritdoc />
        public void DeliverRequest(Exchange exchange)
        {
            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ServerSendRequest, exchange.Request, exchange);

            Pump.Queue.Enqueue(item);
        }
        public bool Pump()
        {
            List <MockStack> serverStacks;

            if (Queue.Count == 0)
            {
                return(false);
            }

            MockQueueItem item = Queue.Peek();

            switch (item.ItemType)
            {
            //  state #1 - client requested a send of a request
            case MockQueueItem.QueueType.ClientSendRequest:
                Queue.Dequeue();
                if (item.Request.Destination == null)
                {
                    item.Request.Destination = ServerAddress;
                }

                ClientStack.SendRequest(item.Request);
                break;

            //  state #2 - client ready for network send
            case MockQueueItem.QueueType.ClientSendRequestNetwork:
                Queue.Dequeue();
                MessageEncoder encoder        = new Spec.MessageEncoder18();
                byte[]         encodedRequest = encoder.Encode(item.Request);
                EndPoint       destination    = item.Request.Destination;

                item             = new MockQueueItem(MockQueueItem.QueueType.ServerSendRequestNetwork, encodedRequest);
                item.Source      = ClientAddress;
                item.Destination = destination;
                Queue.Enqueue(item);
                break;

            //  state #3 - server receives network send
            case MockQueueItem.QueueType.ServerSendRequestNetwork:
                Queue.Dequeue();
                serverStacks = ServerStacks[item.Destination];
                foreach (MockStack s in serverStacks)
                {
                    s.MyEndPoint.ReceiveData(item);
                }

                break;

            //  state #4 - server application receives request
            case MockQueueItem.QueueType.ServerSendRequest:
                break;


            // state #5 - server sends an response
            case MockQueueItem.QueueType.ServerSendResponse:
                Queue.Dequeue();
                serverStacks = ServerStacks[item.Source];
                Assert.AreEqual(1, serverStacks.Count);
                foreach (MockStack s in serverStacks)
                {
                    s.SendResponse(item.Exchange, item.Response);
                }

                break;

            // state #6 - server ready to send over network
            case MockQueueItem.QueueType.ServerSendResponseNetwork:
                Queue.Dequeue();
                encoder = new Spec.MessageEncoder18();
                byte[] encodedResponse = encoder.Encode(item.Response);

                MockQueueItem item2 = new MockQueueItem(MockQueueItem.QueueType.ClientSendResponseNetwork, encodedResponse);
                item2.Source      = item.Response.Source;
                item2.Destination = item.Response.Destination;
                Queue.Enqueue(item2);
                break;

            // state #7 - client receives response over network
            case MockQueueItem.QueueType.ClientSendResponseNetwork:
                Queue.Dequeue();

                serverStacks = ServerStacks[item.Destination];
                Assert.AreEqual(1, serverStacks.Count);
                foreach (MockStack s in serverStacks)
                {
                    s.MyEndPoint.ReceiveData(item);
                }

                break;

            case MockQueueItem.QueueType.ClientSendResponse:
                break;

            // state #8 - client application to process response
            case MockQueueItem.QueueType.ClientSendEmptyMessageNetwork:
                Queue.Dequeue();
                encoder        = new Spec.MessageEncoder18();
                encodedRequest = encoder.Encode(item.EmptyMessage);

                item2             = new MockQueueItem(MockQueueItem.QueueType.ServerSendEmptyMessageNetwork, encodedRequest);
                item2.Source      = item.Source;
                item2.Destination = item.EmptyMessage.Destination;
                Queue.Enqueue(item2);
                break;

            //  state #3 - server receives network send
            case MockQueueItem.QueueType.ServerSendEmptyMessageNetwork:
                Queue.Dequeue();
                serverStacks = ServerStacks[item.Destination];
                foreach (MockStack s in serverStacks)
                {
                    s.MyEndPoint.ReceiveData(item);
                }
                break;

            case MockQueueItem.QueueType.NetworkSend:
                Queue.Dequeue();
                List <MockChannel> channels = ChannelsByEndpoint[item.Destination];

                foreach (MockChannel c in channels)
                {
                    c.ReceiveData(item);
                }

                break;


            default:
                Assert.Fail("Unknown item in the pump");
                break;
            }

            return(Queue.Count > 0);
        }
        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);
        }
        public void ReceiveData(MockQueueItem item)
        {
            IMessageDecoder decoder = Spec.NewMessageDecoder(item.ItemData);

            if (decoder.IsRequest)
            {
                Request request = decoder.DecodeRequest();

                request.Source      = item.Source;
                request.Destination = item.Destination;

                Exchange exchange = Matcher.ReceiveRequest(request);
                exchange.EndPoint = this;

                request.Session = Session;

                Stack.ReceiveRequest(exchange, request);
            }
            else if (decoder.IsResponse)
            {
                Response response = decoder.DecodeResponse();

                response.Source  = item.Source;
                response.Session = Session;
                Exchange exchange = Matcher.ReceiveResponse(response);
                if (exchange != null)
                {
                    exchange.EndPoint = this;
                    Stack.ReceiveResponse(exchange, response);
                }
                else if (response.Type != MessageType.ACK)
                {
                    Reject(response);
                }
            }
            else if (decoder.IsEmpty)
            {
                EmptyMessage message;

                try {
                    message = decoder.DecodeEmptyMessage();
                }
                catch (Exception ex) {
                    return;
                }

                message.Source = item.Source;

                if (!message.IsCancelled)
                {
                    // CoAP Ping
                    if (message.Type == MessageType.CON || message.Type == MessageType.NON)
                    {
                        Reject(message);
                    }
                    else
                    {
                        Exchange exchange = Matcher.ReceiveEmptyMessage(message);
                        if (exchange != null)
                        {
                            exchange.EndPoint = this;
                            Stack.ReceiveEmptyMessage(exchange, message);
                        }
                    }
                }
            }
            else
            {
                Assert.Fail();
            }
        }
示例#12
0
        public void ReceiveData(MockQueueItem item)
        {
            DataReceivedEventArgs args = new DataReceivedEventArgs(item.ItemData, item.Source, item.Destination, Session);

            DataReceived?.Invoke(this, args);
        }
        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));
        }
示例#14
0
        private void CommonTestCode(Method method, bool longRequest, bool longResponse, int expectedClient, int expectedServer)
        {
            string requestText = null;

            byte[] observeToken = new byte[] { 0xa, 0xa, 0xa };
            int    observeNum   = 0;

            string[] currentResourceContent = new string[2];

            Type[]          layerTypes = new Type[] { typeof(BlockwiseLayer) };
            MockMessagePump pump       = new MockMessagePump(layerTypes, ClientConfig, ServerConfig);

            Request r = new Request(method);

            if (method == Method.POST)
            {
                requestText = longRequest ? LongPostRequest : ShortPostRequest;
                currentResourceContent[0] = longResponse ? LongPostResponse : ShortPostReponse;
                r.PayloadString           = requestText;
            }
            else
            {
                currentResourceContent[0] = longResponse ? LongGetResponse : ShortGetResponse;
                if (Observe)
                {
                    r.Observe = 1;
                    r.Token   = observeToken;
                }
            }
            pump.SendRequest(r);

            if (Parallel)
            {
                Request r2 = new Request(method)
                {
                    UriPath = "/resource2"
                };
                currentResourceContent[1] = longResponse ? LongGetResponse.Replace("get ", "getA") : ShortGetResponse + "P";
                pump.SendRequest(r2);
            }

            int      clientCount     = 0;
            int      serverCount     = 0;
            int      success         = 0;
            Exchange observeExchange = null;

            while (pump.Pump())
            {
                MockQueueItem item = pump.Queue.Peek();

                switch (item.ItemType)
                {
                //  Check conditions of the request when ready to transmit it on the wire
                case MockQueueItem.QueueType.ClientSendRequestNetwork:
                    if (Observe)
                    {
                        if (item.Request.HasOption(OptionType.Observe))
                        {
                            Assert.IsFalse(item.Request.HasOption(OptionType.Block2));
                        }
                        else
                        {
                            Assert.IsTrue(item.Request.Block2.NUM > 0);
                        }
                    }

                    clientCount += 1;
                    break;

                //  Check conditions of the response when ready to transmit it on the wire
                case MockQueueItem.QueueType.ServerSendResponseNetwork:
                    if (Observe)
                    {
                        if (item.Response.HasOption(OptionType.Observe))
                        {
                            Assert.AreEqual(0, item.Response.Block2.NUM);
                            CollectionAssert.AreEqual(observeToken, item.Response.Token);
                        }
                        else
                        {
                            Assert.IsTrue(item.Response.Block2.NUM > 0);
                            CollectionAssert.AreNotEqual(observeToken, item.Response.Token);
                        }
                    }
                    serverCount += 1;
                    break;

                // Server Resource is going to respond
                case MockQueueItem.QueueType.ServerSendRequest:
                    pump.Queue.Dequeue();
                    if (method == Method.POST)
                    {
                        Assert.AreEqual(requestText, item.Request.PayloadString);
                    }
                    else
                    {
                        Assert.AreEqual(0, item.Request.PayloadSize);
                    }

                    Response s = new Response(StatusCode.Content);
                    s.PayloadString = currentResourceContent[0];

                    if (Parallel && item.Request.UriPath == "/resource2")
                    {
                        s.PayloadString = currentResourceContent[1];
                    }

                    if (Observe && item.Request.HasOption(OptionType.Observe))
                    {
                        s.Observe       = 3;
                        observeExchange = item.Exchange;
                        s.Type          = MessageType.NON;
                    }

                    item.Exchange.EndPoint.SendResponse(item.Exchange, s);
                    break;

                case MockQueueItem.QueueType.ClientSendResponse:
                    pump.Queue.Dequeue();

                    if (Parallel && item.Exchange.Request.UriPath == "/resource2")
                    {
                        Assert.AreEqual(currentResourceContent[1], item.Response.PayloadString);
                        currentResourceContent[1] = currentResourceContent[0].Replace("get ", "get9");
                    }
                    else
                    {
                        Assert.AreEqual(currentResourceContent[0], item.Response.PayloadString);
                        currentResourceContent[0] = currentResourceContent[0].Replace("get ", "get3");
                    }

                    success += 1;

                    //  For observe, send a second observe out
                    if (Observe && observeNum == 0)
                    {
                        observeNum += 1;


                        s = new Response(StatusCode.Content)
                        {
                            PayloadString = currentResourceContent[0],
                            Observe       = 5,
                            Type          = MessageType.NON
                        };

                        List <MockStack> stacks = pump.ServerStacks[MockMessagePump.ServerAddress];
                        stacks[0].MyEndPoint.SendResponse(observeExchange, s);
                    }

                    break;
                }
            }

            if (Parallel || Observe)
            {
                Assert.AreEqual(2, success);
            }
            else
            {
                Assert.AreEqual(1, success);
            }

            Assert.AreEqual(expectedClient, clientCount);
            Assert.AreEqual(expectedServer, serverCount);
        }
示例#15
0
        public void BlockwiseTest7()
        {
            string response2 = LongGetResponse.Replace("get ", "get2");

            string responseText;

            Request r = new Request(Method.GET)
            {
                Destination = MockMessagePump.MulticastAddress
            };

            responseText = LongGetResponse;

            MockMessagePump pump = new MockMessagePump(new Type[] { typeof(BlockwiseLayer) }, ClientConfig, ServerConfig);

            int clientCount = 0;
            int serverCount = 0;
            int success     = 0;
            int sent        = 0;

            pump.SendRequest(r);
            while (pump.Pump())
            {
                MockQueueItem item = pump.Queue.Peek();

                switch (item.ItemType)
                {
                case MockQueueItem.QueueType.ClientSendRequestNetwork:
                    clientCount += 1;
                    break;

                case MockQueueItem.QueueType.ServerSendResponseNetwork:
                    serverCount += 1;
                    break;

                case MockQueueItem.QueueType.ServerSendRequest:
                    pump.Queue.Dequeue();
                    Assert.AreEqual(0, item.Request.PayloadSize);

                    Response s = new Response(StatusCode.Content);
                    s.PayloadString = (sent == 0) ? responseText : response2;
                    sent           += 1;
                    item.Exchange.EndPoint.SendResponse(item.Exchange, s);
                    break;

                case MockQueueItem.QueueType.ClientSendResponse:
                    pump.Queue.Dequeue();

                    if (item.Response.PayloadString == responseText)
                    {
                        Assert.IsTrue((success & 1) == 0);
                        success |= 1;
                    }
                    else if (item.Response.PayloadString == response2)
                    {
                        Assert.IsTrue((success & 2) == 0);
                        success |= 2;
                    }
                    else
                    {
                        Assert.Fail();
                    }

                    break;
                }
            }

            Assert.AreEqual(3, success);
            Assert.AreEqual(21, clientCount);
            Assert.AreEqual(22, serverCount);
        }
示例#16
0
        /// <inheritdoc />
        public void DeliverResponse(Exchange exchange, Response response)
        {
            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.ClientSendResponse, response, exchange);

            Pump.Queue.Enqueue(item);
        }
示例#17
0
        /// <inheritdoc />
        public void Send(byte[] data, ISession session, EndPoint ep)
        {
            MockQueueItem item = new MockQueueItem(MockQueueItem.QueueType.NetworkSend, data);

            item.Destination = ep;
            item.Source      = LocalEndPoint;

            MessageDecoder decoder = new Spec.MessageDecoder18(data);

            if (decoder.IsRequest)
            {
                item.Request = decoder.DecodeRequest();
            }
            else if (decoder.IsResponse)
            {
                item.Response = decoder.DecodeResponse();
            }
            else if (decoder.IsEmpty)
            {
                item.EmptyMessage = decoder.DecodeEmptyMessage();
            }
            else
            {
                throw new Exception("UNKNOWN MESSAGE TYPE");
            }

            DeliveryInstrutions rule = DeliveryInstrutions.Deliver;

            if (DeliveryRules != null && deliveryPoint < DeliveryRules.Length)
            {
                int defer = -1;
                switch (DeliveryRules[deliveryPoint])
                {
                case DeliveryInstrutions.Deliver:
                    break;

                case DeliveryInstrutions.DeferBy1:
                case DeliveryInstrutions.DeferBy2:
                case DeliveryInstrutions.DeferBy3:
                case DeliveryInstrutions.DeferBy4:
                case DeliveryInstrutions.DeferBy5:
                    defer = DeliveryRules[deliveryPoint] - DeliveryInstrutions.DeferBy1 + 1;
                    rule  = DeliveryInstrutions.Omit;
                    break;

                case DeliveryInstrutions.DupAndDeferBy0:
                case DeliveryInstrutions.DupAndDeferBy1:
                case DeliveryInstrutions.DupAndDeferBy2:
                case DeliveryInstrutions.DupAndDeferBy3:
                case DeliveryInstrutions.DupAndDeferBy4:
                    defer = DeliveryRules[deliveryPoint] - DeliveryInstrutions.DupAndDeferBy0;
                    break;
                }

                if (defer >= 0)
                {
                    int insertAt = 0;
                    foreach (TransportItem t in DelayList)
                    {
                        if (t.DelayCount > defer)
                        {
                            break;
                        }

                        insertAt += 1;
                    }

                    DelayList.Insert(insertAt, new TransportItem(item, defer));
                }
            }

            if (rule == DeliveryInstrutions.Deliver)
            {
                Pump.Queue.Enqueue(item);
            }

            if (DelayList.Count > 0)
            {
                int removeCount = 0;
                foreach (TransportItem t in DelayList)
                {
                    t.DelayCount -= 1;
                    if (t.DelayCount == 0)
                    {
                        Pump.Queue.Enqueue(t.Item);
                        removeCount += 1;
                    }
                }

                if (removeCount > 0)
                {
                    DelayList.RemoveRange(0, removeCount);
                }
            }
        }
        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);
        }
示例#19
0
 public TransportItem(MockQueueItem item, int delay)
 {
     Item       = item;
     DelayCount = delay;
 }
        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);
        }