Esempio n. 1
0
        public void TestGameModePoolModifiedAndGameModePoolInserted()
        {
            var state = new ProtocolState();

            state.GameModePool.TryAdd("gamemode1", new GameModeModel() {
                Name = "gamemode 1",
                FriendlyName = "Boring GameMode 1"
            });

            var segment = new ProtocolStateSegment() {
                GameModePool = new ConcurrentDictionary<String, GameModeModel>()
            };
            segment.GameModePool.TryAdd("gamemode1", new GameModeModel() {
                Name = "gamemode 1",
                FriendlyName = "Fun GameMode 1"
            });
            segment.GameModePool.TryAdd("gamemode2", new GameModeModel() {
                Name = "gamemode 2",
                FriendlyName = "Fun GameMode 2"
            });

            state.Set(segment);

            Assert.AreEqual(2, state.GameModePool.Count);
            Assert.AreEqual("Fun GameMode 1", state.GameModePool["gamemode1"].FriendlyName);
            Assert.AreEqual("Fun GameMode 2", state.GameModePool["gamemode2"].FriendlyName);
        }
        //Invoke by Transporter, process the message
        internal void processMessage(byte[] bytes)
        {
            Package pkg = PackageProtocol.decode(bytes);

            //Ignore all the message except handshading at handshake stage
            if (pkg.type == PackageType.PKG_HANDSHAKE && this.state == ProtocolState.handshaking)
            {

                //Ignore all the message except handshading
                JsonObject data = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(pkg.body));

                processHandshakeData(data);

                this.state = ProtocolState.working;

            }
            else if (pkg.type == PackageType.PKG_HEARTBEAT && this.state == ProtocolState.working)
            {
                this.heartBeatService.resetTimeout();
            }
            else if (pkg.type == PackageType.PKG_DATA && this.state == ProtocolState.working)
            {
                this.heartBeatService.resetTimeout();
                pc.processMessage(messageProtocol.decode(pkg.body));
            }
            else if (pkg.type == PackageType.PKG_KICK)
            {
                this.getPomeloClient().disconnect();
                this.close();
            }
        }
Esempio n. 3
0
        public void TestSingleGameModePoolRemoved()
        {
            var state = new ProtocolState();

            state.GameModePool.TryAdd("gamemode1", new GameModeModel() {
                Name = "gamemode 1",
                FriendlyName = "Boring GameMode 1"
            });
            state.GameModePool.TryAdd("gamemode2", new GameModeModel() {
                Name = "gamemode 2",
                FriendlyName = "Boring GameMode 2"
            });

            var segment = new ProtocolStateSegment() {
                GameModePool = new ConcurrentDictionary<String, GameModeModel>()
            };
            segment.GameModePool.TryAdd("gamemode1", new GameModeModel() {
                Name = "gamemode 1",
                FriendlyName = "Boring GameMode 1"
            });

            state.Removed(segment);

            Assert.AreEqual(1, state.GameModePool.Count);
            Assert.AreEqual("Boring GameMode 2", state.GameModePool.First().Value.FriendlyName);
        }
Esempio n. 4
0
        public void TestMapPoolIdenticalNamesDifferentGameModes()
        {
            var state = new ProtocolState();

            state.MapPool.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "First Map"
            });
            state.MapPool.TryAdd("gamemode2/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode2"
                },
                FriendlyName = "Second Map"
            });

            var segment = new ProtocolStateSegment() {
                MapPool = new ConcurrentDictionary<String, MapModel>()
            };
            segment.MapPool.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "First Map"
            });

            state.Removed(segment);

            Assert.AreEqual(1, state.MapPool.Count);
            Assert.AreEqual("Second Map", state.MapPool.First().Value.FriendlyName);
        }
Esempio n. 5
0
        public int HandlePacket(Packet packetIn, SerialPort serialPort, Chart chart = null, bool forceSend = false)
        {
            if (forceSend)
            {
                writePacket(packetIn, serialPort);
                return (int)ProtocolDirective.DoNothing;
            }

            switch (state)
            {
                case ProtocolState.Idle:
                    if (packetIn.command == ((byte)PacketType.Start | (byte)PacketSender.GUI))
                    {// If we're idle and waiting to be told to do something and we receive a start packet from the GUI
                        writePacket(packetIn, serialPort);
                        state = ProtocolState.StartSent;
                    }
                    break;

                case ProtocolState.StartSent:
                    if (packetIn.command == ((byte)PacketType.Start | (byte)PacketSender.Microcontroller))
                    {// If we're waiting for an acknowledge and we receive one from the microcontroller
                        state = ProtocolState.WaitForData;
                    }
                    else if (packetIn.command == ((byte)PacketType.Error | (byte)PacketSender.Microcontroller))
                    {// If we're waiting for an acknowledge and we receive an error packet from the microcontroller
                        state = ProtocolState.ErrorReceived;
                    }
                    break;

                case ProtocolState.StopSent:
                    if (packetIn.command == ((byte)PacketType.Stop | (byte)PacketSender.Microcontroller))
                    {// If we're waiting for an acknowledge and we receive one from the microcontroller
                        state = ProtocolState.Idle;
                    }
                    break;

                case ProtocolState.WaitForData:
                    if (packetIn.command == ((byte)PacketType.Report | (byte)PacketSender.Microcontroller))
                    {// If we're waiting for data packets and we receive one from the microcontroller
                        byte[] payload = new byte[1];
                        payload[0] = packetIn.payload[0];
                        Packet ackPacket = new Packet((byte)PacketType.Report | (byte)PacketSender.GUI, 1, payload);
                        writePacket(ackPacket, serialPort);
                        return (int)ProtocolDirective.AddData;
                    }
                    else if (packetIn.command == ((byte)PacketType.Stop | (byte)PacketSender.GUI))
                    {// If we're waiting for data packets and we receive a stop packet from the GUI
                        writePacket(packetIn, serialPort);
                        state = ProtocolState.StopSent;
                    }
                    break;

                case ProtocolState.ErrorReceived:
                    break;

                default:
                    break;
            }
            return (int)ProtocolDirective.DoNothing;
        }
