Пример #1
0
 public ServerClient(ICommunicationChannel communicationChannel)
 {
     _communicationChannel = communicationChannel;
     _communicationChannel.MessageReceived += CommunicationChannel_MessageReceived;
     _communicationChannel.MessageSent += CommunicationChannel_MessageSent;
     _communicationChannel.Disconnected += CommunicationChannel_Disconnected;
 }
Пример #2
0
 /// <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));
     }
 }
Пример #3
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);
 }
Пример #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));
 }
Пример #5
0
        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;
            }
        }
Пример #6
0
 protected virtual void SendConnectedEvent(ICommunicationChannel communicationChannel)
 {
     EventHandler<CommunicationChannelEventArg> handler = CommunicationChannelConnected;
     if (handler != null)
     {
         handler(this, new CommunicationChannelEventArg(communicationChannel));
     }
 }
Пример #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);
 }
Пример #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;
 }
Пример #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);
        }
Пример #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;
 }
 private void bridge_CommunicationsStopping(ICommunicationChannel serialDevice)
 {
     Debug.WriteLine("RobotPluckyHardwareBridge: bridge_CommunicationsStopping: Clean up your serial device here");
 }
Пример #12
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();
            }
        }
Пример #13
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;
        }
Пример #14
0
 private void HandleDisconnection(ICommunicationChannel disconnectingChannel)
 {
     _connectedClients.Remove(disconnectingChannel);
     disconnectingChannel.MessageReceived -= HandleMessageReceived;
 }
Пример #15
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();
 }
Пример #16
0
        private static BuildToolsServer StartBuildServer(Mock <IProject> projectMock, ICommunicationChannel channel, IFileSynchronizationManager deployManager = null, IBuildErrorProcessor errorProcessor = null)
        {
            deployManager  = deployManager ?? new Mock <IFileSynchronizationManager>().Object;
            errorProcessor = errorProcessor ?? new Mock <IBuildErrorProcessor>().Object;

            var output = new Mock <IOutputWindowManager>();

            output.Setup((w) => w.GetExecutionResultPane()).Returns(new Mock <IOutputWindowWriter>().Object);

            var server = new BuildToolsServer(projectMock.Object, channel, output.Object, errorProcessor, deployManager, null);

            projectMock.Raise((p) => p.Loaded += null, projectMock.Object.Options); // starts the server
            return(server);
        }
Пример #17
0
 private void registerChannel(ICommunicationChannel channel)
 {
     channel.Command += OnCommand;
     channel.Message += OnChannelMessage;
 }
 public static TransactionObserver BuildTransactionObserver(ICommunicationChannel channel)
 {
     return(new TransactionObserver(channel));
 }
Пример #19
0
        /// <summary>
        /// Encodes a given vector
        /// </summary>
        /// <param name="vector">A vector to encode</param>
        /// <param name="encoder">Encoder to encode vector with</param>
        /// <returns>Resulting text</returns>
        public static async Task <StringResultWithErrorPositions> EncodeAndSendVector(string vector, IEncoder encoder, ICommunicationChannel channel)
        {
            var bits = vectorConverter.ToBitStream(vector);

            var encodedBits = await Task.FromResult(encoder.Encode(bits));

            var bitsAfterTransmission = await Task.FromResult(channel.Transmit(encodedBits));

            var errors = encodedBits.DifferenceWithPositions(bitsAfterTransmission);

            var encodedVector = vectorConverter.FromBitStream(encodedBits);

            return(new StringResultWithErrorPositions
            {
                ErrorPositions = errors,
                Errors = errors.Count,
                Result = encodedVector
            });
        }
