Esempio n. 1
0
        private void HandleChatCommand(CmdId cmd, ChatInfo data)
        {
            if (cmd != CmdId.Event_ChatMessage)
            {
                return;
            }

            if (!playerSteamIds.ContainsKey(data.playerId))
            {
                new APIResult <PlayerInfo>().From(new Id(data.playerId)).OnResponse(x =>
                {
                    playerSteamIds[data.playerId] = x.steamId;
                    HandleChatCommand(cmd, data);
                }).Execute();
                return;
            }

            var steamId = playerSteamIds[data.playerId];

            if (!elevated.Contains(steamId))
            {
                return;
            }

            var action = getAction(data.msg);

            action(data);
        }
Esempio n. 2
0
 public void Handle_Game_Event(CmdId evt, ushort seqNr, object data)
 {
     modDict.Values.Where(x => x.isActive).ToList().ForEach(x => {
         log(() => $"sending msg {seqNr} to {x.title}");
         x.mod.Game_Event(evt, seqNr, data);
     });
 }
Esempio n. 3
0
 public APIRequest(CmdId cmdId, Type paramType, CmdId responseCmdId, APIFeatureState featureState = APIFeatureState.Untested)
 {
     CmdId         = cmdId;
     ParamType     = paramType;
     ResponseCmdId = responseCmdId;
     FeatureState  = featureState;
 }
Esempio n. 4
0
    void ModInterface.Game_Event(CmdId eventId, ushort seqNr, object data)
    {
      Broker.HandleGameEvent(eventId, seqNr, data);
      if (eventId == CmdId.Event_ChatMessage) SimpleMod_ProcessChatCommands((ChatInfo)data);

      API_Message_Received?.Invoke(eventId, seqNr, data);
    }
 public Package(CmdId cmdId, int nClientId, ushort nSeqNr, object nData)
 {
     cmd      = cmdId;
     clientId = nClientId;
     seqNr    = nSeqNr;
     data     = nData;
 }
Esempio n. 6
0
                public override int GetHashCode()
                {
                    int hash = 1;

                    if (Type != 0)
                    {
                        hash ^= Type.GetHashCode();
                    }
                    if (Version != 0)
                    {
                        hash ^= Version.GetHashCode();
                    }
                    if (CmdId != 0)
                    {
                        hash ^= CmdId.GetHashCode();
                    }
                    if (UserId != 0UL)
                    {
                        hash ^= UserId.GetHashCode();
                    }
                    if (Reserved != 0)
                    {
                        hash ^= Reserved.GetHashCode();
                    }
                    if (Message.Length != 0)
                    {
                        hash ^= Message.GetHashCode();
                    }
                    return(hash);
                }
    public void Game_Event(CmdId eventId, ushort seqNr, object data)
    {
        broker.HandleMessage(eventId, seqNr, data);

        if (settlementOperations.ContainsKey(seqNr))
        {
            var op = settlementOperations[seqNr];
            HandleSettlementWokflowEvent(GameAPI, op, eventId, data);
        }

        GameAPI.Console_Write($"ID:EVENT! {eventId} - {seqNr}");
        try
        {
            switch (eventId)
            {
            case CmdId.Event_Playfield_Stats:
                var playfieldData = (PlayfieldStats)data;
                var pstatstring   = $"id: {Serializer.Serialize(playfieldData)}";
                GameAPI.Console_Write(pstatstring);
                break;

            case CmdId.Event_Player_Connected:
                GameAPI.Game_Request(CmdId.Request_Player_Info, (ushort)CmdId.Request_Player_Info, (Id)data);
                break;

            case CmdId.Event_Statistics:

                StatisticsParam stats = (StatisticsParam)data;
                Handle_event_statistics(stats);
                break;

            case CmdId.Event_ChatMessage:
                ChatInfo ci = (ChatInfo)data;
                Handle_chat_message(ci);
                break;

            case CmdId.Event_GlobalStructure_List:
                GlobalStructureList info = (GlobalStructureList)data;
                writeGlobalStructureList(info);
                break;

            default:
                GameAPI.Console_Write($"event: {eventId}");
                var outmessage = "NO DATA";
                if (data != null)
                {
                    outmessage = "data: " + data.ToString();
                }
                GameAPI.Console_Write(outmessage);

                break;
            }
        }
        catch (Exception ex)
        {
            GameAPI.Console_Write(ex.Message);
            GameAPI.Console_Write(ex.ToString());
        }
    }
        private T SyncRequest <T>(CmdId reqCmdId, CmdId resCmdId, object data)
        {
            Handle handle = new Handle();

            lock (_handles)
            {
                bool passedZero = false;
                do
                {
                    if (_sequenceNumber == 0)
                    {
                        // Sequence Number 0 is reserved for Game Events
                        _sequenceNumber = 1;
                        // This avoids the rare scenario that we have somehow
                        // simultainiously used up all 65534 available sequence
                        // numbers. If we pass Zero twice insize a lock.. fsck it.
                        if (passedZero)
                        {
                            throw new Exception("Ran out of Available Sequence Numbers");
                        }
                        else
                        {
                            passedZero = true;
                        }
                    }
                    else
                    {
                        // Increment until we find an unused SequenceNumber
                        _sequenceNumber += 1;
                    }
                } while (_handles.ContainsKey(_sequenceNumber));
                handle._sequenceNumber = _sequenceNumber;
                _handles.Add(_sequenceNumber, handle);
            }

            lock (handle)
            {
                _modGameApi.Game_Request(reqCmdId, handle._sequenceNumber, data);
                Monitor.Wait(handle);
            }

            lock (_handles)
            {
                _handles.Remove(handle._sequenceNumber);
            }

            if (handle._resCmdId == CmdId.Event_Error)
            {
                ErrorInfo errorInfo = (ErrorInfo)handle._responseData;
                throw new Exception("Error Invoking Game Request: " + Enum.GetName(typeof(ErrorType), errorInfo.errorType));
            }

            if (handle._resCmdId != resCmdId)
            {
                throw new Exception("Expected CmdId: " + Enum.GetName(typeof(CmdId), resCmdId)
                                    + " Found CmdId: " + Enum.GetName(typeof(CmdId), handle._resCmdId));
            }
            return((T)handle._responseData);
        }
 public void HandleMessage(CmdId eventType, object data)
 {
     if (!(eventType == CmdId.Event_ChatMessage))
     {
         return;
     }
     Handle_chat_message((ChatInfo)data);
 }
