public void SearchForCommands(List <byte> incomingBuffer, ICommandPartFoundListener listener) { for (int i = 0; i < incomingBuffer.Count; ++i) { for (int x = 0; x < _cmdPartsCount; ++x) { var commandPart = _cmdPartConfigs[x]; if (incomingBuffer.Count - i >= commandPart.Length) { try { var confirmation = _commandPartSearcher.IsHereCmdPart(incomingBuffer.ToArray(), i, commandPart); // TODO: IS NOT SO FAST CAUSE OF ARRAY if (confirmation == PsnCommandPartConfirmation.EverythyngIsOk) { var commandPartBytes = incomingBuffer.Skip(i).Take(commandPart.Length).ToArray(); //var commandPartBytes = new List<byte>(); //commandPartBytes.AddRange(incomingBuffer.Skip(i).Take(commandPart.Length)); // clean buffer bytes before command and command's bytes: int removeBytesCount = i + commandPart.Length; incomingBuffer.RemoveRange(0, removeBytesCount); i = -1; // because the next cycle iteration will increase i by 1 and "i" will be zero listener.CommandPartFound(new CommandPartSimple((byte)commandPart.Address.DefinedValue, (byte)commandPart.CommandCode.DefinedValue, commandPartBytes, commandPart)); break; } } catch { } } } } }
private void RunThroughDataAndExectueCustomActionOnCommandPartsFound( IPsnProtocolCommandPartConfiguration[] commandParts, byte[] dataBytes, Func <IPsnCommandPartsPosition, int> maybeCmdPartFoundAction) { int zeroBasedCurrentByte = 0; try { var maxCmdLenInProtocol = commandParts.Max(cp => cp.Length); // TODO: Replace LINQ for perfomance while (true) { var remainingLength = dataBytes.Length - zeroBasedCurrentByte - 1; // WHY? - To gain perfomance IPsnProtocolCommandPartConfiguration[] commandPartsThatCouldBeInRemainingBytes; if (remainingLength < maxCmdLenInProtocol) { commandPartsThatCouldBeInRemainingBytes = commandParts.Where(cp => cp.Length <= remainingLength) .ToArray(); // TODO: Replace LINQ for perfomance if (commandPartsThatCouldBeInRemainingBytes.Length == 0) { break; // выход из цикла, если нет комманд, укалыдвающихся в оставшуюся длину потока данных } } else { commandPartsThatCouldBeInRemainingBytes = commandParts; } int iterationBytesCount = 1; for (int i = 0; i < commandPartsThatCouldBeInRemainingBytes.Length; ++i) { var commandPartThatCouldBeInRemainingBytes = commandPartsThatCouldBeInRemainingBytes[i]; var isHereCmdPartResult = _cmdPartSearcher.IsHereCmdPart(dataBytes, zeroBasedCurrentByte, commandPartThatCouldBeInRemainingBytes); if (isHereCmdPartResult == PsnCommandPartConfirmation.EverythyngIsOk) { iterationBytesCount = maybeCmdPartFoundAction.Invoke(new PsnCommandPartsAndPosition( zeroBasedCurrentByte, commandPartThatCouldBeInRemainingBytes)); break; } } zeroBasedCurrentByte += iterationBytesCount; } } catch (Exception ex) { throw new Exception("Ошибка при сканировании лога на наличие команд", ex); } Console.WriteLine("RunThroughDataAndExectueCustomActionOnCommandPartsFound complete"); }