using PlantBox.Shared.Communication.Commands;
using System;
using System.Collections.Generic;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace PlantBox.Shared.Communication
{
///
/// Wrap a to send easily, see Wiki > Protocol
///
public class CommandStream : IDisposable
{
private NetworkStream _stream;
///
/// Create a new
///
/// A connected and valid
public CommandStream(NetworkStream networkStream)
{
_stream = networkStream;
}
///
/// Release resources associated with the underlying stream
///
public void Dispose()
{
_stream.Dispose();
}
///
/// Read a from the stream
///
///
public CommandPacket Receive()
{
// Length
byte[] buffer = new byte[4];
_stream.Read(buffer, 0, buffer.Length);
int length = BitConverter.ToInt32(buffer, 0);
// Data
buffer = new byte[length];
_stream.Read(buffer, 0, buffer.Length);
string[] packet = Encoding.UTF8.GetString(buffer).Split('\n');
if (!Enum.TryParse(packet[0], true, out Command command))
{
command = Command.Invalid;
}
return new CommandPacket(command, packet[1].Split(';'));
}
///
/// Read a from the stream and deserialize data to a
///
/// A valid
///
public (CommandPacket, T) Receive() where T : CommandSerializable, new()
{
var packet = Receive();
return (packet, new T().Deserialize(packet.Arguments));
}
///
/// Read a from the stream asynchronously
///
///
public async Task ReceiveAsync()
{
// Length
byte[] buffer = new byte[4];
await _stream.ReadAsync(buffer, 0, buffer.Length);
int length = BitConverter.ToInt32(buffer, 0);
// Data
buffer = new byte[length];
await _stream.ReadAsync(buffer, 0, buffer.Length);
string[] packet = Encoding.UTF8.GetString(buffer).Split('\n');
if (!Enum.TryParse(packet[0], true, out Command command))
{
command = Command.Invalid;
}
return new CommandPacket(command, packet[1].Split(';'));
}
///
/// Read a from the stream and deserialize data to a asynchronously
///
/// A valid
///
public async Task<(CommandPacket, T)> ReceiveAsync() where T : CommandSerializable, new()
{
var packet = await ReceiveAsync();
return (packet, new T().Deserialize(packet.Arguments));
}
///
/// Write a in the stream
///
///
public void Send(CommandPacket command)
{
string packet = command.ToString();
byte[] data = Encoding.UTF8.GetBytes(packet);
_stream.Write(BitConverter.GetBytes(data.Length), 0, 4);
_stream.Write(data, 0, data.Length);
}
///
/// Write a in the stream asynchronously
///
///
///
public async Task SendAsync(CommandPacket command)
{
string packet = command.ToString();
byte[] data = Encoding.UTF8.GetBytes(packet);
await _stream.WriteAsync(BitConverter.GetBytes(data.Length), 0, 4);
await _stream.WriteAsync(data, 0, data.Length);
}
}
}