public async Task WriteMessageFrameAsync(MessageFrame messageFrame, CancellationToken cancellationToken)
        {
            if (messageFrame == null) throw new ArgumentNullException("messageFrame");
            if (messageFrame.RawMessage == null) throw new ArgumentException("messageFrame.RawMessage cannot be null");

            await CreateBufferWriteSingleAsync(messageFrame, cancellationToken);
        }
Example #2
0
    void Awake()
    {
        ws = GameObject.FindGameObjectWithTag("ServerController").
             GetComponent <ConnectionController> ();

        ws.OnConnect((sender, e) => {
            Debug.Log("Connected at server");
            ws.Emit("login", nickname);
            loginPanel.SetActive(false);
            chatPanel.SetActive(true);
        });

        ws.On("message", (data) => {
            ChatMessage chatMessage = JsonConvert.DeserializeObject <ChatMessage> (data);

            Vector3 framePos = new Vector3(content.position.x,
                                           content.position.y,
                                           content.position.z);

            GameObject goFrame = Instantiate(messageFrame,
                                             framePos,
                                             Quaternion.identity)
                                 as GameObject;

            goFrame.transform.SetParent(content);

            MessageFrame mf      = goFrame.GetComponent <MessageFrame> ();
            mf.nameFrame.text    = chatMessage.name;
            mf.messageFrame.text = chatMessage.message;

            messageField.text = "";
        });
    }
        public void WriteMessageFrame(MessageFrame messageFrame)
        {
            if (messageFrame == null) throw new ArgumentNullException("messageFrame");
            if (messageFrame.RawMessage == null) throw new ArgumentException("messageFrame.RawMessage cannot be null");

            CreateBufferWriteSingle(messageFrame);
        }
        public async Task WriteMessageFrameAsync(MessageFrame messageFrame, CancellationToken cancellationToken)
        {
            if (messageFrame == null) throw new ArgumentNullException("messageFrame");
            if (messageFrame.RawMessage == null) throw new ArgumentException("messageFrame.RawMessage cannot be null");

            _queueSocket.Write(messageFrame);
        }
        public void WriteMessageFrame(MessageFrame messageFrame)
        {
            if (messageFrame == null) throw new ArgumentNullException("messageFrame");
            if (messageFrame.RawMessage == null) throw new ArgumentException("messageFrame.RawMessage cannot be null");

            _queueSocket.Write(messageFrame);
        }
Example #6
0
        public static void Write(this Stream stream, MessageFrame message)
        {
            var buffer = message.ToBytes();

            stream.Write(buffer, 0, buffer.Length);
            stream.Flush();
        }
        public void code_decode_with_properties_test()
        {
            var bufMgr  = new BufferManager(65535, 1);
            var context = new WriterContext(bufMgr);
            var buf     = bufMgr.Dequeue();

            bufMgr.Enqueue(buf);

            var sut = new MessageFrame();

            sut.SequenceNumber = 22;
            sut.Properties.Add("hello", "world");
            var payload = Encoding.UTF8.GetBytes("Hello world");

            sut.PayloadBuffer = new ArraySegment <byte>(payload, 0, payload.Length);
            sut.Write(context);

            var pos    = 0;
            var len    = context.GetPackets().First().Count;
            var frame2 = new MessageFrame();

            frame2.Read(buf.Array, ref pos, ref len);
            frame2.SequenceNumber.Should().Be(22);
            Encoding.ASCII.GetString(sut.PayloadBuffer.Array, 0, sut.PayloadBuffer.Count).Should().Be("Hello world");
            sut.Properties["hello"].Should().Be("world");
        }
        public void deserualize_Simplistic_filter()
        {
            var filter = Encoding.ASCII.GetBytes("last_name<kalle");
            var buffer = new byte[]
            {
                0,                                                                                                 //flags,
                0, 2,                                                                                              // sequence number,
                2,                                                                                                 //destination length,
                (byte)'M', (byte)'Q',
                0, 15,                                                                                             // filter length
                (byte)'l', (byte)'a', (byte)'s', (byte)'t', (byte)'_', (byte)'n', (byte)'a', (byte)'m', (byte)'e', //filter part 1
                (byte)':', (byte)'k', (byte)'a', (byte)'l', (byte)'l', (byte)'e',                                  //filter part 2
                6,                                                                                                 //payload length
                (byte)'m', (byte)'o', (byte)'t', (byte)'h', (byte)'e', (byte)'r'                                   //payload
            };
            var offset = 0;
            var count  = buffer.Length;

            var sut    = new MessageFrame();
            var actual = sut.Read(buffer, ref offset, ref count);

            actual.Should().Be(true);
            sut.Destination.Should().Be("MQ");
            sut.Properties["last_name"].Should().Be("kalle");
        }
Example #9
0
        private static void OnFrame(ServerClient channel, MessageFrame frame)
        {
            var msg = Encoding.ASCII.GetString(frame.PayloadBuffer.Array, frame.PayloadBuffer.Offset,
                                               frame.PayloadBuffer.Count);

            Console.WriteLine("Received '" + msg + "' from " + channel.RemoteEndPoint);
        }
        public void AddFrame(MessageFrame frame)
        {
            if (_framesToAck.Count >= _maxAmountOfPendingMessages)
            {
                throw new AckException(string.Format("There are already {0} awaiting an ACK. HOLD ON!",
                                                     _framesToAck.Count));
            }

            _receivedMessages.Add(frame.SequenceNumber);
            if (frame.SequenceNumber < _lastSeq)
            {
                LogMessage("ERROR: " + frame.SequenceNumber + ", last: " + _lastSeq);
            }
            _lastSeq = frame.SequenceNumber;


            lock (_framesToAck)
            {
                //less since we should include this message in the count
                if (_framesToAck.Count < Threshold)
                {
                    _sendCounter++;
                    _framesToAck.Enqueue(new FrameWrapper(frame));
                    _deliverMessageMethod(frame);
                }
                else
                {
                    _framesToAck.Enqueue(new FrameWrapper(frame));
                }
            }
        }