Esempio n. 10
0
 public GenericAPICommand(CmdId cmdId, object argument, Action <CmdId, object> responseHandler = null, Action <ErrorInfo> errorHandler = null, bool validate = false)
 {
     this.call            = APIManifest.APIRequestTable[cmdId];
     this.argument        = argument;
     this.responseHandler = responseHandler ?? defaultResponseHandler;
     this.errorHandler    = errorHandler ?? defaultErrorHandler;
     this.validated       = validate ? validateArguments(this.call, this.argument, this.responseHandler) : validate;
 }
Esempio n. 11
0
 public bool Game_Request(CmdId reqId, ushort seqNr, object data)
 {
     if (this.GameRequestReceived != null)
     {
         this.GameRequestReceived(this, new GameRequestEventArgs(reqId, seqNr, data));
     }
     return(true);
 }
Esempio n. 12
0
        public static TypeMatchValidator getResponseValidatorForRequest(CmdId requestId)
        {
            var request   = APIRequestTable[requestId];
            var response  = APIRequestResponseTable[requestId];
            var validator = validators.FirstOrDefault(x => x.ParamType == request.ParamType && x.DataType == response.ParamType);

            return(validator);
        }
 void ModInterface.Game_Event(CmdId eventId, ushort seqNr, object data)
 {
     Broker.HandleGameEvent(eventId, seqNr, data);
     if (eventId == CmdId.Event_ChatMessage)
     {
         HandleChatCommand(eventId, (ChatInfo)data);
     }
     modManager.Handle_Game_Event(eventId, seqNr, data);
 }
Esempio n. 14
0
 public bool Game_Request(CmdId reqId, ushort seqNr, object data)
 {
     Console.WriteLine($"Game_Request:{reqId}#{seqNr} = {data}");
     ToEmpyrion.SendMessage(new EmpyrionGameEventData()
     {
         eventId = reqId, seqNr = seqNr, data = data
     });
     return(true);
 }
Esempio n. 15
0
        /// <summary>
        /// 获得命令描述
        /// </summary>
        /// <param name="cmdId"></param>
        /// <returns></returns>
        public static string GetCmdDesc(CmdId cmdId)
        {
            string cmdDesc;

            if (CmdDesc.TryGetValue(cmdId, out cmdDesc))
            {
                return(cmdDesc);
            }
            return("");
        }
Esempio n. 16
0
 /// <summary>
 /// Events from Empyrion that have already been determined to be destined for this mod are passed to this method. Each event CmdId has a queue of callback delegates waiting for a
 /// response. The delegate that is next in line is dequeued and given the event data.
 /// </summary>
 /// <param name="cmd">The event CmdId received from Empyrion.</param>
 /// <param name="data">A data object received with the event. The callback delegate will need to cast it to the type associated with the event.</param>
 public void DispatchEvent(CmdId cmd, object data)
 {
     if (callbacks.ContainsKey(cmd))
     {
         Delegate callback = callbacks[cmd].Dequeue();
         if (callback != null)
         {
             callback.DynamicInvoke(data);
         }
     }
 }