Esempio n. 6
0
        public void TestGroupPoolModifiedAndGroupPoolInserted()
        {
            var state = new ProtocolState();

            state.Groups.TryAdd("Team/1", new GroupModel() {
                Uid = "1",
                Type = GroupModel.Team,
                FriendlyName = "Boring Group 1"
            });

            var segment = new ProtocolStateSegment() {
                Groups = new ConcurrentDictionary<String, GroupModel>()
            };
            segment.Groups.TryAdd("Team/1", new GroupModel() {
                Uid = "1",
                Type = GroupModel.Team,
                FriendlyName = "Fun Group 1"
            });
            segment.Groups.TryAdd("Team/2", new GroupModel() {
                Uid = "2",
                Type = GroupModel.Team,
                FriendlyName = "Fun Group 2"
            });

            state.Modified(segment);

            Assert.AreEqual(2, state.Groups.Count);
            Assert.AreEqual("Fun Group 1", state.Groups["Team/1"].FriendlyName);
            Assert.AreEqual("Fun Group 2", state.Groups["Team/2"].FriendlyName);
        }
 public Protocol(PomeloClient pc, System.Net.Sockets.Socket socket)
 {
     this.pc = pc;
     this.transporter = new Transporter (socket, this.processMessage);
     this.handshake = new HandShakeService(this);
     this.state = ProtocolState.start;
 }
        internal void close()
        {
            transporter.close();

            if (heartBeatService != null) heartBeatService.stop();

            this.state = ProtocolState.closed;
        }
Esempio n. 9
0
        public Protocol(Connection pc, System.Net.Sockets.Socket socket)
        {
            this._pomeloClient             = pc;
            this._transporter              = new Transporter(socket, this.processMessage);
            this._transporter.onDisconnect = onDisconnect;

            this._handshake = new HandShakeService(this);
            this._state     = ProtocolState.start;
        }
Esempio n. 10
0
        public Protocol(MongoClient mc, System.Net.Sockets.Socket socket)
        {
            this.mc          = mc;
            this.transporter = new Transporter(socket, this.processMessage);
            this.transporter.onDisconnect = onDisconnect;

            this.handshake = new HandShakeService(this);
            this.state     = ProtocolState.start;
        }
Esempio n. 11
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RfbMessageReceiver"/>.
        /// </summary>
        /// <param name="context">The connection context.</param>
        public RfbMessageReceiver(RfbConnectionContext context) : base("RFB Message Receiver")
        {
            _context = context ?? throw new ArgumentNullException(nameof(context));
            _state   = context.GetState <ProtocolState>();
            _logger  = context.Connection.LoggerFactory.CreateLogger <RfbMessageReceiver>();

            // Log failure events from background thread base
            Failed += (sender, args) => _logger.LogWarning(args.Exception, "Receive loop failed.");
        }
Esempio n. 12
0
 private void Reconnect()
 {
     if (mRunning && ((mConnection.State == BotConnectionState.Stopped) || (mConnection.State == BotConnectionState.Failed)))
     {
         mState = ProtocolState.Idle;
         mConnection.Start();
         UpdateTimeout();
     }
 }
Esempio n. 13
0
 public bool TryCreatePacket(int packetId, PacketBoundTo boundTo, ProtocolState state, out IPacket packet)
 {
     packet = _packetInfo.FirstOrDefault(info =>
                                         info.PacketId == packetId &&
                                         info.BoundTo == boundTo &&
                                         (info.State == state || info.State == ProtocolState.Any)
                                         )?.Constructor();
     return(packet != null);
 }
 private void Disconnect()
 {
     if (_proto_state != ProtocolState.NONE)
     {
         _mystate     = MyState.NONE;
         _proto_state = ProtocolState.NONE;
         _usb2snes.Disconnect();
     }
 }
Esempio n. 15
0
 protected StateMachine(TransactionEnlistment enlistment)
 {
     this.enlistment      = enlistment;
     this.state           = enlistment.State;
     this.synchronization = new SynchronizationManager(this);
     if (DebugTrace.Warning || DiagnosticUtility.ShouldTraceWarning)
     {
         this.history = new StateMachineHistory();
     }
 }
Esempio n. 16
0
        public void Close()
        {
            this.transporter.Close();
            if (this.heartBeatService != null)
            {
                this.heartBeatService.Stop();
            }

            this.state = ProtocolState.closed;
        }
        public Protocol(PomeloClient pc, System.Net.Sockets.Socket socket)
        {
            this.pc = pc;
            Trace.TraceInformation("this.transporter = new Transporter");
            this.transporter = new Transporter(socket, this.processMessage);
            this.transporter.onDisconnect = onDisconnect;

            this.handshake = new HandShakeService(this);
            this.state     = ProtocolState.start;
        }
Esempio n. 18
0
        public Protocol(ITransporter transproter, Action <Message> messageProcessor, Action onProtoClose)
        {
            this.transporter = transproter;
            this.transporter.onReceive(this.processMessage);
            this.onProtocolClose  += onProtoClose;
            this.messageProcessor += messageProcessor;

            this.handshake = new HandShakeService(this);
            this.state     = ProtocolState.ready;
        }
        public Protocol(PomeloClient pc, TransporterBase inTransporter)
        {
            this.pc          = pc;
            this.transporter = inTransporter;
            this.transporter.SetMessageProcesser(this.processMessage);
            this.transporter.onDisconnect = onDisconnect;

            this.handshake = new HandShakeService(this);
            this.state     = ProtocolState.start;
        }