Example #11
0
        private void OnMessageFrame(MessageFrame frame)
        {
            if (_state != ServerState.Ready)
            {
                throw new Exception("Handshake not completed, should not have received a message frame.");
            }


            if (_payloadSerializer != null)
            {
                if (_payloadDotNetType != null)
                {
                    frame.Payload = frame.PayloadStream == null
                        ? _payloadSerializer.Deserialize(_payloadDotNetType, frame.PayloadBuffer.Array,
                                                         frame.PayloadBuffer.Offset,
                                                         frame.PayloadBuffer.Count)
                        : _payloadSerializer.Deserialize(_payloadDotNetType, frame.PayloadStream);
                }
                else
                {
                    frame.Payload = frame.PayloadStream == null
                        ? _payloadSerializer.Deserialize(frame.PayloadBuffer.Array,
                                                         frame.PayloadBuffer.Offset,
                                                         frame.PayloadBuffer.Count)
                        : _payloadSerializer.Deserialize(frame.PayloadStream);
                }
            }

            if (_ackSender == null || _ackSender.AddFrame(frame))
            {
                FrameReceived(this, frame);
            }
        }
        public void CheckSortMessagesByAllCriteria_MessagesSorted_ReturnsSortedList()
        {
            //Arrange
            MessageFrame messages1 = new MessageFrame();
            MessageFrame messages2 = new MessageFrame();

            //Act
            for (int i = 0; i <= 50; i++)
            {
                Guid    id = new Guid();
                Message m  = new Message("test" + i, DateTime.Now, id, new User("test" + i, "test", i.ToString()));
                messages1.NewUserMessage(m);
            }
            messages2.messages = messages1.messages;
            List <Message> l2 = messages2.messages.ToList();

            Shuffle(l2);
            var queue = new Queue <Message>(l2);

            messages2.messages = queue;
            messages2.SortingMethods("All Criteria", true);

            //Assert
            Assert.AreEqual(messages1.messages, messages2.messages);
        }
Example #13
0
        internal async Task <T> QueryWebsocketOneCallAsync <T>(string functionName, object payload = null)
        {
            if (string.IsNullOrWhiteSpace(functionName))
            {
                throw new ArgumentNullException(nameof(functionName));
            }

            // Wrap all calls in a frame object.
            var frame = new MessageFrame
            {
                FunctionName   = functionName,
                MessageType    = MessageType.Request,
                SequenceNumber = GetNextSequenceNumber(),
                Payload        = JsonConvert.SerializeObject(payload)
            };

            var tcs             = new TaskCompletionSource <T>();
            var handlerFinished = tcs.Task;

            using (ConnectWebSocketAsync("", (socket, bytes) =>
            {
                var messageFrame = JsonConvert.DeserializeObject <MessageFrame>(bytes.ToStringFromUTF8().TrimEnd('\0'));
                tcs.SetResult(messageFrame.PayloadAs <T>());
                return(Task.CompletedTask);
            }, async socket =>
            {
                await socket.SendMessageAsync(frame);
            }))
            {
                return(await handlerFinished);
            }
        }
        private void Benchmark(SharpMessagingClient client)
        {
            var buffer = MessageSize < 12
                ? Encoding.ASCII.GetBytes("1".PadLeft(MessageSize, '0'))
                : Encoding.ASCII.GetBytes("\"hello world ".PadRight(9999) + "\"");
            var payload = new ArraySegment <byte>(buffer);

            Console.WriteLine(DateTime.UtcNow.ToString("HH:mm:ss.fff") + " Starting");
            for (var i = 1; i < MessageCount; i++)
            {
                var frame = new MessageFrame
                {
                    PayloadBuffer = payload
                };
                client.Send(frame);
            }

            // packet to mark the end.
            client.Send(new MessageFrame
            {
                PayloadBuffer =
                    new ArraySegment <byte>(new[]
                                            { (byte)'"', (byte)'m', (byte)'o', (byte)'t', (byte)'h', (byte)'e', (byte)'r', (byte)'"' })
            });
        }
Example #15
0
        /// <summary>
        /// Read data sent by the master.
        /// </summary>
        /// <returns></returns>
        public MessageFrame ReceiveData()
        {
            var receivedData = new List <ushort>(_slave.DataStore.InputRegisters.Count);

            foreach (var registerValue in _slave.DataStore.InputRegisters)
            {
                if (registerValue == 0x00)
                {
                    break;
                }

                receivedData.Add(registerValue);
            }

            var messageFrame  = new MessageFrame();
            var stringBuilder = new StringBuilder();

            messageFrame.FunctionCode = (FunctionCode)receivedData[0];
            for (int i = 1; i < receivedData.Count; i++)
            {
                stringBuilder.Append((char)receivedData[i]);
            }

            messageFrame.Data = stringBuilder.ToString();

            return(messageFrame);
        }
        public void MessageFrameStreamWriter_writes_MessageFrameStreamReader_reads()
        {
            var random        = TestHelpers.CreateSemiRandomGenerator();
            var messageFrames = new Queue <MessageFrame>();

            using (var mem = new MemoryStream())
                using (var socket = new TestStreamSocket(mem))
                {
                    var writer = new MessageFrameStreamWriter(socket);
                    var reader = new MessageFrameStreamReader(socket);

                    for (var i = 0; i < 1000; i++)
                    {
                        var messageFrame = new MessageFrame
                        {
                            MessageTypeId = (ushort)random.Next(0, UInt16.MaxValue),
                            RawMessage    = TestHelpers.GetRandomBytes(random, random.Next(100 * i))
                        };
                        messageFrames.Enqueue(messageFrame);
                        writer.WriteMessageFrame(messageFrame);
                    }

                    mem.Position = 0;
                    while (messageFrames.Count > 0)
                    {
                        var messageFrameWritten = messageFrames.Dequeue();
                        var messageFrameRead    = reader.ReadMessageFrame();

                        Assert.AreEqual(messageFrameWritten, messageFrameRead);
                    }
                }
        }
