private void OnSocketMessageAvailable(ProsthesisMessage message, TCP.ConnectionState state)
        {
            //Only one message allowed in at a time
            lock (this)
            {
                ProsthesisStateBase newState = mCurrentState;
                //Capture handshakes and send appropriate events
                if (message is ProsthesisHandshakeRequest)
                {
                    ProsthesisHandshakeRequest hsReq = message as ProsthesisHandshakeRequest;
                    if (hsReq.VersionId == ProsthesisCore.ProsthesisConstants.OSVersion)
                    {
                        newState = mCurrentState.OnClientAuthorization(state, true);
                        mAuthorizedConnection = state;
                    }
                    else
                    {
                        newState = mCurrentState.OnClientAuthorization(state, false);
                    }
                }
                else if (state == mAuthorizedConnection)
                {
                    //Capture commands and send appropriate events
                    if (message is ProsthesisCommand)
                    {
                        ProsthesisCommand command = message as ProsthesisCommand;
                        mLogger.LogMessage(Logger.LoggerChannels.Events, string.Format("Received command {0} from {1}", command.Command, state.RemoteEndPoint));


                        ProsthesisCommandAck ack = new ProsthesisCommandAck();
                        ack.Command   = command.Command;
                        ack.Timestamp = System.DateTime.Now.Ticks;
                        ProsthesisDataPacket pack = ProsthesisDataPacket.BoxMessage <ProsthesisCommandAck>(ack);

                        state._conn.Send(pack.Bytes, pack.Bytes.Length, System.Net.Sockets.SocketFlags.None);

                        if (command.Command == ProsthesisConstants.ProsthesisCommand.EmergencyStop)
                        {
                            Terminate(string.Format("Emergency stop from {0}", state.RemoteEndPoint));
                        }
                        else
                        {
                            newState = mCurrentState.OnProsthesisCommand(command.Command, state);
                        }
                    }
                    else
                    {
                        newState = mCurrentState.OnSocketMessage(message, state);
                    }
                }
                else
                {
                    state._server.DropConnection(state);
                }

                ChangeState(newState);
            }
        }
 public static ProsthesisMessage UnboxMessage(ProsthesisDataPacket packet)
 {
     try
     {
         System.IO.MemoryStream memStream = new System.IO.MemoryStream(packet.Data);
         memStream.Position = 0;
         ProsthesisMessage mess = ProtoBuf.Serializer.DeserializeWithLengthPrefix <ProsthesisMessage>(memStream, PrefixStyle.Fixed32);
         return(mess);
     }
     catch
     {
         return(null);
     }
 }
Exemple #3
0
        public override void OnReceiveData(ConnectionState state)
        {
            byte[] buffer = new byte[1024];
            while (state.AvailableData > 0)
            {
                int readCount = state.Read(buffer, 0, (int)(mReceiveBuffer.Capacity - mReceiveBuffer.Position));
                if (readCount > 0)
                {
                    //Drop connection if we are missing a packet parser
                    if (!mParsers.ContainsKey(state))
                    {
                        mLogger.LogMessage(Logger.LoggerChannels.Network, string.Format("Dropped connection to {0} because its parser was missing.", GetIPFor(state.RemoteEndPoint)));
                        state._server.DropConnection(state);
                        return;
                    }

                    ProsthesisPacketParser parser = mParsers[state];
                    parser.AddData(buffer, readCount);
                    try
                    {
                        while (parser.MoveNext())
                        {
                            ProsthesisMessage msg = parser.Current;
                            if (MessageAvailable != null)
                            {
                                MessageAvailable(msg, state);
                            }
                        }
                    }
                    catch (Exception e)
                    {
                        mLogger.LogMessage(Logger.LoggerChannels.Faults, string.Format("Caught protobuf exception {0} receiving data from {1}. Closing connection", e, GetIPFor(state.RemoteEndPoint)));
                        state._server.DropConnection(state);
                    }
                }
                else
                {
                    //If read fails then close connection
                    mLogger.LogMessage(Logger.LoggerChannels.Network, string.Format("Read failed from {0}. Dropping connection", GetIPFor(state.RemoteEndPoint)));
                    state._server.DropConnection(state);
                }
            }
        }