Пример #20
0
            public override void Run()
            {
                while (true)
                {
                    if (Enclosing_Instance.commandQueue.Count == 0)
                    {
                        try
                        {
                            Thread.Sleep(new TimeSpan(10000 * 10));
                        }
                        catch (ThreadInterruptedException e)
                        {
                            // TODO Auto-generated catch block
                            //SupportClass.WriteStackTrace(e, Console.Error);
                        }
                        catch (Exception e)
                        {
                            //SupportClass.WriteStackTrace(e, Console.Error);
                            return;
                        }
                    }
                    else
                    {
                        CommandObject schabau = (CommandObject)Enclosing_Instance.commandQueue[0];
                        Enclosing_Instance.commandQueue.RemoveAt(0);
                        if (schabau != null)
                        {
                            Enclosing_Instance.currentChannelId = schabau.channelId;
                            try
                            {
                                Enclosing_Instance.messageQueue.Add(new MessageEvent(MessageEvent.COMMAND, schabau.command, Enclosing_Instance.currentChannelId));
                                IReturnVector result = Enclosing_Instance.interpreter.executeCommand(schabau.command);
                                Enclosing_Instance.messageQueue.Add(new MessageEvent(MessageEvent.RESULT, result, Enclosing_Instance.currentChannelId));
                            }
                            catch (Exception e)
                            {
                                Enclosing_Instance.postMessageEvent(new MessageEvent(MessageEvent.ERROR, e, Enclosing_Instance.currentChannelId));
                            }
                            finally
                            {
                                Enclosing_Instance.currentChannelId = null;
                            }
                        }
                    }

                    MessageEvent[] evts        = (MessageEvent[])Enclosing_Instance.messageQueue.ToArray(typeof(MessageEvent));
                    ArrayList      allMessages = new ArrayList(evts);

                    Enclosing_Instance.messageQueue.Clear();
                    for (int i = 0; i < allMessages.Count; ++i)
                    {
                        MessageEvent event_Renamed = (MessageEvent)allMessages[i];
                        lock (Enclosing_Instance.idToChannel)
                        {
                            IEnumerator ch = Enclosing_Instance.idToChannel.Values.GetEnumerator();
                            while (ch.MoveNext())
                            {
                                ICommunicationChannel channel = (ICommunicationChannel)ch.Current;
                                if (InterestType.ALL == channel.Interest || (InterestType.MINE == channel.Interest) && channel.ChannelId.Equals(event_Renamed.ChannelId))
                                {
                                    IList messageList = (IList)Enclosing_Instance.idToMessages.Get(channel.ChannelId);
                                    if (messageList != null)
                                    {
                                        messageList.Add(event_Renamed);
                                    }
                                }
                            }
                        }
                    }
                }
            }
Пример #21
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);
        }
Пример #22
0
 public RxControllerActions(ICommunicationChannel channel, ITransactionProcessor processor)
 {
     this.channel   = channel;
     this.processor = processor;
 }
Пример #23
0
 public override void Close(ICommunicationChannel channel, CloseReason reason)
 {
     channel.Close(reason);
 }
Пример #24
0
 public NetworkClient(ICommunicationChannel communicationChannel) : base(communicationChannel)
 {
 }
Пример #25
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);
        }
 /// <summary>
 /// Creates a new CommunicationChannelEventArgs object.
 /// </summary>
 /// <param name="channel">Communication channel that is associated with this event</param>
 public CommunicationChannelEventArgs(ICommunicationChannel channel) => Channel = channel;
Пример #27
0
 private void registerChannel(ICommunicationChannel channel)
 {
     channel.Command += OnCommand;
     channel.Message += OnChannelMessage;
 }
Пример #28
0
 private void SignalCommunicationsStopping(ICommunicationChannel sp)
 {
     CommunicationsStopping?.Invoke(sp);
 }
Пример #29
0
 private void HandleConnection(ICommunicationChannel ch)
 {
     _connectedClients.Add(ch);
     ch.MessageReceived += HandleMessageReceived;
 }
Пример #30
0
 internal void StoppingCommunication(ICommunicationChannel sp)
 {
     if (communicating)
     {
         SignalCommunicationsStopping(sp);
     }
 }
Пример #31
0
 public NetworkClient(ICommunicationChannel communicationChannel)
     : base(communicationChannel)
 {
 }
Пример #32
0
 private void SignalCommunicationsStopping(ICommunicationChannel sp)
 {
     CommunicationsStopping?.Invoke(sp);
 }
