Example #1
0
 /// <summary>
 /// Creates a new ScsClient object.
 /// 
 /// </summary>
 /// <param name="communicationChannel">The communication channel that is used by client to send and receive messages</param>
 public ScsServerClient(ICommunicationChannel communicationChannel)
 {
     this._communicationChannel = communicationChannel;
     this._communicationChannel.MessageReceived += new EventHandler<MessageEventArgs>(this.CommunicationChannel_MessageReceived);
     this._communicationChannel.MessageSent += new EventHandler<MessageEventArgs>(this.CommunicationChannel_MessageSent);
     this._communicationChannel.Disconnected += new EventHandler(this.CommunicationChannel_Disconnected);
 }
Example #2
0
 public ServerClient(ICommunicationChannel communicationChannel)
 {
     _communicationChannel = communicationChannel;
     _communicationChannel.MessageReceived += CommunicationChannel_MessageReceived;
     _communicationChannel.MessageSent += CommunicationChannel_MessageSent;
     _communicationChannel.Disconnected += CommunicationChannel_Disconnected;
 }
 /// <summary>
 ///     Raises CommunicationChannelConnected event.
 /// </summary>
 /// <param name="client"></param>
 protected virtual void OnCommunicationChannelConnected(ICommunicationChannel client)
 {
     var handler = CommunicationChannelConnected;
     if (handler != null) {
         handler(this, new CommunicationChannelEventArgs(client));
     }
 }
Example #4
0
 /// <summary>
 /// Raises CommunicationChannelConnected event.
 /// 
 /// </summary>
 /// <param name="client"/>
 protected virtual void OnCommunicationChannelConnected(ICommunicationChannel client)
 {
     EventHandler<CommunicationChannelEventArgs> eventHandler = this.CommunicationChannelConnected;
     if (eventHandler == null)
         return;
     eventHandler((object)this, new CommunicationChannelEventArgs(client));
 }
        public async Task Start(string portName, int baudRate, CancellationTokenSource cts)
        {
            Debug.WriteLine("Element:CommunicationTask: Start:   port: {0}  baudRate: {1}", portName, baudRate);

            //serialPort = new CommunicationChannelBT();

            serialChannel = new CommunicationChannelSerial(cts)
            {
                Name = portName,
                BaudRate = (uint)baudRate
            };

            try
            {
                Debug.WriteLine("IP: Element:CommunicationTask: serialPort " + portName + " opening...");
                await serialChannel.Open();
                Debug.WriteLine("OK: Element:CommunicationTask: serialPort " + portName + " opened");

                //await Task.Delay(2000);

                // Notify users to initialize any devices
                // they have before we start processing commands:
                element.StartingCommunication(serialChannel);

                running = true;
                ClearJobQueues();

                Task workerTask = new Task(() => ThreadProc(cts.Token), cts.Token);
                workerTask.Start();

                Debug.WriteLine("IP: Element:CommunicationTask: trying to synch up with the board - resetting...");

                // try to synch up with the board
                string resp = EnqueueCommJobAndWait(Priority.High, "reset");

                //await Task.Delay(3000); // let other processes continue

                // This HAS TO BE HERE...Since it takes the Element about a second to boot up
                // using the new Tiny Bootloader...
                //Thread.Sleep(1000);
                await Task.Delay(2000);

                // Clear receive buffer out, since the bootloader can send
                // some junk characters, which might hose subsequent command responses:
                serialChannel.DiscardInBuffer();
                stopWatch.Start();
            }
            catch (AggregateException aexc)
            {
                throw new CommunicationException("CommunicationTask: Could not start communication");
            }
            catch (Exception exc)
            {
                Debug.WriteLine("Error: Element:CommunicationTask: exception while opening serial port " + portName + " : " + exc);
                //await Stop();
                //throw new CommunicationException("CommunicationTask: Could not start communication");
                throw;
            }
        }
 protected virtual void SendConnectedEvent(ICommunicationChannel communicationChannel)
 {
     EventHandler<CommunicationChannelEventArg> handler = CommunicationChannelConnected;
     if (handler != null)
     {
         handler(this, new CommunicationChannelEventArg(communicationChannel));
     }
 }