Exemple #4
0
        static void Main(string[] args)
        {
            string timestamp         = System.DateTime.Now.ToString("dd MMM yyyy HH-mm-ss");
            string fileName          = string.Format("ClientTest-{0}.txt", timestamp);
            string telemetryFileName = string.Format("ClientTest-Telemetry-{0}.txt", timestamp);

            mLogger = new Logger(fileName, true);
            //No no telemetry in main output
            mLogger.DeactivateChannels(Logger.LoggerChannels.Telemetry);

            //Start telemetry logging
            mTelemetryLogger         = new Logger(telemetryFileName, false);
            mTelemReceiver           = new ProsthesisClient.ProsthesisTelemetryReceiver(mTelemetryLogger);
            mTelemReceiver.Received += OnTelemetryReceive;

            mClient = new ProsthesisSocketClient(OnDataPacketReceive, "127.0.0.1", ProsthesisCore.ProsthesisConstants.ConnectionPort, mLogger);
            mClient.ConnectFinished  += new Action <ProsthesisSocketClient, bool>(OnConnectFinished);
            mClient.ConnectionClosed += new Action <ProsthesisSocketClient>(OnConnectionClosed);

            mTelemReceiver.Start();

            //Safely shut down app
            AppDomain.CurrentDomain.ProcessExit += delegate(object sender, EventArgs e)
            {
                try
                {
                    if (mClient != null && mClient.Connected)
                    {
                        mClient.Shutdown();
                    }
                }
                catch (Exception ex)
                {
                    mLogger.LogMessage(Logger.LoggerChannels.Faults, string.Format("Exception shutting down socket client: {0}", ex));
                }

                if (mTelemReceiver != null)
                {
                    mTelemReceiver.Stop();
                }

                mTelemetryLogger.ShutDown();
                mLogger.ShutDown();
            };

            try
            {
                mClient.StartConnect();
            }
            catch (SocketException ex)
            {
                mLogger.LogMessage(Logger.LoggerChannels.Faults, string.Format("Couldn't connect. Reason: {0}", ex));
            }
            finally
            {
                mLogger.LogMessage("Waiting for connection to server");
                mWaitForConnect.WaitOne();

                ProsthesisCore.Messages.ProsthesisHandshakeRequest req = new ProsthesisCore.Messages.ProsthesisHandshakeRequest();
                req.VersionId = ProsthesisCore.ProsthesisConstants.OSVersion;

                if (mClient.Connected)
                {
                    ProsthesisDataPacket packet = ProsthesisDataPacket.BoxMessage <ProsthesisHandshakeRequest>(req);
                    mClient.Send(packet.Bytes, 0, packet.Bytes.Length);

                    ConsoleKey key = ConsoleKey.A;
                    do
                    {
                        while (mPacketParser.MoveNext())
                        {
                            ProsthesisMessage mess = mPacketParser.Current;
                            if (mess is ProsthesisHandshakeResponse)
                            {
                                ProsthesisHandshakeResponse castMess = mess as ProsthesisHandshakeResponse;
                                mLogger.LogMessage(Logger.LoggerChannels.Events, string.Format("Got handshake response. Authed? {0}", castMess.AuthorizedConnection ? "yes" : "no"));
                            }
                            else if (mess is ProsthesisCommandAck)
                            {
                                ProsthesisCommandAck ack = mess as ProsthesisCommandAck;
                                mLogger.LogMessage(Logger.LoggerChannels.Events, string.Format("Got command acknowledgement for cmd {0}", ack.Command));
                            }
                            else if (mess == null)
                            {
                                mLogger.LogMessage(Logger.LoggerChannels.Events, string.Format("Got a null message from packet parser"));
                            }
                            else
                            {
                                mLogger.LogMessage(Logger.LoggerChannels.Events, string.Format("Got unhandled message type: {0}", mess.GetType()));
                            }
                        }

                        //Check 60 times per second for messages (simulating a game loop)
                        System.Threading.Thread.Sleep(16);

                        if (Console.KeyAvailable)
                        {
                            key = Console.ReadKey().Key;

                            switch (key)
                            {
                            case ConsoleKey.I:
                                SendCommand(ProsthesisCore.ProsthesisConstants.ProsthesisCommand.Initialize);
                                break;

                            case ConsoleKey.S:
                                SendCommand(ProsthesisCore.ProsthesisConstants.ProsthesisCommand.Shutdown);
                                break;

                            case ConsoleKey.R:
                                SendCommand(ProsthesisCore.ProsthesisConstants.ProsthesisCommand.Resume);
                                break;

                            case ConsoleKey.P:
                                SendCommand(ProsthesisCore.ProsthesisConstants.ProsthesisCommand.Pause);
                                break;

                            case ConsoleKey.E:
                                SendCommand(ProsthesisCore.ProsthesisConstants.ProsthesisCommand.EmergencyStop);
                                break;
                            }
                        }
                    } while (key != ConsoleKey.X && mClient.Connected);
                    mClient.Shutdown();
                }
                else
                {
                    ConsoleKey key = ConsoleKey.K;
                    do
                    {
                        System.Threading.Thread.Sleep(16);
                        if (Console.KeyAvailable)
                        {
                            key = Console.ReadKey().Key;
                        }
                    }while (key != ConsoleKey.X);
                }

                mClient = null;
            }

            mTelemReceiver.Stop();
            mTelemetryLogger.ShutDown();
            mLogger.ShutDown();
        }