Пример #33
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);
        }
Пример #34
0
        internal static Task MessageLoopAsync(
            this TcpClient client,
            ICommunicationChannel channel,
            Action <Exception> errorHandler,
            CancellationToken cancellationToken)
        {
            Exception error = null;

            var remoteEndPoint = string.Empty;
            var localEndPoint  = string.Empty;

            try
            {
                remoteEndPoint = client.Client.RemoteEndPoint?.ToString();
                localEndPoint  = client.Client.LocalEndPoint?.ToString();
            }
            catch (SocketException socketException)
            {
                EqtTrace.Error(
                    "TcpClientExtensions.MessageLoopAsync: Failed to access the endpoint due to socket error: {0}",
                    socketException);
            }

            // Set read timeout to avoid blocking receive raw message
            while (channel != null && !cancellationToken.IsCancellationRequested)
            {
                EqtTrace.Verbose("TcpClientExtensions.MessageLoopAsync: Polling on remoteEndPoint: {0} localEndPoint: {1}", remoteEndPoint, localEndPoint);

                try
                {
                    if (client.Client.Poll(STREAMREADTIMEOUT, SelectMode.SelectRead))
                    {
                        EqtTrace.Verbose("TcpClientExtensions.MessageLoopAsync: NotifyDataAvailable remoteEndPoint: {0} localEndPoint: {1}", remoteEndPoint, localEndPoint);
                        channel.NotifyDataAvailable();
                    }
                }
                catch (IOException ioException)
                {
                    var socketException = ioException.InnerException as SocketException;
                    if (socketException != null &&
                        socketException.SocketErrorCode == SocketError.TimedOut)
                    {
                        EqtTrace.Info(
                            "Socket: Message loop: failed to receive message due to read timeout {0}, remoteEndPoint: {1} localEndPoint: {2}",
                            ioException,
                            remoteEndPoint,
                            localEndPoint);
                    }
                    else
                    {
                        EqtTrace.Error(
                            "Socket: Message loop: failed to receive message due to socket error {0}, remoteEndPoint: {1} localEndPoint: {2}",
                            ioException,
                            remoteEndPoint,
                            localEndPoint);
                        error = ioException;
                        break;
                    }
                }
                catch (Exception exception)
                {
                    EqtTrace.Error(
                        "Socket: Message loop: failed to receive message {0}, remoteEndPoint: {1} localEndPoint: {2}",
                        exception,
                        remoteEndPoint,
                        localEndPoint);
                    error = exception;
                    break;
                }
            }

            // Try clean up and raise client disconnected events
            errorHandler(error);

            EqtTrace.Verbose("TcpClientExtensions.MessageLoopAsync: exiting MessageLoopAsync remoteEndPoint: {0} localEndPoint: {1}", remoteEndPoint, localEndPoint);

            return(Task.FromResult(0));
        }
 /// <summary>
 ///     Raises CommunicationChannelConnected event.
 /// </summary>
 /// <param name="client"></param>
 protected virtual void OnCommunicationChannelConnected(ICommunicationChannel client) => CommunicationChannelConnected?.Invoke(this, new CommunicationChannelEventArgs(client));
 /// <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);
 }
 /// <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;
 }
Пример #38
0
 // Token: 0x06000761 RID: 1889
 public abstract void Close(ICommunicationChannel channel, CloseReason reason);
        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;
                }
            });
        }
Пример #40
0
 public Publisher([Dependency(ChannelNames.Server)] ICommunicationChannel publishChannel)
 {
     _publishChannel = publishChannel;
 }
Пример #41
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;
            }
        }
Пример #42
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;
            }
        }
Пример #43
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();
 }
Пример #44
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;
			}
		}
 private void bridge_CommunicationsStarting(ICommunicationChannel serialDevice)
 {
     Debug.WriteLine("RobotShortyHardwareBridge: bridge_CommunicationsStarting: Init your serial device here");
 }
Пример #46
0
 /// <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;
 }