1 // 2 // Copyright (c) 2010 - 2023 Antmicro 3 // 4 // This file is licensed under the MIT License. 5 // Full license text is available in 'licenses/MIT.txt'. 6 // 7 using System; 8 using System.Collections.Generic; 9 using System.Linq; 10 using System.Text; 11 using Antmicro.Renode.Logging; 12 13 namespace Antmicro.Renode.Peripherals.Network 14 { 15 public class EchoService : IEmulatedNetworkService 16 { EchoService(string host, ushort port, string args)17 public EchoService(string host, ushort port, string args) 18 { 19 Host = host; 20 Port = port; 21 } 22 Dispose()23 public void Dispose() 24 { 25 // intentionally left blank 26 } 27 Disconnect()28 public void Disconnect() 29 { 30 responseBuffer.Clear(); 31 } 32 Receive(int bytes)33 public byte[] Receive(int bytes) 34 { 35 var data = responseBuffer.Take(bytes).ToArray(); 36 responseBuffer.RemoveRange(0, Math.Min(bytes, responseBuffer.Count)); 37 Logger.Log(LogLevel.Info, "Echo: Sending {0} bytes: '{1}' to modem, {2} bytes left after this", 38 bytes, Encoding.ASCII.GetString(data), BytesAvailable); 39 return data.ToArray(); 40 } 41 Send(byte[] data)42 public bool Send(byte[] data) 43 { 44 Logger.Log(LogLevel.Info, "Echo: Received packet of size {0}: '{1}'", 45 data.Length, Encoding.ASCII.GetString(data)); 46 // Add the received data to the response buffer and notify the modem about the received bytes 47 // being available for reading 48 responseBuffer.AddRange(data); 49 BytesReceived?.Invoke(data.Length); 50 return true; 51 } 52 53 public int BytesAvailable => responseBuffer.Count; 54 55 public string Host { get; } 56 public ushort Port { get; } 57 58 public event Action<int> BytesReceived; 59 60 private readonly List<byte> responseBuffer = new List<byte>(); 61 } 62 } 63