Example #7
0
 public override void Connect(IPAddress ip, int port, String username)
 {
     IP = ip;
     Port = port;
     Username = username;
     Client = new TcpClient();
     CommunicationChannel = new TcpCommunicationChannel(Client, ip, port);
     Client.BeginConnect(ip, port, ConnectCallBack, null);
 }
Example #8
0
 public WCServerClient(ICommunicationChannel comChannel, String username)
     : base()
 {
     CommunicationChannel = comChannel;
     Username = username;
     CommunicationChannel.MessageRecieved += new EventHandler<WCMessageEventArg>(ComChannel_OnMessageReceivedEvent);
     CommunicationChannel.Disconnected += new EventHandler(ComChannel_OnDisconnectEvent);
     pendingAuth = true;
 }
Example #9
0
        public WebSocketContext(ICommunicationChannel channel, IBufferManager bufferManager)
        {
            BufferManager = bufferManager;
            Channel = channel;

            var session = channel as IAppSession;

            if (session != null)
                session.Items.Add(c_WebSocketContextKey, this);
        }
Example #10
0
 /// <summary>
 /// Closes the channel.
 /// </summary>
 /// <param name="channel">The channel.</param>
 public virtual void closeChannel(ICommunicationChannel channel)
 {
     if (channel is StreamChannelImpl)
     {
         ((StreamChannelImpl) channel).close();
     }
     if (channel is IDisposable)
     {
         ((IDisposable)channel).Dispose();
     }
     channel.Command -= OnCommand;
     channel.Message -= OnChannelMessage;
 }
 /// <summary>
 /// Creates a new CommunicationChannelEventArgs object.
 /// 
 /// </summary>
 /// <param name="channel">Communication channel that is associated with this event</param>
 public CommunicationChannelEventArgs(ICommunicationChannel channel)
 {
     this.Channel = channel;
 }
 private void bridge_CommunicationsStopping(ICommunicationChannel serialDevice)
 {
     Debug.WriteLine("RobotPluckyHardwareBridge: bridge_CommunicationsStopping: Clean up your serial device here");
 }
Example #13
0
 private void SignalCommunicationsStopping(ICommunicationChannel sp)
 {
     CommunicationsStopping?.Invoke(sp);
 }
Example #14
0
        private void CommunicationChannel_StateChanged(ICommunicationChannel sender, CommunicationStateChangedEventArgs e)
        {
            //Process only Closed event
            if (sender.State != CommunicationStates.Closed)
            {
                return;
            }

            //Pulse waiting threads for incoming messages, because disconnected to the server, and can not receive message anymore.
            lock (_waitingMessages)
            {
                foreach (var waitingMessage in _waitingMessages.Values)
                {
                    waitingMessage.WaitEvent.Set();
                }

                _waitingMessages.Clear();
            }
        }
Example #15
0
        /// <summary>
        /// This event handles incoming messages from communication channel.
        /// </summary>
        /// <param name="sender">Communication channel that received message</param>
        /// <param name="e">Event arguments</param>
        private void CommunicationChannel_MessageReceived(ICommunicationChannel sender, MessageReceivedEventArgs e)
        {
            LastIncomingMessageTime = DateTime.Now;

            if ((e.Message.MessageTypeId == MDSMessageFactory.MessageTypeIdMDSControllerMessage) && (!string.IsNullOrEmpty(e.Message.RepliedMessageId)))
            {
                //Find and send signal/pulse to waiting thread for this message
                WaitingMessage waitingMessage = null;
                lock (_waitingMessages)
                {
                    if (_waitingMessages.ContainsKey(e.Message.RepliedMessageId))
                    {
                        waitingMessage = _waitingMessages[e.Message.RepliedMessageId];
                    }
                }

                if (waitingMessage != null)
                {
                    waitingMessage.ResponseMessage = e.Message as MDSControllerMessage;
                    waitingMessage.WaitEvent.Set();
                    return;
                }
            }
            
            //Add message to queue to process in a seperated thread
            _incomingMessageQueue.Add(e.Message);
        }