Esempio n. 20
0
 public LogEntrySerialization(ProtocolState state)
 {
     if (state == null)
     {
         throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("state"));
     }
     this.state           = state;
     this.protocolVersion = state.ProtocolVersion;
     this.maxLogEntrySize = this.state.TransactionManager.MaxLogEntrySize;
 }
Esempio n. 21
0
        public bool StartRun(ConfigPacket configPacket, StartPacket startPacket)
        {
            if (configPacket != null)                                                                                   // If we need to send a configuration packet (by default, we always will),
            {
                try {
                    writePacket <ConfigPacket>(configPacket, serialPort);                                       // try writing the packet
                } catch (Exception) {                                                                           // If something bad happens,
                    this.errorCode = (byte)ErrorCode.TimeOut;                                                   // set the error code to the ProtocolHandler-specific code,
                    return(false);                                                                              // and return false
                }
                this.state = ProtocolState.ConfigSent;                                                          // Otherwise, set the state,
                oneshotTimer(2000);                                                                             // start the timer,
                while (!this.timerDone && this.state == ProtocolState.ConfigSent)
                {
                    ;                                                                                   // and wait for either the timer to stop or the microcontroller to respond (state changes in HandlePacket)
                }
                if (this.state == ProtocolState.ConfigSent)                                             // If we haven't changed states, that means we timed out,
                {
                    this.state     = ProtocolState.Idle;                                                // so set us back to idle,
                    this.errorCode = (byte)ErrorCode.TimeOut;                                           // set the error code to the ProtocolHandler-specific code,
                    return(false);                                                                      // and return false
                }
                if (this.state == ProtocolState.ErrorReceived)                                          // If we received an error,
                {
                    this.state = ProtocolState.Idle;                                                    // set us back to idle,
                    return(false);                                                                      // and return false
                }
            }

            try {                                                                                               // If we made it to here, that means we successfully sent the configuration packet
                writePacket <StartPacket>(startPacket, serialPort);                                             // Try writing the packet
            } catch (Exception) {                                                                               // If something bad happens,
                this.errorCode = (byte)ErrorCode.TimeOut;                                                       // set the error code to the ProtocolHandler-specific code,
                return(false);                                                                                  // and return false
            }
            this.state = ProtocolState.StartSent;                                                               // Otherwise, set the state,
            oneshotTimer(2000);                                                                                 // start the timer,
            while (!this.timerDone && this.state == ProtocolState.StartSent)
            {
                ;                                                                                       // and wait for either the timer to stop or the microcontroller to respond
            }
            if (this.state == ProtocolState.StartSent)                                                  // If we haven't changed states, that means we timed out,
            {
                this.state     = ProtocolState.Idle;                                                    // so set us back to idle,
                this.errorCode = (byte)ErrorCode.TimeOut;                                               // set the error code to the ProtocolHander-specific code,
                return(false);                                                                          // and return false
            }
            if (this.state == ProtocolState.ErrorReceived)                                              // If we received and error,
            {
                this.state = ProtocolState.Idle;                                                        // set us back to idle,
                return(false);                                                                          // and return false
            }

            return(true);                                                                                               // If we made it this far, that means we successfully sent both packets, so return true!
        }
Esempio n. 22
0
        internal void close()
        {
            transporter.close();

            if (heartBeatService != null)
            {
                heartBeatService.stop();
            }

            this.state = ProtocolState.closed;
        }
 public ClientHandshake(
     VarInt protocolVersion,
     [DataLengthConstraint(Max = 255)] Utf8String serverAddress,
     ushort serverPort,
     VarInt nextState)
 {
     ProtocolVersion = protocolVersion;
     ServerAddress   = serverAddress;
     ServerPort      = serverPort;
     NextState       = nextState.AsEnum <ProtocolState>();
 }
        internal void close()
        {
            Trace.TraceInformation("close");
            transporter.close();

            if (heartBeatService != null)
            {
                heartBeatService.stop();
            }

            this.state = ProtocolState.closed;
        }
Esempio n. 25
0
        public void BeginHandling(Socket socket, string ip)
        {
            _socket          = socket;
            _socket.Blocking = false;

            State  = ProtocolState.Handshaked;
            IP     = ip;
            Active = true;
            DCTime = -1;

            Manager.AddClient(this);
        }
Esempio n. 26
0
        internal void close()
        {
            if(this.state == ProtocolState.closed){
                return;
            }

            this.state = ProtocolState.closed;
            transporter.close();

            if(heartBeatService != null) {
                heartBeatService.stop();
            }
        }
Esempio n. 27
0
 private void ProtocolError(string error)
 {
     if (!mRunning)
     {
         return;
     }
     mLastAvalabilityError = error;
     mState = ProtocolState.Finished;
     UpdateTimeout();
     mConnection.BeginStop();
     mDispatcher.ScheduleInvoke(RETRY_CONNECTION_INTERVAL, new ReconnectEvnetHandler(Reconnect));
     SetAvailable(false);
 }
Esempio n. 28
0
        public void ReadFromPacket(IPacket packet)
        {
            PacketId = packet.PacketId;
            BoundTo  = packet.BoundTo;
            State    = packet.State;
            Content.WriteVarInt(packet.PacketId);
            var pos = BaseStream.Position;

            packet.WriteToStream(Content);
            BaseStream.Position = pos;
            PacketLength        = (int)BaseStream.Length;
            DataLength          = (int)BaseStream.Length;
        }
Esempio n. 29
0
        public void close()
        {
            if (heartBeatService != null)
            {
                heartBeatService.stop();
            }

            this.state = ProtocolState.closed;

            if (onProtocolClose != null)
            {
                onProtocolClose();
            }
        }