Example #17
0
        public void deliver_last_frame_within_the_specified_ack_count()
        {
            var          connection     = Substitute.For <IConnection>();
            MessageFrame deliveredFrame = null;

            var sut = new AckReceiver(connection, frame => deliveredFrame = frame, 5);

            sut.Send(new MessageFrame {
                SequenceNumber = 1
            });
            sut.Send(new MessageFrame {
                SequenceNumber = 2
            });
            sut.Send(new MessageFrame {
                SequenceNumber = 3
            });
            sut.Send(new MessageFrame {
                SequenceNumber = 4
            });
            sut.Send(new MessageFrame {
                SequenceNumber = 5
            });

            deliveredFrame.SequenceNumber.Should().Be(5);
        }
Example #18
0
 public StompMessage(IStompClient client, MessageFrame messageFrame, bool acknowledgeable, string transactionId = null)
 {
     _client           = client;
     MessageFrame      = messageFrame;
     IsAcknowledgeable = acknowledgeable;
     _transactionId    = transactionId;
 }
Example #19
0
        public bool AddFrame(MessageFrame frame)
        {
            if (_lastAckTime == DateTime.MinValue)
            {
                _lastAckTime = DateTime.UtcNow;
            }

            //send acks directly for frames that we've already acked.
            if (ShouldReAck(frame))
            {
                _lastAckTime             = DateTime.UtcNow;
                _lastAckedSequenceNumber = _lastReceivedSequenceNumber;
                _numberOfFramesToAck     = 0;
                _connection.Send(new AckFrame(_extensionId, (ushort)_lastReceivedSequenceNumber));
                return(false);
            }

            lock (_syncLock)
            {
                _lastReceivedSequenceNumber = frame.SequenceNumber;
                ++_amountNotAcked;
                if (_amountNotAcked < Threshold)
                {
                    return(true);
                }

                _lastAckTime             = DateTime.UtcNow;
                _lastAckedSequenceNumber = frame.SequenceNumber;
                _connection.Send(new AckFrame(_extensionId, frame.SequenceNumber));
                _amountNotAcked = 0;
            }

            return(true);
        }
Example #20
0
        public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout)
        {
            if (m_TS == -1)
            {
                throw new Exception("Source address must be set up before sending messages");
            }

            //add to queue
            BacnetNpduControls   function   = NPDU.DecodeFunction(buffer, offset);
            BacnetMstpFrameTypes frame_type = (function & BacnetNpduControls.ExpectingReply) == BacnetNpduControls.ExpectingReply ? BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY : BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY;

            byte[] copy = new byte[data_length + MSTP.MSTP_HEADER_LENGTH + 2];
            Array.Copy(buffer, offset, copy, MSTP.MSTP_HEADER_LENGTH, data_length);
            MessageFrame f = new MessageFrame(frame_type, address.adr[0], copy, data_length);

            lock (m_send_queue)
                m_send_queue.AddLast(f);
            if (m_reply == null)
            {
                m_reply = f;
                m_reply_mutex.Set();
            }

            //wait for message to be sent
            if (wait_for_transmission)
            {
                if (!f.send_mutex.WaitOne(timeout))
                {
                    return(-ETIMEDOUT);
                }
            }

            return(data_length);
        }