Example #16
0
        public async Task Stop()
		{
			running = false;
            stopWatch.Stop();

            sem.Up();

            await Task.Delay(100);

            // Notify users to clean up any devices
            // connected to the serial port if need be, before closing it.
            element.StoppingCommunication(serialChannel);

			if (serialChannel != null)
			{
                // Clear receive buffer out, since the bootloader can send
                // some just characters, which might hose subsequent command responses:
                //serialPort.DiscardInBuffer();

				serialChannel.Close();
				serialChannel = null;
			}
		}
 /// <summary>
 /// Closes the specified channel.
 /// </summary>
 /// <param name="channel">The channel.</param>
 /// <param name="reason">The reason.</param>
 public override void Close(ICommunicationChannel channel, CloseReason reason)
 {
     channel.Close(reason);
 }
Example #18
0
 private void registerChannel(ICommunicationChannel channel)
 {
     channel.Command += OnCommand;
     channel.Message += OnChannelMessage;
 }
Example #19
0
 /// <summary>
 /// Connects to server.
 /// 
 /// </summary>
 public void Connect()
 {
     this.WireProtocol.Reset();
     this._communicationChannel = this.CreateCommunicationChannel();
     this._communicationChannel.WireProtocol = this.WireProtocol;
     this._communicationChannel.Disconnected += new EventHandler(this.CommunicationChannel_Disconnected);
     this._communicationChannel.MessageReceived += new EventHandler<MessageEventArgs>(this.CommunicationChannel_MessageReceived);
     this._communicationChannel.MessageSent += new EventHandler<MessageEventArgs>(this.CommunicationChannel_MessageSent);
     this._communicationChannel.Start();
     this._pingTimer.Start();
     this.OnConnected();
 }
Example #20
0
        /// <summary>
        /// This event handles incoming messages from communication channel.
        /// </summary>
        /// <param name="sender">Communication channel that received message</param>
        /// <param name="e">Event arguments</param>
        private void CommunicationChannel_MessageReceived(ICommunicationChannel sender, Communication.Channels.MessageReceivedEventArgs e)
        {
            //Update last incoming message time
            LastIncomingMessageTime = DateTime.Now;

            //Check for duplicate messages.
            if (e.Message.MessageTypeId == NGRIDMessageFactory.MessageTypeIdNGRIDDataTransferMessage)
            {
                var dataMessage = e.Message as NGRIDDataTransferMessage;
                if (dataMessage != null)
                {
                    if (dataMessage.MessageId == LastAcknowledgedMessageId)
                    {
                        try
                        {
                            SendMessageInternal(new NGRIDOperationResultMessage
                            {
                                RepliedMessageId = dataMessage.MessageId,
                                Success = true,
                                ResultText = "Duplicate message."
                            });
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn(ex.Message, ex);
                        }

                        return;
                    }
                }
            }

            //Check if there is a waiting thread for this message (in SendAndWaitForReply method)
            if (!string.IsNullOrEmpty(e.Message.RepliedMessageId))
            {
                WaitingMessage waitingMessage = null;
                lock (_waitingMessages)
                {
                    if (_waitingMessages.ContainsKey(e.Message.RepliedMessageId))
                    {
                        waitingMessage = _waitingMessages[e.Message.RepliedMessageId];
                    }
                }

                if (waitingMessage != null)
                {
                    if (waitingMessage.WaitingResponseType == e.Message.MessageTypeId)
                    {
                        waitingMessage.ResponseMessage = e.Message;
                        waitingMessage.State = WaitingMessageStates.ResponseReceived;
                        waitingMessage.WaitEvent.Set();
                        return;
                    }
                    
                    if(e.Message.MessageTypeId == NGRIDMessageFactory.MessageTypeIdNGRIDOperationResultMessage)
                    {
                        var resultMessage = e.Message as NGRIDOperationResultMessage;
                        if ((resultMessage != null) && (!resultMessage.Success))
                        {
                            waitingMessage.State = WaitingMessageStates.MessageRejected;
                            waitingMessage.WaitEvent.Set();
                            return;
                        }
                    }
                }
            }

            //If this message is not a response, then add it to message process queue
            _incomingMessageQueue.Add(e.Message);
        }