Esempio n. 30
0
        internal void StateChangeListener(object sender, ProtocolState state)
        {
            if (state == ProtocolState.Open && previousState == ProtocolState.Reconnecting)
            {
                kuzzle.GetEventHandler().DispatchReconnected();

                Task.Run(async() => {
                    QueryReplayer.WaitLoginToReplay = true;
                    await Recover();
                });
            }

            previousState = state;
        }
 public void Reset()
 {
     // We don't clear the receive buffer since there may be queued data that is still relevent to us,
     // plus clearing it here messes up the loop in ProcessReceivedData.
     protocolState        = ProtocolState.Idle;
     unacknowledgedPacket = null;
     lastSendTime         = DateTime.MinValue;
     sendRetries          = 0;
     sendPVTData          = false;
     sendSatData          = false;
     pvtPacket            = null;
     satDataPacket        = null;
     sendStream.SetLength(0);
 }
Esempio n. 32
0
 private void MConnection_StateChanged(IBotConnection sender, BotConnectionState state)
 {
     if (!mRunning)
     {
         return;
     }
     if ((state == BotConnectionState.Stopped) || (state == BotConnectionState.Failed))
     {
         ProtocolError((mConnection.LastError != null) ? mConnection.LastError : "Connection failed.");
     }
     else if (state == BotConnectionState.Started)
     {
         mConnection.SendMessage(Encoding.ASCII.GetBytes("INIT"));
         mState = ProtocolState.InitSent;
         UpdateTimeout();
     }
 }
Esempio n. 33
0
        private void processHandshakeData(JsonObject msg)
        {
            if ((!msg.ContainsKey("code") || !msg.ContainsKey("sys")) || (Convert.ToInt32(msg["code"]) != 200))
            {
                throw new Exception("Handshake error! Please check your handshake config.");
            }
            JsonObject obj2 = (JsonObject)msg["sys"];
            JsonObject dict = new JsonObject();

            if (obj2.ContainsKey("dict"))
            {
                dict = (JsonObject)obj2["dict"];
            }
            JsonObject obj4         = new JsonObject();
            JsonObject serverProtos = new JsonObject();
            JsonObject clientProtos = new JsonObject();

            if (obj2.ContainsKey("protos"))
            {
                obj4         = (JsonObject)obj2["protos"];
                serverProtos = (JsonObject)obj4["server"];
                clientProtos = (JsonObject)obj4["client"];
            }
            this.messageProtocol = new MessageProtocol(dict, serverProtos, clientProtos);
            int timeout = 0;

            if (obj2.ContainsKey("heartbeat"))
            {
                timeout = Convert.ToInt32(obj2["heartbeat"]);
            }
            this.heartBeatService = new HeartBeatService(timeout, this);
            if (timeout > 0)
            {
                this.heartBeatService.start();
            }
            this.handshake.ack();
            this.state = ProtocolState.working;
            JsonObject data = new JsonObject();

            if (msg.ContainsKey("user"))
            {
                data = (JsonObject)msg["user"];
            }
            this.handshake.invokeCallback(data);
        }
Esempio n. 34
0
        public void TestRedefineBuildsPlayerOutliers()
        {
            var state = new ProtocolState();

            state.Players.TryAdd("1", new PlayerModel() {
                Uid = "1",
                Kills = 2
            });
            state.Players.TryAdd("2", new PlayerModel() {
                Uid = "2",
                Kills = 4
            });
            state.Players.TryAdd("3", new PlayerModel() {
                Uid = "3",
                Kills = 4
            });
            state.Players.TryAdd("4", new PlayerModel() {
                Uid = "4",
                Kills = 4
            });
            state.Players.TryAdd("5", new PlayerModel() {
                Uid = "5",
                Kills = 5
            });
            state.Players.TryAdd("6", new PlayerModel() {
                Uid = "6",
                Kills = 5
            });
            state.Players.TryAdd("7", new PlayerModel() {
                Uid = "7",
                Kills = 7
            });
            state.Players.TryAdd("8", new PlayerModel() {
                Uid = "8",
                Kills = 9
            });

            state.Redefine();

            Assert.AreEqual("Kills", state.Players["8"].Outliers.First().Field);
            Assert.AreEqual(5.0f, state.Players["8"].Outliers.First().Mean);
            Assert.AreEqual(2.0f, state.Players["8"].Outliers.First().StandardDeviation);
            Assert.AreEqual(2.0f, state.Players["8"].Outliers.First().Deviations);
            Assert.AreEqual(9.0f, state.Players["8"].Outliers.First().Value);
        }
Esempio n. 35
0
        public PacketIdMappingAttribute(ProtocolState state, int rawId)
        {
            switch (state)
            {
            case ProtocolState.Handshaking:
            case ProtocolState.Status:
            case ProtocolState.Login:
            case ProtocolState.Play:
                break;

            default:
            case ProtocolState.Undefined:
            case ProtocolState.Disconnected:
                throw new ArgumentOutOfRangeException(nameof(state));
            }

            State = state;
            RawId = rawId;
        }
        private bool isConnectionReady()
        {
            Debug.WriteLine("Checking connection");
            if (_proto_state == ProtocolState.ATTACHED)
            {
                return(true);
            }

            // this method actually does a BLOCKING request-response cycle (!!)
            bool connected = _usb2snes.Connected();

            if (!connected)
            {
                SetState(MyState.NONE);
                _proto_state = ProtocolState.NONE;
            }
            this.connect();
            return(false);
        }