Example #21
0
        private void SendFrame(MessageFrame frame)
        {
            if (m_TS == -1 || m_port == null)
            {
                return;
            }
            int tx;

            if (frame.data == null || frame.data.Length == 0)
            {
                byte[] tmp_transmit_buffer = new byte[MSTP.MSTP_HEADER_LENGTH];
                tx = MSTP.Encode(tmp_transmit_buffer, 0, frame.frame_type, frame.destination_address, (byte)m_TS, 0);
                m_port.Write(tmp_transmit_buffer, 0, tx);
            }
            else
            {
                tx = MSTP.Encode(frame.data, 0, frame.frame_type, frame.destination_address, (byte)m_TS, frame.data_length);
                m_port.Write(frame.data, 0, tx);
            }
            frame.send_mutex.Set();

            //debug
            if (StateLogging)
            {
                Trace.WriteLine("         " + frame.frame_type + " " + frame.destination_address.ToString("X2") + " ");
            }
        }
        public void Send(MessageFrame frame)
        {
            //if (!_authenticationEvent.WaitOne(100000))
            //    throw new InvalidOperationException("Handshake was not completed in a reasonable time.");

            if (frame.PayloadBuffer.Count == 0)
            {
                Debugger.Break();
            }

            frame.SequenceNumber = ++_sequenceCounter;
            if (_sequenceCounter == ushort.MaxValue)
            {
                _sequenceCounter = 0;
            }

            if (_ackReceiver != null)
            {
                _ackReceiver.AddFrame(frame);
            }
            else
            {
                DeliverMessage(frame);
            }
        }
        public void MessageFrameStreamWriter_writes_MessageFrameStreamReader_reads()
        {
            var random = TestHelpers.CreateSemiRandomGenerator();
            var messageFrames = new Queue<MessageFrame>();
            using (var mem = new MemoryStream())
            using (var socket = new TestStreamSocket(mem))
            {
                var writer = new MessageFrameStreamWriter(socket);
                var reader = new MessageFrameStreamReader(socket);

                for (var i = 0; i < 1000; i++)
                {
                    var messageFrame = new MessageFrame
                    {
                        MessageTypeId = (ushort) random.Next(0, UInt16.MaxValue),
                        RawMessage = TestHelpers.GetRandomBytes(random, random.Next(100 * i))
                    };
                    messageFrames.Enqueue(messageFrame);
                    writer.WriteMessageFrame(messageFrame);
                }

                mem.Position = 0;
                while (messageFrames.Count > 0)
                {
                    var messageFrameWritten = messageFrames.Dequeue();
                    var messageFrameRead = reader.ReadMessageFrame();

                    Assert.AreEqual(messageFrameWritten, messageFrameRead);
                }
            }
        }
        public void the_10kb_payload()
        {
            var bufMgr  = new BufferManager(65535, 1);
            var context = new WriterContext(bufMgr);
            var buf     = bufMgr.Dequeue();

            bufMgr.Enqueue(buf);

            var sut = new MessageFrame();

            sut.SequenceNumber = 22;
            var payload = Encoding.ASCII.GetBytes("Hello world".PadRight(10000));

            sut.PayloadBuffer = new ArraySegment <byte>(payload, 0, payload.Length);
            sut.Write(context);

            var pos    = 0;
            var len    = context.GetPackets().First().Count;
            var frame2 = new MessageFrame();

            frame2.Read(buf.Array, ref pos, ref len);
            frame2.SequenceNumber.Should().Be(22);
            frame2.IsFlaggedAsSmall.Should().BeFalse();
            Encoding.ASCII.GetString(sut.PayloadBuffer.Array, 0, sut.PayloadBuffer.Count).TrimEnd(' ').Should().Be("Hello world");
        }
        private void OnMessageFrame(MessageFrame frame)
        {
            if (_state != ClientState.Ready)
            {
                throw new Exception("Handshake not completed, should not have received a message frame.");
            }

            if (_payloadSerializer == null)
            {
                FrameReceived(frame);
                return;
            }

            if (_payloadDotNetType != null)
            {
                frame.Payload = frame.IsFlaggedAsSmall
                    ? _payloadSerializer.Deserialize(_payloadDotNetType, frame.PayloadBuffer.Array,
                                                     frame.PayloadBuffer.Offset,
                                                     frame.PayloadBuffer.Count)
                    : _payloadSerializer.Deserialize(_payloadDotNetType, frame.PayloadStream);
            }
            else
            {
                frame.Payload = frame.IsFlaggedAsSmall
                    ? _payloadSerializer.Deserialize(frame.PayloadBuffer.Array,
                                                     frame.PayloadBuffer.Offset,
                                                     frame.PayloadBuffer.Count)
                    : _payloadSerializer.Deserialize(frame.PayloadStream);
            }

            FrameReceived(frame);
        }
        public void doing_a_partial_payload_write_properly()
        {
            var bufMgr  = new BufferManager(5010, 1);
            var context = new WriterContext(bufMgr);
            var buf1    = bufMgr.Dequeue();

            bufMgr.Enqueue(buf1);
            var sut = new MessageFrame();

            sut.SequenceNumber = 22;
            var payload = Encoding.ASCII.GetBytes("Hello world".PadRight(10000));

            sut.PayloadBuffer = new ArraySegment <byte>(payload, 0, payload.Length);


            var actual1 = sut.Write(context);
            var pos     = 0;
            var len     = context.GetPackets().First().Count;
            var frame2  = new MessageFrame();

            frame2.Read(buf1.Array, ref pos, ref len);

            var actual2 = sut.Write(context);

            pos = 0;
            len = context.GetPackets().Last().Count;
            frame2.Read(buf1.Array, ref pos, ref len);


            frame2.SequenceNumber.Should().Be(22);
            frame2.IsFlaggedAsSmall.Should().BeFalse();
            Encoding.ASCII.GetString(sut.PayloadBuffer.Array, 0, sut.PayloadBuffer.Count).TrimEnd(' ').Should().Be("Hello world");
            actual1.Should().BeFalse();
            actual2.Should().BeTrue();
        }