Example #21
0
        public async Task Stop()
        {
            running = false;
            stopWatch.Stop();
            //commandsBufferBlock.Complete();
            actionBlock.Complete();

            Flush();

            await Task.Delay(100);

            // Notify users to clean up any devices
            // connected to the serial port if need be, before closing it.
            arduinoBrick.StoppingCommunication(serialChannel);

            if (serialChannel != null)
            {
                serialChannel.DiscardInBuffer();
                serialChannel.Close();
                serialChannel = null;
            }
        }
Example #22
0
 internal void StoppingCommunication(ICommunicationChannel sp)
 {
     if (communicating)
     {
         SignalCommunicationsStopping(sp);
     }
 }
        public ClientCommunicator()
        {
            this._participant = new UdpParticipant();
            this._participant.ManagerFound += ((sender, e) =>
            {
                // Found a game host.
                this._managerCommunicationChannel = _participant.CreateCommunicationChannel(e.Id);
                this._managerGuid = e.Id;
                this.GameAvailable(this, EventArgs.Empty);

            });


            this._participantCommunicationChannel = new TcpCommunicationChannel();
            this._participantCommunicationChannel.MessageReceived += ((sender, e) =>
            {
                // Decode the message that the game host sent to us.
                string[] message = e.Message.ToString().Split('-');
                switch (message[0])
                {
                    case QUESTION_COMMAND: // The game host sent a question to us.
                        NewQuestionAvailable(this,
                            new QuestionEventArgs { Question = ParseQuestion(e.Message.ToString()) });
                        break;
                    case JOIN_COMMAND: // The game host sent a confirmation that we are connected.
                        this.HostJoinStatusMessageReceived(this,
                            new HostJoinStatusMessageReceivedArgs { IsJoined = Boolean.Parse(message[1]) });
                        break;
                }
            });
        }
Example #24
0
        /// <summary>
        /// Creates a new MDSClient object.
        /// </summary>
        /// <param name="ipAddress">Ip address of the MDS server</param>
        /// <param name="port">Listening TCP Port of MDS server</param>
        public MDSController(string ipAddress, int port)
        {
            ReConnectServerOnError = true;

            _reconnectTimer = new Timer(ReconnectTimer_Tick, null, Timeout.Infinite, Timeout.Infinite);
            _waitingMessages = new SortedList<string, WaitingMessage>();

            _incomingMessageQueue = new QueueProcessorThread<MDSMessage>();
            _incomingMessageQueue.ProcessItem += IncomingMessageQueue_ProcessItem;

            _communicationChannel = new TCPChannel(ipAddress, port);
            _communicationChannel.MessageReceived += CommunicationChannel_MessageReceived;
            _communicationChannel.StateChanged += CommunicationChannel_StateChanged;

            LastIncomingMessageTime = DateTime.MinValue;
            LastOutgoingMessageTime = DateTime.MinValue;
        }
 private void HandleConnection(ICommunicationChannel ch)
 {
     _connectedClients.Add(ch);
     ch.MessageReceived += HandleMessageReceived;
 }