Esempio n. 37
0
        private void processHandshakeData(JsonData msg)
        {
            //Handshake error
            if (!msg.ContainsKey("code") || !msg.ContainsKey("sys") || Convert.ToInt32(msg["code"].ToString()) != 200)
            {
                throw new Exception("Handshake error! Please check your handshake config.");
            }
            //Debug.Log(msg.ToJson());

            //Set compress data
            JsonData sys = (JsonData)msg["sys"];


            //Init heartbeat service
            int interval = 0;

            if (sys.ContainsKey("heartbeat"))
            {
                interval = Convert.ToInt32(sys["heartbeat"].ToString());
            }
            heartBeatService = new HeartBeatService(interval, this);

            if (interval > 0)
            {
                heartBeatService.start();
            }

            this.InitProtoCache(sys);

            //send ack and change protocol state
            handshake.ack();
            this.state = ProtocolState.working;

            //Invoke handshake callback
            JsonData user = new JsonData();

            if (msg.ContainsKey("user"))
            {
                user = (JsonData)msg["user"];
            }
            handshake.invokeCallback(user);
        }
Esempio n. 38
0
        private void processHandshakeData(byte[] data)
        {
            //Ignore all the message except handshading
            JsonObject msg = (JsonObject)SimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(data));

            //Handshake error
            if (!msg.ContainsKey("code") || !msg.ContainsKey("sys") || Convert.ToInt32(msg["code"]) != 200)
            {
                throw new Exception("Handshake error! Please check your handshake config.");
            }

            //Set compress data
            JsonObject sys = (JsonObject)msg["sys"];

            JsonObject dict = new JsonObject();

            if (sys.ContainsKey("dict"))
            {
                dict = (JsonObject)sys["dict"];
            }
            messageProtocol = new MessageProtocol(dict);

            //Init heartbeat service
            int interval = 0;

            if (sys.ContainsKey("heartbeat"))
            {
                interval = Convert.ToInt32(sys["heartbeat"]);
            }
            heartBeatService = new HeartBeatService(interval, this);

            if (interval > 0)
            {
                heartBeatService.start();
            }

            //send ack and change protocol state
            handshake.ack();
            this.state = ProtocolState.working;
            handshake.invokeCallback(data);
        }
Esempio n. 39
0
        private void MConnection_Message(IBotConnection sender, byte[] message)
        {
            switch (mState)
            {
            case ProtocolState.InitSent:
                if (Encoding.ASCII.GetString(message) == "REDY")
                {
                    mState = ProtocolState.Connected;
                    UpdateTimeout();
                    SetAvailable(true);
                }
                else
                {
                    ProtocolError("Invalid response from bot.");
                }
                break;

            case ProtocolState.Connected:
                string text = Encoding.ASCII.GetString(message);
                int    time;
                if (int.TryParse(text, out time))
                {
                    if (mTimerMain != null)
                    {
                        mTimerMain.SetTime(time);
                    }
                }
                else
                {
                    ProtocolError("Invalid message from bot.");
                }
                break;

            default:
                ProtocolError("Unexpected response from bot.");
                break;
            }
        }
Esempio n. 40
0
 internal void processMessage(byte[] bytes)
 {
     Package package = PackageProtocol.decode(bytes);
     if (package.type == PackageType.PKG_HANDSHAKE && this.state == ProtocolState.handshaking)
     {
         this.processHandshakeData((JsonObject)SimpleJson.SimpleJson.DeserializeObject(Encoding.UTF8.GetString(package.body)));
         this.state = ProtocolState.working;
     }
     else if (package.type == PackageType.PKG_HEARTBEAT && this.state == ProtocolState.working)
         this.heartBeatService.resetTimeout();
     else if (package.type == PackageType.PKG_DATA && this.state == ProtocolState.working)
     {
         this.heartBeatService.resetTimeout();
         this.pc.processMessage(this.messageProtocol.decode(package.body));
     }
     else
     {
         if (package.type != PackageType.PKG_KICK)
             return;
         this.getPomeloClient().disconnect();
         this.close();
     }
 }
Esempio n. 41
0
        public void TestSingleUidBansRemoved()
        {
            var state = new ProtocolState();

            state.Bans.TryAdd("Permanent/Uid/1", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Permanent
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Uid = "1",
                            Score = 1
                        }
                    }
                }
            });
            state.Bans.TryAdd("Time/Uid/2", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Time
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Uid = "2",
                            Score = 2
                        }
                    }
                }
            });

            var segment = new ProtocolStateSegment() {
                Bans = new ConcurrentDictionary<String, BanModel>()
            };
            segment.Bans.TryAdd("Permanent/Uid/1", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Permanent
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Uid = "1",
                            Score = 1
                        }
                    }
                }
            });

            state.Removed(segment);

            Assert.AreEqual(1, state.Bans.Count);
            Assert.AreEqual(TimeSubsetContext.Time, state.Bans.First().Value.Scope.Times.First().Context);
        }
Esempio n. 42
0
        public void TestSinglePlayersRemoved()
        {
            var state = new ProtocolState();

            state.Players.TryAdd("1", new PlayerModel() {
                Uid = "1",
                Score = 1
            });
            state.Players.TryAdd("2", new PlayerModel() {
                Uid = "2",
                Score = 2
            });

            var segment = new ProtocolStateSegment() {
                Players = new ConcurrentDictionary<String, PlayerModel>()
            };
            segment.Players.TryAdd("1", new PlayerModel() {
                Uid = "1",
                Score = 1
            });

            state.Removed(segment);

            Assert.AreEqual(1, state.Players.Count);
            Assert.AreEqual(2, state.Players.First().Value.Score);
        }
Esempio n. 43
0
        public void TestSingleMapsRemoved()
        {
            var state = new ProtocolState();

            state.Maps.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "Boring Map 1"
            });
            state.Maps.TryAdd("gamemode2/map2", new MapModel() {
                Name = "map2",
                GameMode = new GameModeModel() {
                    Name = "gamemode2"
                },
                FriendlyName = "Boring Map 2"
            });

            var segment = new ProtocolStateSegment() {
                Maps = new ConcurrentDictionary<String, MapModel>()
            };
            segment.Maps.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "Boring Map 1"
            });

            state.Removed(segment);

            Assert.AreEqual(1, state.Maps.Count);
            Assert.AreEqual("Boring Map 2", state.Maps.First().Value.FriendlyName);
        }
