2016-10-16 16:26:13 +00:00
|
|
|
|
using System;
|
|
|
|
|
using System.Net.Sockets;
|
|
|
|
|
using System.Threading.Tasks;
|
|
|
|
|
using System.IO;
|
|
|
|
|
|
|
|
|
|
namespace PixelHub.Server
|
|
|
|
|
{
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Provides an interface through which you can communicate with and control a Hull PixelBot.
|
|
|
|
|
/// </summary>
|
|
|
|
|
public class PixelBot
|
|
|
|
|
{
|
|
|
|
|
public bool Connected { get; private set; } = false;
|
|
|
|
|
TcpClient client;
|
|
|
|
|
|
|
|
|
|
StreamReader incoming;
|
|
|
|
|
StreamWriter outgoing;
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
2016-11-20 21:51:31 +00:00
|
|
|
|
/// Initializes a new <see cref="PixelBot"/> instance and connects it to a Hull Pixelbot.
|
2016-10-16 16:26:13 +00:00
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="inClient">The Tcp connection between the PixelHub server and the Hull PixelBot.</param>
|
|
|
|
|
public PixelBot(TcpClient inClient)
|
|
|
|
|
{
|
|
|
|
|
client = inClient;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Starts listening for and handling messages that come from the remote PixelBot.
|
|
|
|
|
/// </summary>
|
2016-10-20 16:52:39 +00:00
|
|
|
|
public async Task Handle()
|
2016-10-16 16:26:13 +00:00
|
|
|
|
{
|
|
|
|
|
if (Connected)
|
|
|
|
|
throw new InvalidOperationException("Only one connection handling loop can be active at once!");
|
|
|
|
|
|
|
|
|
|
Connected = true;
|
|
|
|
|
|
|
|
|
|
incoming = new StreamReader(client.GetStream());
|
|
|
|
|
outgoing = new StreamWriter(client.GetStream()) { AutoFlush = true };
|
|
|
|
|
|
2016-11-20 21:51:31 +00:00
|
|
|
|
outgoing.WriteLine("Test message!");
|
|
|
|
|
|
2016-10-16 16:26:13 +00:00
|
|
|
|
string nextLine;
|
|
|
|
|
while((nextLine = await incoming.ReadLineAsync()) != null)
|
|
|
|
|
{
|
|
|
|
|
Console.WriteLine("Got message from client: '{0}'", nextLine.Trim());
|
|
|
|
|
}
|
|
|
|
|
|
2016-11-20 21:51:31 +00:00
|
|
|
|
|
2016-10-16 16:26:13 +00:00
|
|
|
|
Connected = false;
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
/// <summary>
|
|
|
|
|
/// Sends the given command to the remote PixelBot.
|
|
|
|
|
/// </summary>
|
|
|
|
|
/// <param name="command">The command to send.</param>
|
2017-03-04 12:43:46 +00:00
|
|
|
|
public async Task Send(PixelMessage command)
|
2016-10-16 16:26:13 +00:00
|
|
|
|
{
|
2017-02-26 20:08:25 +00:00
|
|
|
|
byte[] message = command.AsCompiledCommand();
|
|
|
|
|
await client.GetStream().WriteAsync(message, 0, message.Length);
|
|
|
|
|
await client.GetStream().FlushAsync();
|
2016-10-16 16:26:13 +00:00
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|