Esempio n. 17
0
        public async Task <TResult> SendRequestAsync <TResult>(CmdId cmdID, CancellationToken ct = default(CancellationToken))
            where TResult : class, new()
        {
            ct.ThrowIfCancellationRequested();

            var result = await _requestTracker.GetNewTaskCompletionSourceAsync <TResult>(ct);

            api.Game_Request(cmdID, result.Item1, null);

            return(await result.Item2);
        }
    public void HandleMessage(CmdId eventId, ushort seqNr, object data)
    {
        if (!actionTracker.ContainsKey(seqNr))
        {
            return;
        }
        var action = actionTracker[seqNr];

        action(eventId, data);
        deprovisionSequenceNumber(seqNr);
    }
Esempio n. 19
0
        public string CommandString()
        {
            var commandString = CmdId.ToString(CultureInfo.InvariantCulture);

            foreach (var argument in Arguments)
            {
                commandString += FieldSeparator + argument;
            }
            commandString += CommandSeparator;
            return(commandString);
        }
Esempio n. 20
0
        public void Send(CmdId cmdId, ushort seqNr, object data)
        {
            //ClientMessages("Sending request event: c=" + cmdId + " sNr=" + seqNr + " d=" + data + " client="+client);
            // Send events of the network
            ModProtocol c = client;

            if (c != null)
            {
                ModProtocol.Package p = new ModProtocol.Package(cmdId, clientId, seqNr, data);
                c.AddToSendQueue(p);
            }
        }
Esempio n. 21
0
        public bool Game_Request(CmdId reqId, ushort seqNr, object data)
        {
            //Console.WriteLine($"Game_Request:{reqId}#{seqNr} = {data}");
            var msg = new EmpyrionGameEventData()
            {
                eventId = reqId, seqNr = seqNr
            };

            msg.SetEmpyrionObject(data);
            ToEmpyrion.SendMessage(msg);
            return(true);
        }
Esempio n. 22
0
        public bool HandleGameEvent(CmdId eventId, ushort seqNr, object data)
        {
            if (eventTable.TryGetValue(eventId, out Delegate handler))
            {
                try
                {
                    handler.DynamicInvoke(new object[] { data });
                }
                catch (Exception Error)
                {
                    Log($"HandleGameEvent: CmdId:{eventId} seqNr:{seqNr} data:{data} => {Error}");
                }
            }

            return(_requestTracker.TryHandleEvent(eventId, seqNr, data));
        }
Esempio n. 23
0
        public static void HandleGameEvent(CmdId eventId, ushort seqNr, object data)
        {
            var apiEvent = new apiEvent(eventId, seqNr, data);

            log(() => $"receiving event {eventId.ToString()}:{seqNr}");

            Delegate handler;

            if (eventTable.TryGetValue(eventId, out handler))
            {
                handler.DynamicInvoke(new object[] { data });
            }


            if (!commandTracker.ContainsKey(seqNr))
            {
                return;
            }

            var outstandingRequestList = commandTracker[seqNr];

            var firstApplicableRequest = outstandingRequestList.FirstOrDefault(x => x.call.ResponseCmdId == eventId || eventId == CmdId.Event_Error);

            if (firstApplicableRequest == null)
            {
                return;
            }

            outstandingRequestList.Remove(firstApplicableRequest);

            if (outstandingRequestList.Count > 0)
            {
                commandTracker[seqNr] = outstandingRequestList;
            }
            else
            {
                commandTracker.Remove(seqNr);
            }

            if (eventId == CmdId.Event_Error && firstApplicableRequest.errorHandler != null)
            {
                firstApplicableRequest.errorHandler((ErrorInfo)data);
                return;
            }

            firstApplicableRequest.responseHandler(eventId, data);
        }
Esempio n. 24
0
 public void ProcessResponseData(CmdId eventId, ushort seqId, object responseData)
 {
     if (_handles.ContainsKey(seqId))
     {
         Handle handle = _handles[seqId];
         lock (handle)
         {
             handle._resCmdId     = eventId;
             handle._responseData = responseData;
             Monitor.PulseAll(handle);
         }
     }
     else
     {
         LogMessage("Error: Received Response Data for missing Handle");
     }
 }