Esempio n. 44
0
        public void TestSingleItemPoolRemoved()
        {
            var state = new ProtocolState();

            state.Items.TryAdd("1", new ItemModel() {
                Name = "1",
                FriendlyName = "Boring Item 1"
            });
            state.Items.TryAdd("2", new ItemModel() {
                Name = "2",
                FriendlyName = "Boring Item 2"
            });

            var segment = new ProtocolStateSegment() {
                Items = new ConcurrentDictionary<String, ItemModel>()
            };
            segment.Items.TryAdd("1", new ItemModel() {
                Name = "1",
                FriendlyName = "Boring Item 1"
            });

            state.Removed(segment);

            Assert.AreEqual(1, state.Items.Count);
            Assert.AreEqual("Boring Item 2", state.Items.First().Value.FriendlyName);
        }
Esempio n. 45
0
        public void TestTwoMapsIdenticalNamesDifferentGameModes()
        {
            var state = new ProtocolState();

            state.Maps.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "Boring Gamemode 1"
            });
            state.Maps.TryAdd("gamemode2/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode2"
                },
                FriendlyName = "Boring Gamemode 2"
            });

            var segment = new ProtocolStateSegment() {
                Maps = new ConcurrentDictionary<String, MapModel>()
            };
            segment.Maps.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "Fun First Map"
            });
            segment.Maps.TryAdd("gamemode2/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode2"
                },
                FriendlyName = "Fun Second Map"
            });

            state.Modified(segment);

            Assert.AreEqual(2, state.Maps.Count);
            Assert.AreEqual("Fun First Map", state.Maps.First(item => item.Value.Name == "map1" && item.Value.GameMode.Name == "gamemode1").Value.FriendlyName);
            Assert.AreEqual("Fun Second Map", state.Maps.First(item => item.Value.Name == "map1" && item.Value.GameMode.Name == "gamemode2").Value.FriendlyName);
        }
Esempio n. 46
0
        public void TestPlayerModifiedAndPlayerInserted()
        {
            var state = new ProtocolState();

            state.Players.TryAdd("1", new PlayerModel() {
                Uid = "1",
                Score = 1
            });

            var segment = new ProtocolStateSegment() {
                Players = new ConcurrentDictionary<String, PlayerModel>()
            };
            segment.Players.TryAdd("1", new PlayerModel() {
                Uid = "1",
                Score = 100
            });
            segment.Players.TryAdd("2", new PlayerModel() {
                Uid = "2",
                Score = 200
            });

            state.Modified(segment);

            Assert.AreEqual(2, state.Players.Count);
            Assert.AreEqual(100, state.Players.First(item => item.Value.Uid == "1").Value.Score);
            Assert.AreEqual(200, state.Players.First(item => item.Value.Uid == "2").Value.Score);
        }
Esempio n. 47
0
        internal void start(JsonObject user, Action<JsonObject> callback)
        {
            this.transporter.start();
            this.handshakeUser = user;
            this.handshakeCallback = callback;

            this.state = ProtocolState.handshaking;
        }
		public void Reset()
		{
			// We don't clear the receive buffer since there may be queued data that is still relevent to us,
			// plus clearing it here messes up the loop in ProcessReceivedData.
			protocolState = ProtocolState.Idle;
			unacknowledgedPacket = null;
			lastSendTime = DateTime.MinValue;
			sendRetries = 0;
			sendPVTData = false;
			sendSatData = false;
			pvtPacket = null;
			satDataPacket = null;
			sendStream.SetLength(0);
		}