Example #26
0
        public async Task Start(string portName, int baudRate, CancellationTokenSource cts)
        {
            Debug.WriteLine("ArduinoBrick:CommunicationTask: Start:   port: {0}  baudRate: {1}", portName, baudRate);

            cancellationTokenSource = cts;

            //serialPort = new CommunicationChannelBT();

            serialChannel = new CommunicationChannelSerial(cts)
            {
                Name = portName,
                BaudRate = (uint)baudRate,
                NewLineIn = "\r\n>",
                NewLineOut = "\r"
            };

            try
            {
                Debug.WriteLine("IP: ArduinoBrick:CommunicationTask: serialPort " + portName + " opening...");
                await serialChannel.Open();
                Debug.WriteLine("OK: ArduinoBrick:CommunicationTask: serialPort " + portName + " opened");

                //await Task.Delay(2000);

                // Notify users to initialize any devices
                // they have before we start processing commands:
                arduinoBrick.StartingCommunication(serialChannel);

                //commandsBufferBlock = new BufferBlock<CommandAndResponse>(
                //                        new DataflowBlockOptions() { CancellationToken = cts.Token });

                actionBlock = new ActionBlock<CommandAndResponse>(
                                        async prompt =>
                                        {
                                            await serialChannel.WriteLine(prompt.command);
                                            string response = await serialChannel.ReadLine();
                                            prompt.completionSource.SetResult(response);
                                        },
                                        new ExecutionDataflowBlockOptions() { CancellationToken = cts.Token, BoundedCapacity = 10 });

                //commandsBufferBlock.LinkTo(actionBlock, new DataflowLinkOptions { PropagateCompletion = true });

                Debug.WriteLine("IP: ArduinoBrick:CommunicationTask: trying to synch up with the board - resetting...");

                string resp = null;
                int count = 10;
                bool boardFound = false;

                while (count-- > 0)
                {
                    // try to sync up with the board
                    resp = await SendAndReceive("reset");

                    Debug.WriteLine("OK: ArduinoBrick:CommunicationTask: 'reset' -> '" + resp + "'");

                    if (string.Equals(resp, "Arduino firmware Plucky Wheels"))
                    {
                        boardFound = true;
                        break;
                    }
                }

                if (boardFound)
                {
                    Debug.WriteLine("OK: ArduinoBrick:CommunicationTask: found Plucky Wheels Arduino brick");
                }
                else
                {
                    throw new CommunicationException("CommunicationTask: Could not find Plucky Wheels Arduino brick, invalid response to 'reset' at serial port " + portName);
                }

                stopWatch.Start();
                running = true;
            }
            catch (AggregateException aexc)
            {
                throw new CommunicationException("CommunicationTask: Could not start communication");
            }
            catch (Exception exc)
            {
                Debug.WriteLine("Error: ArduinoBrick:CommunicationTask: exception while opening serial port " + portName + " : " + exc);
                //await Stop();
                //throw new CommunicationException("CommunicationTask: Could not start communication");
                throw;
            }
        }
Example #27
0
 /// <summary>
 ///     Connects to server.
 /// </summary>
 public void Connect()
 {
     WireProtocol.Reset();
     _communicationChannel = CreateCommunicationChannel();
     _communicationChannel.WireProtocol = WireProtocol;
     _communicationChannel.Disconnected += CommunicationChannel_Disconnected;
     _communicationChannel.MessageReceived += CommunicationChannel_MessageReceived;
     _communicationChannel.MessageSent += CommunicationChannel_MessageSent;
     _communicationChannel.Start();
     _pingTimer.Start();
     OnConnected();
 }
 private void HandleDisconnection(ICommunicationChannel disconnectingChannel)
 {
     _connectedClients.Remove(disconnectingChannel);
     disconnectingChannel.MessageReceived -= HandleMessageReceived;
 }
 private void bridge_CommunicationsStarting(ICommunicationChannel serialDevice)
 {
     Debug.WriteLine("RobotShortyHardwareBridge: bridge_CommunicationsStarting: Init your serial device here");
 }
Example #30
0
 public NetworkClient(ICommunicationChannel communicationChannel)
     : base(communicationChannel)
 {
 }