Esempio n. 25
0
        public string CommandString()
        {
            if (CommunicationManager == null)
            {
                throw new InvalidOperationException("CommunicationManager was not set for command.");
            }

            var commandString = new StringBuilder(CmdId.ToString(CultureInfo.InvariantCulture));

            foreach (var argument in Arguments)
            {
                commandString.Append(CommunicationManager.FieldSeparator).Append(argument);
            }
            commandString.Append(CommunicationManager.CommandSeparator);

            return(commandString.ToString());
        }
Esempio n. 26
0
        /// <summary>
        /// Enqueues a callback delegate for a specific CmdId.
        /// </summary>
        /// <param name="cmd">The event CmdId that is expected to be received from Empyrion.</param>
        /// <param name="callback">A callback delegate that will receive the data from the event. Data will be an object that must be cast into the data type associated with the event.</param>
        private void AddCallback(CmdId cmd, Delegate callback)
        {
            if (EmpyrionExtension.LegacyApi == null)
            {
                // LegacyApi is not availble so a response will never arrive.
                // This means the process is not owned by a dedicated server.
                callback.DynamicInvoke(null);
            }
            else
            {
                if (!callbacks.ContainsKey(cmd))
                {
                    callbacks[cmd] = new Queue <Delegate>();
                }

                callbacks[cmd].Enqueue(callback);
            }
        }
Esempio n. 27
0
 public void Game_Event(CmdId eventId, ushort seqNr, object data)
 {
     try
     {
         if (mSingleModInstance != null)
         {
             mSingleModInstance.Game_Event(eventId, seqNr, data);
         }
         else
         {
             mModInstance.ForEach(M => ThreadPool.QueueUserWorkItem(SubM => { ((ModInterface)SubM).Game_Event(eventId, seqNr, data); }));
         }
     }
     catch (Exception Error)
     {
         mGameAPI.Console_Write($"Game_Event(Error): {Error}");
     }
 }
Esempio n. 28
0
        /// <summary>
        /// 获得命令字节数组
        /// </summary>
        /// <param name="cmdId"></param>
        /// <returns></returns>
        public static byte[] GetCmdBytes(CmdId cmdId)
        {
            string cmdStr;

            if (CmdString.TryGetValue(cmdId, out cmdStr))
            {
                byte[] buffer;
                if (!_cmdBytes.TryGetValue(cmdId, out buffer))
                {
                    buffer           = Encoding.ASCII.GetBytes(cmdStr);
                    _cmdBytes[cmdId] = buffer;
                }
                return(buffer);
            }
            else
            {
                return(null);
            }
        }
Esempio n. 29
0
        public static void HandleGameEvent(CmdId eventId, ushort seqNr, object data)
        {
            var apiEvent = new apiEvent(eventId, seqNr, data);

            Delegate handler;

            if (eventTable.TryGetValue(eventId, out handler))
            {
                handler.DynamicInvoke(new object[] { data });
            }

            var seqNrString = seqNr.ToString();

            if (!commandTracker.Contains(seqNrString))
            {
                return;
            }

            GenericAPICommand outstandingCommand = default(GenericAPICommand);

            lock (commandTracker)
            {
                outstandingCommand = (GenericAPICommand)commandTracker.Get(seqNrString);
                if (eventId == CmdId.Event_Error || outstandingCommand.validateResponse(eventId, seqNr, data))
                {
                    commandTracker.Remove(seqNrString);
                }
                else
                {
                    return;
                }
            }
            if (eventId == CmdId.Event_Error && outstandingCommand.errorHandler != null)
            {
                outstandingCommand.errorHandler((ErrorInfo)data);
            }
            else
            {
                outstandingCommand.responseHandler(eventId, data);
            }
        }
        public void Game_Event(CmdId eventId, ushort seqNr, object data)
        {
            if (OutServer == null)
            {
                return;
            }

            try
            {
                var msg = new EmpyrionGameEventData()
                {
                    eventId = eventId, seqNr = seqNr
                };
                msg.SetEmpyrionObject(data);
                OutServer.SendMessage(msg);
            }
            catch (System.Exception Error)
            {
                GameAPI.Console_Write($"ModClientDll: {Error.Message}");
            }
        }
Esempio n. 31
0
 public static extern bool BRCommandFetchAvatarDataFromServer(IntPtr sockRef, int avatarIndex, CmdId cmdId);
Esempio n. 32
0
 public static extern bool BRUnregisterAutoSyncParmeter(IntPtr sockRef, CmdId cmdId);
Esempio n. 33
0
 public static extern bool BRCommandFetchDataFromServer(IntPtr sockRef, CmdId cmdId);
Esempio n. 34
0
 static CommandID MakeCmd(CmdId id)
 {
     return new CommandID(guidNemerleProjectCmdSet, (int)id);
 }