Esempio n. 49
0
        internal void start(JsonObject user, Action<JsonObject> callback)
        {
            this.transporter.start();
            this.handshake.request(user, callback);

            this.state = ProtocolState.handshaking;
        }
		private void ProcessPacket(byte[] packet)
		{
			// Extract the packet ID and data length.
			byte packetId = packet[0];
			byte dataLength = packet[1];

			// Verify the checksum. We have previously checked that packets are at least 3 bytes long.
			int i;
			byte checksum = 0;
			for (i = 0; i < packet.Length - 1; i++)
				checksum -= packet[i];
			if (checksum != packet[packet.Length - 1])
			{
				// Corrupt packet. NACK it.
				SendPacket(BuildNACKPacket(packetId));
			}
			else if (packetId == (byte)PacketId.ACK)
			{
				// ACK. We can only have an unacknowledged packet if we are not in the Idle state.
				if ((protocolState != ProtocolState.Idle) && (dataLength > 0) && (packet[2] == unacknowledgedPacket[1]))
				{
					// Advance the protocol state. This is where multi-part communications are continued.
					switch (protocolState) 
					{
						case ProtocolState.SendProductData:
							SendPacket(BuildProtocolArrayPacket(), ProtocolState.NeedAck);
							break;
						case ProtocolState.SendAlmanacStart:
							// We specified D550 as the data type, so we don't actually have to send any data.
							SendPacket(BuildTransferCompletePacket((Int16)CommandId.TRANSFER_ALM), ProtocolState.NeedAck);
							break;
						default:
							// No more steps, or not a multi-part communication.
							unacknowledgedPacket = null;
							protocolState = ProtocolState.Idle;
							break;
					}

					// If we are now idle, check if there is any PVT or satellite data
					// that needs to be sent. If we were idle when the PVT or satellite
					// data arrived, it would have already been sent.
					if ((protocolState == ProtocolState.Idle) && (pvtPacket != null))
					{
						SendPacket(pvtPacket);
						pvtPacket = null;
					}
					if ((protocolState == ProtocolState.Idle) && (satDataPacket != null))
					{
						SendPacket(satDataPacket);
						satDataPacket = null;
					}
				}
			}
			else if (packetId == (byte)PacketId.NACK)
			{
				// We only need to retransmit if we aren't in the Idle state.
				if ((protocolState != ProtocolState.Idle) && (dataLength > 0) && (packet[2] == unacknowledgedPacket[1]))
					SendPacket(unacknowledgedPacket);
			}
			else if (protocolState == ProtocolState.Idle)
			{
				// Can only accept new commands if we are idle. The exception to this would be the interruption of
				// a record transfer, but we don't send any records so we will never have this.
				if (packetId != (byte)PacketId.PRODUCT_RQST)
					SendPacket(BuildACKPacket(packetId));
				switch (packetId) 
				{
					case (byte)PacketId.PRODUCT_RQST:
						// This is the first packet of a conversation, so start from scratch.
						Reset();

						// Need to send the ACK packet here as the reset will have cleared the send buffer.
						SendPacket(BuildACKPacket(packetId));
						SendPacket(BuildProductDataPacket(ProductId, SoftwareVersion, ProductDescription), ProtocolState.SendProductData);
						break;
					case (byte)PacketId.UNLOCK_CODE:
						SendPacket(BuildUnlockResponsePacket(true), ProtocolState.NeedAck);
						break;
					/*
					case (byte)PacketId.ENABLE_ASYNC_EVENTS:
						if (dataLength > 0)
						{
							// Enable or disable async satellite data depending on
							// which bits are set.
							if (packet[2] == 0) 
								sendAsyncSatData = false;
							else if ((packet[2] & 0x80) > 0)
								sendAsyncSatData = true;
						}
						break;
					*/
					case (byte)PacketId.COMMAND_DATA:
						if (dataLength > 0) 
						{
							switch (packet[2]) 
							{
								case (byte)CommandId.TRANSFER_ALM:
									// We always send an empty almanac.
									SendPacket(BuildRecordsPacket(0), ProtocolState.SendAlmanacStart);
									break;
								case (byte)CommandId.TRANSFER_TIME:
									DateTime utc = DateTime.UtcNow;
									SendPacket(BuildDateTimePacket((byte)utc.Month, (byte)utc.Day, (UInt16)utc.Year,
										(byte)utc.Hour, (byte)utc.Minute, (byte)utc.Second), ProtocolState.NeedAck);
									break;
								case (byte)CommandId.TRANSFER_UNIT_ID:
									// The Que software doesn't send an ACK for this packet, so don't expect one.
									SendPacket(BuildUnitIdPacket(UnitId));
									//SendPacket(BuildUnitIdPacket(UnitId), ProtocolState.NeedAck);
									break;
								case (byte)CommandId.START_PVT_DATA:
									sendPVTData = true;
									sendSatData = true;
									break;
								case (byte)CommandId.STOP_PVT_DATA:
									sendPVTData = false;
									sendSatData = false;
									break;
								case (byte)CommandId.START_SAT_DATA:
								case (byte)CommandId.START_DIFF_SAT_DATA:
									sendSatData = true;
									break;
							}
						}
						break;
				}
			}
			else
			{
				// We are not idle, and the packet wasn't relevent to changing that. That probably means that
				// the received packet is out of sequence, but we simply use this as a trigger to check if a
				// retransmit is necessary. This is in the hopes that the other end is capable of recovering
				// from this situation, since we certainly aren't.
				DoRetransmissionCheck();
			}
		}
		private void SendPacket(byte[] packet, ProtocolState newProtocolState)
		{
			protocolState = newProtocolState;
			unacknowledgedPacket = packet;
			SendPacket(packet);
		}
Esempio n. 52
0
        public void TestMultipleItemPoolModified()
        {
            var state = new ProtocolState();

            state.Items.TryAdd("1", new ItemModel() {
                Name = "1",
                FriendlyName = "Boring Item 1"
            });
            state.Items.TryAdd("2", new ItemModel() {
                Name = "2",
                FriendlyName = "Boring Item 2"
            });

            var segment = new ProtocolStateSegment() {
                Items = new ConcurrentDictionary<String, ItemModel>()
            };
            segment.Items.TryAdd("1", new ItemModel() {
                Name = "1",
                FriendlyName = "Fun Item 1"
            });
            segment.Items.TryAdd("2", new ItemModel() {
                Name = "2",
                FriendlyName = "Fun Item 2"
            });

            state.Modified(segment);

            Assert.AreEqual(2, state.Items.Count);
            Assert.AreEqual("Fun Item 1", state.Items["1"].FriendlyName);
            Assert.AreEqual("Fun Item 2", state.Items["2"].FriendlyName);
        }
Esempio n. 53
0
        public void TestMultipleMapsModified()
        {
            var state = new ProtocolState();

            state.Maps.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "Boring Map 1"
            });
            state.Maps.TryAdd("gamemode2/map2", new MapModel() {
                Name = "map2",
                GameMode = new GameModeModel() {
                    Name = "gamemode2"
                },
                FriendlyName = "Boring Map 2"
            });

            var segment = new ProtocolStateSegment() {
                Maps = new ConcurrentDictionary<String, MapModel>()
            };
            segment.Maps.TryAdd("gamemode1/map1", new MapModel() {
                Name = "map1",
                GameMode = new GameModeModel() {
                    Name = "gamemode1"
                },
                FriendlyName = "Fun Map 1"
            });
            segment.Maps.TryAdd("gamemode2/map2", new MapModel() {
                Name = "map2",
                GameMode = new GameModeModel() {
                    Name = "gamemode2"
                },
                FriendlyName = "Fun Map 2"
            });

            state.Modified(segment);

            Assert.AreEqual(2, state.Maps.Count);
            Assert.AreEqual("Fun Map 1", state.Maps.First(item => item.Value.Name == "map1").Value.FriendlyName);
            Assert.AreEqual("Fun Map 2", state.Maps.First(item => item.Value.Name == "map2").Value.FriendlyName);
        }