Example #27
0
        /// <summary>
        /// Called in form of event by the Master form when user desires to send data to slave.
        /// </summary>
        /// <param name="slaveAddress">Destination address for the data to be delivered to. If equal to 0 - sent to everyone.</param>
        /// <param name="functionCode">Determines whether user wants to send data to slave or retrieve data from slave. Note that retrieval of data in broadcast is a big no-no.</param>
        /// <param name="dataToSend">Data to send to slave.</param>
        public void HandleSendToSlaveEvent(int slaveAddress, FunctionCode functionCode, string dataToSend)
        {
            if (functionCode == FunctionCode.RetrieveTextFromSlave && slaveAddress == 0)
            {
                MessageBox.Show(
                    "Cannot retrieve data from any slave in broadcast mode. Imagine that avalanche of zeros and ones trying to get through...",
                    "Wrong operation", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }

            var messageFrame = new MessageFrame
            {
                TargetSlaveAddress = slaveAddress,
                FunctionCode       = functionCode,
                Data = dataToSend
            };

            switch (functionCode)
            {
            case FunctionCode.SendTextFromMaster:
                SendRequestToSlave(messageFrame);
                break;

            case FunctionCode.RetrieveTextFromSlave:
                MessageFrame responseFrame = _masterService.SendRequest(messageFrame);
                masterForm.ShowSlaveData(responseFrame.Data);
                break;
            }
        }
        public void automatically_allocate_larger_payload_buffer()
        {
            var unix    = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
            var now     = new DateTime(2014, 10, 13, 13, 0, 0, DateTimeKind.Local).ToUniversalTime();
            var seconds = now.Subtract(unix).TotalSeconds;

            byte[] length = BitConverter.GetBytes(4096);
            if (BitConverter.IsLittleEndian)
            {
                Array.Reverse(length);
            }
            var buffer = new byte[4096 + 12];

            buffer[0]  = (byte)FrameFlags.LargeFrame; //flags,
            buffer[1]  = 0;                           //sequence
            buffer[2]  = 2;
            buffer[3]  = 2;                           //destination length
            buffer[4]  = (byte)'M';
            buffer[5]  = (byte)'Q';
            buffer[6]  = 0;         // filter length
            buffer[7]  = 0;         // filter length
            buffer[8]  = length[0]; //payload length
            buffer[9]  = length[1];
            buffer[10] = length[2];
            buffer[11] = length[3];
            var offset = 0;
            var count  = buffer.Length;

            var sut    = new MessageFrame();
            var actual = sut.Read(buffer, ref offset, ref count);

            actual.Should().Be(true);
            sut.PayloadBuffer.Array.Length.Should().BeGreaterThan(4096);
        }
Example #29
0
        private void OnTimeSync(ServerClient channel, MessageFrame frame)
        {
            if (_timeSyncCompleted)
            {
                OnFrame(channel, frame);
                return;
            }

            var data = Encoding.ASCII.GetString(frame.PayloadBuffer.Array, frame.PayloadBuffer.Offset,
                                                frame.PayloadBuffer.Count);

            var parts = data.Split(';');
            var time  = DateTime.Parse(parts[0]);

            var buffer =
                Encoding.ASCII.GetBytes((int)DateTime.UtcNow.Subtract(time).TotalMilliseconds + ";" +
                                        DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss.ffff"));

            channel.Send(new MessageFrame(buffer));

            //completed time sync
            if (parts.Length == 2)
            {
                Console.WriteLine("Time synchronization completed");
                _timeSyncCompleted = true;
            }
        }
Example #30
0
        public void TestBasicFeature()
        {
            var requestResponseService = new RequestResponseService <string, byte[]>(5555);

            requestResponseService.ReceiveMessage += ((header, payload) => new MessageFrame <string, byte[]>()
            {
                MessageType = "abc", Payload = new byte[] { 123 }
            });

            CancellationTokenSource cts = new CancellationTokenSource();

            var task = Task.Run(() =>
            {
                requestResponseService.Start(cts.Token);
            });

            var requestResponseClient = new RequestResponseClient <string, byte[]>("127.0.0.1", 5555);

            MessageFrame <string, byte[]> reply = requestResponseClient.SendRequest(new MessageFrame <string, byte[]>()
            {
                MessageType = "hellomessage", Payload = Encoding.ASCII.GetBytes("Hello World")
            });

            requestResponseService.Stop();

            if (!task.IsCompleted)
            {
                cts.Cancel();
            }

            Assert.AreEqual("abc", reply.MessageType);
            Assert.AreEqual(reply.Payload.Length, 1);
            Assert.AreEqual(reply.Payload[0], 123);
        }
Example #31
0
        private void SendFrame(MessageFrame frame)
        {
            if (SourceAddress == -1 || _port == null)
            {
                return;
            }
            int tx;

            if (frame.Data == null || frame.Data.Length == 0)
            {
                var tmpTransmitBuffer = new byte[MSTP.MSTP_HEADER_LENGTH];
                tx = MSTP.Encode(tmpTransmitBuffer, 0, frame.FrameType, frame.DestinationAddress,
                                 (byte)SourceAddress, 0);
                _port.Write(tmpTransmitBuffer, 0, tx);
            }
            else
            {
                tx = MSTP.Encode(frame.Data, 0, frame.FrameType, frame.DestinationAddress, (byte)SourceAddress,
                                 frame.DataLength);
                _port.Write(frame.Data, 0, tx);
            }
            frame.SendMutex.Set();

            //debug
            if (StateLogging)
            {
                Trace.WriteLine($"         {frame.FrameType} {frame.DestinationAddress.ToString("X2")} ");
            }
        }
Example #32
0
        /// <summary>
        /// Sends a message to slave. Does not wait for any data to be returned.
        /// </summary>
        /// <param name="messageFrame">Contains address and message to send.</param>
        public void SendMessage(MessageFrame messageFrame)
        {
            ushort[] message = messageFrame.GetMessageFrameInShorts();

            _master.WriteMultipleRegisters((byte)messageFrame.TargetSlaveAddress,
                                           (ushort)HoldingRegisterStartAddress, message);
        }
Example #33
0
 public void Reset()
 {
     lock (_syncLock)
     {
         _pendingFrame = null;
         _sentAt       = DateTime.MinValue;
     }
 }
 public void Confirm(AckFrame ackFrame)
 {
     lock (_syncLock)
     {
         //TODO: Add a sanity check for the sequence number (supporting wrapping numbers)
         _pendingFrame = null;
     }
 }
Example #35
0
        private MessageFrame ReadInputFromForm(FunctionCode functionCode)
        {
            string inputText    = slaveForm.ReadInputText();
            var    messageFrame = new MessageFrame {
                Data = inputText
            };

            return(messageFrame);
        }
Example #36
0
 public void Add(MessageFrame messageFrame)
 {
     if (messageFrame == null) throw new ArgumentNullException("messageFrame");
     if (_singleMessageFrames.TryAdd(messageFrame))
     {
         MessageCounterSignal.Increment();
         MessageFramesAdded(new [] { messageFrame });
     }
 }
        public void MessageQueue_Add_MessageCounterSignal_IsSet_true()
        {
            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueBatch(4096);
            messageQueue.Add(testMessageFrame);

            Assert.IsTrue(messageQueue.MessageCounterSignal.IsSet);
        }
        public MessageFrame CreateFromMessage(IMessage message)
        {
            if (message == null) throw new ArgumentNullException("message");

            var messageFrame = new MessageFrame
            {
                MessageTypeId = message.MessageTypeId,
                RawMessage = _messageSerialization.Serialize(message)
            };
            return messageFrame;
        }
        public async Task Register()
        {
            var registerMsg = new RegisterMessage();
            registerMsg.challengeId = challengeId;
            registerMsg.deviceId = deviceId;
            var registerMessage = new MessageFrame("register", registerMsg);

            string message = JsonConvert.SerializeObject(registerMessage);

            await connection.SendAsync(message);
            Debug.WriteLine("sent register message: " + message);
        }
        public void MessageQueue_Add_fires_MessageFrameAdded()
        {
            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueSingle();
            MessageFrame messageFrame = null;
            messageQueue.MessageFrameAdded += m => { messageFrame = m; };

            messageQueue.Add(testMessageFrame);
            
            Assert.AreSame(testMessageFrame, messageFrame);
        }
        public void MessageQueue_AddRange_fires_MessageFramesAdded()
        {
            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueBatch(4096);
            MessageFrame messageFrame = null;
            messageQueue.MessageFramesAdded += m => { messageFrame = m.Single(); };

            messageQueue.AddRange(new [] { testMessageFrame });

            Assert.AreSame(testMessageFrame, messageFrame);
        }
        public void MessageQueue_Add_single_message_SendMultipleFromQueue_writer_receives_message()
        {
            var messageFramesWritten = new List<MessageFrame>();
            var messageFramesWriter = CreateMessagFrameWriter(messageFramesWritten);

            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueBatch(4096);
            messageQueue.Add(testMessageFrame);

            messageQueue.SendMultipleFromQueue(messageFramesWriter);

            Assert.AreSame(testMessageFrame, messageFramesWritten.First());
        }
Example #43
0
 private void SendMessageFrame(IMessageFrameWriter writer, MessageFrame messageFrame)
 {
     try
     {
         writer.WriteMessageFrame(messageFrame);
     }
     catch
     {
         if (_resentMessageFrames.TryAdd(messageFrame))
         {
             Interlocked.Increment(ref _resentMessageFramesCount);
         }
         throw;
     }
 }
        public async Task Send(string msg)
        {

            try
            {
                EchoWithTimestamp echo = new EchoWithTimestamp(msg);
                var msgFrame = new MessageFrame("echo-request", echo);
                string message = JsonConvert.SerializeObject(msgFrame);

                Debug.WriteLine("SEND" + message);
                await connection.SendAsync(message);
            }
            catch (Exception e)
            {
                Debug.WriteLine("exception in Send(): " + e.Message);
            }

        }
        private void CreateBufferWriteSingle(MessageFrame messageFrame)
        {
            var sendBufferSize = MessageFrame.HeaderSize + messageFrame.RawMessage.Length;

            WeakReference<MemoryStream> reference;
            var mem = GetOrCreateMemoryStream(sendBufferSize, out reference);

            try
            {
                WriteTypeId(mem, messageFrame.MessageTypeId);
                WriteLength(mem, messageFrame.RawMessage.Length);
                WriteBody(mem, messageFrame.RawMessage);

                var toSend = mem.GetBuffer();
                _streamSocket.Write(toSend, 0, sendBufferSize);
            }
            finally
            {
                mem.SetLength(0);
                RecycledMemoryStreams.Enqueue(reference);
            }
        }
        public void MessageFrameStreamWriter_writes_MessageTypeId_then_Length_then_RawMessage()
        {
            var messageFrame = new MessageFrame
            {
                MessageTypeId = 54321,
                RawMessage = new byte[] { 1, 2, 3, 4, 5}
            };

            using (var mem = new MemoryStream())
            using (var socket = new TestStreamSocket(mem))
            {
                var writer = new MessageFrameStreamWriter(socket);
                writer.WriteMessageFrameAsync(messageFrame, CancellationToken.None).Wait();

                var writtenToStream = mem.ToArray();
                
                Assert.AreEqual(messageFrame.MessageTypeId, BitConverter.ToUInt16(writtenToStream, 0));
                Assert.AreEqual(messageFrame.RawMessage.Length, BitConverter.ToUInt16(writtenToStream, 2));

                Assert.AreEqual(messageFrame.RawMessage, writtenToStream.Skip(6).ToArray());
            }
        }
Example #47
0
        private void SendFrame(MessageFrame frame)
        {
            if (m_TS == -1 || m_port == null) return;
            int tx;
            if (frame.data == null || frame.data.Length == 0)
            {
                byte[] tmp_transmit_buffer = new byte[MSTP.MSTP_HEADER_LENGTH];
                tx = MSTP.Encode(tmp_transmit_buffer, 0, frame.frame_type, frame.destination_address, (byte)m_TS, 0);
                m_port.Write(tmp_transmit_buffer, 0, tx);
            }
            else
            {
                tx = MSTP.Encode(frame.data, 0, frame.frame_type, frame.destination_address, (byte)m_TS, frame.data_length);
                m_port.Write(frame.data, 0, tx);
            }
            frame.send_mutex.Set();

            //debug
            if (StateLogging) Trace.WriteLine("         " + frame.frame_type + " " + frame.destination_address.ToString("X2") + " ");
        }
 public void WriteGreeting(NodeGreetingMessage greetingMessage)
 {
     var messageFrame = new MessageFrame { RawMessage = greetingMessage.Serialize() };
     _queueSocket.Write(messageFrame);
 }
        public void MessageQueue_Add_single_message_SendFromQueueAsync_MessageCounterSignal_IsSet_false()
        {
            var messageFramesWritten = new List<MessageFrame>();
            var messageFramesWriter = CreateMessageFrameWriter(messageFramesWritten);

            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueSingle();
            messageQueue.Add(testMessageFrame);

            messageQueue.SendFromQueueAsync(messageFramesWriter, CancellationToken.None).Wait();

            Assert.IsFalse(messageQueue.MessageCounterSignal.IsSet);
        }
        public void MessageQueue_Add_single_message_SendFromQueueAsync_fails_once_then_succeeds_MessageCounterSignal_IsSet_false()
        {
            var errorMessageFrameWriter = CreateMessageFrameWriterThrowsIOException();
            var messageFramesWritten = new List<MessageFrame>();
            var messageFramesWriter = CreateMessageFrameWriter(messageFramesWritten);

            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueSingle();
            messageQueue.Add(testMessageFrame);

            Assert.Throws<AggregateException>(() => messageQueue.SendFromQueueAsync(errorMessageFrameWriter, CancellationToken.None).Wait());
            messageQueue.SendFromQueueAsync(messageFramesWriter, CancellationToken.None).Wait();

            Assert.IsFalse(messageQueue.MessageCounterSignal.IsSet);
        }
        public void MessageQueue_AddRange_two_messages_SendFromQueueAsync_twice_writer_receives_both_messages()
        {
            var messageFramesWritten = new List<MessageFrame>();
            var messageFramesWriter = CreateMessageFrameWriter(messageFramesWritten);

            var testMessageFrame1 = new MessageFrame();
            var testMessageFrame2 = new MessageFrame();

            var messageQueue = new MessageQueueSingle();
            messageQueue.AddRange(new[] { testMessageFrame1, testMessageFrame2 });

            messageQueue.SendFromQueueAsync(messageFramesWriter, CancellationToken.None).Wait();
            messageQueue.SendFromQueueAsync(messageFramesWriter, CancellationToken.None).Wait();

            Assert.AreSame(testMessageFrame1, messageFramesWritten.First());
            Assert.AreSame(testMessageFrame2, messageFramesWritten.Skip(1).Single());
        }
        public void MessageQueue_AddRange_two_messages_after_SendFromQueueAsync_twice_MessageCounterSignal_IsSet_false()
        {
            var messageFramesWritten = new List<MessageFrame>();
            var messageFramesWriter = CreateMessageFrameWriter(messageFramesWritten);

            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueSingle();
            messageQueue.AddRange(new[] { testMessageFrame, testMessageFrame });

            messageQueue.SendFromQueueAsync(messageFramesWriter, CancellationToken.None).Wait();
            messageQueue.SendFromQueueAsync(messageFramesWriter, CancellationToken.None).Wait();

            Assert.IsFalse(messageQueue.MessageCounterSignal.IsSet);
        }
        public async Task Deregister()
        {
            var deregisterMsg = new DeregisterMessage();
            deregisterMsg.challengeId = challengeId;
            deregisterMsg.deviceId = deviceId;
            var deregisterMessage = new MessageFrame("deregister", deregisterMsg);

            string message = JsonConvert.SerializeObject(deregisterMessage);

            await connection.SendAsync(message);

            Debug.WriteLine("sent deregister message");
        }
        public async Task Join()
        {
            var joinMsg = new JoinMessage();
            joinMsg.challengeId = challengeId;
            joinMsg.userName = userName;
            var joinMessage = new MessageFrame("join", joinMsg);

            string message = JsonConvert.SerializeObject(joinMessage);
            await connection.SendAsync(message);

            Debug.WriteLine("sent join message");
        }
        public void MessageQueue_AddRange_two_messages_SendMultipleFromQueue_writer_receives_both_messages()
        {
            var messageFramesWritten = new List<MessageFrame>();
            var messageFramesWriter = CreateMessagFrameWriter(messageFramesWritten);

            var testMessageFrame = new MessageFrame();

            var testMessageFrame1 = new MessageFrame();
            var testMessageFrame2 = new MessageFrame();

            var messageQueue = new MessageQueueBatch(4096);
            messageQueue.AddRange(new[] { testMessageFrame1, testMessageFrame2 });

            messageQueue.SendMultipleFromQueue(messageFramesWriter);

            Assert.AreSame(testMessageFrame1, messageFramesWritten.First());
            Assert.AreSame(testMessageFrame2, messageFramesWritten.Skip(1).Single());
        }
Example #56
0
 private async Task SendMessageFrameAsync(IMessageFrameWriter writer, MessageFrame messageFrame, CancellationToken cancellationToken)
 {
     try
     {
         await writer.WriteMessageFrameAsync(messageFrame, cancellationToken);
     }
     catch
     {
         if (_resentMessageFrames.TryAdd(messageFrame))
         {
             Interlocked.Increment(ref _resentMessageFramesCount);
         }
         throw;
     }
 }
Example #57
0
        public int Send(byte[] buffer, int offset, int data_length, BacnetAddress address, bool wait_for_transmission, int timeout)
        {
            if (m_TS == -1) throw new Exception("Source address must be set up before sending messages");

            //add to queue
            BacnetNpduControls function = NPDU.DecodeFunction(buffer, offset);
            BacnetMstpFrameTypes frame_type = (function & BacnetNpduControls.ExpectingReply) == BacnetNpduControls.ExpectingReply ? BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY : BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY;
            byte[] copy = new byte[data_length + MSTP.MSTP_HEADER_LENGTH + 2];
            Array.Copy(buffer, offset, copy, MSTP.MSTP_HEADER_LENGTH, data_length);
            MessageFrame f = new MessageFrame(frame_type, address.adr[0], copy, data_length);
            m_send_queue.AddLast(f);
            if (m_reply == null)
            {
                m_reply = f;
                m_reply_mutex.Set();
            }

            //wait for message to be sent
            if (wait_for_transmission)
                if (!f.send_mutex.WaitOne(timeout))
                    return -ETIMEDOUT;

            return data_length;
        }
Example #58
0
 public void Write(MessageFrame messageFrame)
 {
     _writeStream.Enqueue(messageFrame);
 }
Example #59
0
        private StateChanges Idle()
        {
            int no_token_timeout = T_NO_TOKEN + 10 * m_TS;
            BacnetMstpFrameTypes frame_type;
            byte destination_address;
            byte source_address;
            int msg_length;

            while (m_port != null)
            {
                //get message
                GetMessageStatus status = GetNextMessage(no_token_timeout, out frame_type, out destination_address, out source_address, out msg_length);

                if (status == GetMessageStatus.Good)
                {
                    try
                    {
                        if (destination_address == m_TS || destination_address == 0xFF)
                        {
                            switch (frame_type)
                            {
                                case BacnetMstpFrameTypes.FRAME_TYPE_POLL_FOR_MASTER:
                                    if (destination_address == 0xFF)
                                        QueueFrame(BacnetMstpFrameTypes.FRAME_TYPE_REPLY_TO_POLL_FOR_MASTER, source_address);
                                    else
                                    {
                                        //respond to PFM
                                        SendFrame(BacnetMstpFrameTypes.FRAME_TYPE_REPLY_TO_POLL_FOR_MASTER, source_address);
                                    }
                                    break;
                                case BacnetMstpFrameTypes.FRAME_TYPE_TOKEN:
                                    if (destination_address != 0xFF)
                                    {
                                        m_frame_count = 0;
                                        m_sole_master = false;
                                        return StateChanges.ReceivedToken;
                                    }
                                    break;
                                case BacnetMstpFrameTypes.FRAME_TYPE_TEST_REQUEST:
                                    if (destination_address == 0xFF)
                                        QueueFrame(BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE, source_address);
                                    else
                                    {
                                        //respond to test
                                        SendFrame(BacnetMstpFrameTypes.FRAME_TYPE_TEST_RESPONSE, source_address);
                                    }
                                    break;
                                case BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_NOT_EXPECTING_REPLY:
                                case BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY:
                                    //signal upper layer
                                    if (MessageRecieved != null)
                                    {
                                        BacnetAddress remote_address = new BacnetAddress(BacnetAddressTypes.MSTP, 0, new byte[] { source_address });
                                        try
                                        {
                                            MessageRecieved(this, m_local_buffer, MSTP.MSTP_HEADER_LENGTH, msg_length, remote_address);
                                        }
                                        catch (Exception ex)
                                        {
                                            Trace.TraceError("Exception in MessageRecieved event: " + ex.Message);
                                        }
                                    }
                                    if (frame_type == BacnetMstpFrameTypes.FRAME_TYPE_BACNET_DATA_EXPECTING_REPLY)
                                    {
                                        m_reply_source = source_address;
                                        m_reply = null;
                                        m_reply_mutex.Reset();
                                        return StateChanges.ReceivedDataNeedingReply;
                                    }
                                    break;
                            }
                        }
                    }
                    finally
                    {
                        RemoveCurrentMessage(msg_length);
                    }
                }
                else if (status == GetMessageStatus.Timeout)
                {
                    /* GenerateToken */
                    m_PS = (byte)((m_TS + 1) % (m_max_master + 1));
                    m_NS = (byte)m_TS;
                    m_token_count = 0;
                    return StateChanges.GenerateToken;
                }
                else if (status == GetMessageStatus.ConnectionClose)
                {
                    Trace.WriteLine("No connection", null);
                }
                else if (status == GetMessageStatus.ConnectionError)
                {
                    Trace.WriteLine("Connection Error", null);
                }
                else
                {
                    Trace.WriteLine("Garbage", null);
                }
            }

            return StateChanges.Reset;
        }
        public void MessageQueue_Add_single_message_after_SendMultipleFromQueue_MessageCounterSignal_IsSet_false()
        {
            var messageFramesWritten = new List<MessageFrame>();
            var messageFramesWriter = CreateMessagFrameWriter(messageFramesWritten);

            var testMessageFrame = new MessageFrame();

            var messageQueue = new MessageQueueBatch(4096);
            messageQueue.Add(testMessageFrame);

            messageQueue.SendMultipleFromQueue(messageFramesWriter);

            Assert.IsFalse(messageQueue.MessageCounterSignal.IsSet);
        }