Esempio n. 54
0
 public ProtocolHandler()
 {
     state = ProtocolState.Idle;
 }
Esempio n. 55
0
        public void TestStateSandboxedNotNull()
        {
            IProtocolState state = new ProtocolState();

            var controller = new SandboxProtocolController() {
                SandboxedProtocol = new MockIntegrationTestProtocol() {
                    WaitingState = state
                }
            };

            Assert.AreEqual(state, controller.State);
        }
Esempio n. 56
0
        public void TestSettingsModified()
        {
            var state = new ProtocolState() {
                Settings = new Settings() {
                    Current = {
                        ServerNameText = "Boring Name"
                    }
                }
            };

            state.Modified(new ProtocolStateSegment() {
                Settings = new Settings() {
                    Current = {
                        ServerNameText = "Fun Name"
                    }
                }
            });

            Assert.AreEqual("Fun Name", state.Settings.Current.ServerNameText);
        }
Esempio n. 57
0
        private void processHandshakeData(JsonObject msg)
        {
            //Handshake error
            if(!msg.ContainsKey("code") || !msg.ContainsKey("sys") || Convert.ToInt32(msg["code"]) != 200){
                throw new Exception("Handshake error! Please check your handshake config.");
            }

            //Set compress data
            JsonObject sys = (JsonObject)msg["sys"];

            JsonObject dict = new JsonObject();
            if(sys.ContainsKey("dict")) dict = (JsonObject)sys["dict"];

            JsonObject protos = new JsonObject();
            JsonObject serverProtos = new JsonObject();
            JsonObject clientProtos = new JsonObject();

            if(sys.ContainsKey("protos")){
                protos = (JsonObject)sys["protos"];
                serverProtos = (JsonObject)protos["server"];
                clientProtos = (JsonObject)protos["client"];
            }

            messageProtocol = new MessageProtocol (dict, serverProtos, clientProtos);

            //Init heartbeat service
            int interval = 0;
            if(sys.ContainsKey("heartbeat")) interval = Convert.ToInt32(sys["heartbeat"]);
            heartBeatService = new HeartBeatService(interval, this);

            if(interval > 0){
                heartBeatService.start();
            }

            //send ack and change protocol state
            handshake.ack();
            this.state = ProtocolState.working;

            //Invoke handshake callback
            JsonObject user = new JsonObject();
            if(msg.ContainsKey("user")) user = (JsonObject)msg["user"];
            handshake.invokeCallback(user);
        }
Esempio n. 58
0
        public void TestIpBanModifiedAndIpBanInserted()
        {
            var state = new ProtocolState();

            state.Bans.TryAdd("Permanent/Ip/1", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Permanent
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Ip = "1",
                            Score = 1
                        }
                    }
                }
            });

            var segment = new ProtocolStateSegment() {
                Bans = new ConcurrentDictionary<String, BanModel>()
            };
            segment.Bans.TryAdd("Permanent/Ip/1", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Permanent
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Ip = "1",
                            Score = 3
                        }
                    }
                }
            });
            segment.Bans.TryAdd("Permanent/Ip/2", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Permanent
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Ip = "2",
                            Score = 4
                        }
                    }
                }
            });

            state.Modified(segment);

            Assert.AreEqual(2, state.Bans.Count);
            Assert.AreEqual(3, state.Bans.First(ban => ban.Key == "Permanent/Ip/1").Value.Scope.Players.First().Score);
            Assert.AreEqual(4, state.Bans.Last(ban => ban.Key == "Permanent/Ip/2").Value.Scope.Players.First().Score);
        }
Esempio n. 59
0
        public void TestSingleNameBansSet()
        {
            var state = new ProtocolState();

            state.Bans.TryAdd("Permanent/Name/1", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Permanent
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Name = "1",
                            Score = 1
                        }
                    }
                }
            });
            state.Bans.TryAdd("Time/Name/2", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Time
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Name = "2",
                            Score = 2
                        }
                    }
                }
            });

            var segment = new ProtocolStateSegment() {
                Bans = new ConcurrentDictionary<String, BanModel>()
            };
            // Technically it would have an incorrect key, so next sync it would be
            // removed because it does not exist..
            segment.Bans.TryAdd("Permanent/Name/1", new BanModel() {
                Scope = {
                    Times = {
                        new TimeSubsetModel() {
                            Context = TimeSubsetContext.Time
                        }
                    },
                    Players = new List<PlayerModel>() {
                        new PlayerModel() {
                            Name = "1",
                            Score = 1
                        }
                    }
                }
            });

            state.Set(segment);

            Assert.AreEqual(1, state.Bans.Count);
            Assert.AreEqual(TimeSubsetContext.Time, state.Bans.First().Value.Scope.Times.First().Context);
        }
Esempio n. 60
0
        public void TestSingleGroupPoolRemoved()
        {
            var state = new ProtocolState();

            state.Groups.TryAdd("Team/1", new GroupModel() {
                Uid = "1",
                Type = GroupModel.Team,
                FriendlyName = "Boring Group 1"
            });
            state.Groups.TryAdd("Team/2", new GroupModel() {
                Uid = "2",
                Type = GroupModel.Team,
                FriendlyName = "Boring Group 2"
            });

            var segment = new ProtocolStateSegment() {
                Groups = new ConcurrentDictionary<String, GroupModel>()
            };
            segment.Groups.TryAdd("Team/1", new GroupModel() {
                Uid = "1",
                Type = GroupModel.Team,
                FriendlyName = "Boring Group 1"
            });

            state.Removed(segment);

            Assert.AreEqual(1, state.Groups.Count);
            Assert.AreEqual("Boring Group 2", state.Groups.First().Value.FriendlyName);
        }