using System.IO.Ports;
using System.Text;
namespace RGBController2.Boards
{
///
/// ArduinoBoard used for communicating with a sigle Arduino device.
///
public class ArduinoBoard : IBoard
{
///
/// True is communication has been established with the Arduino, false otherwise.
///
public bool Connected { get; }
///
/// The serial port object for communicating with the Arduino.
///
private SerialPort _serialPort;
///
/// Constructs an ArduinoBoard object for controlling the Arduino.
///
/// The COM port name of the arduino.
/// The baud rate at which to communicate with the arduion. Default 9600.
public ArduinoBoard(string portName, int baudRate = 9600)
{
Connected = false;
_serialPort = new SerialPort();
_serialPort.PortName = portName;
_serialPort.BaudRate = baudRate;
_serialPort.Open();
if (_serialPort.IsOpen)
Connected = true;
}
///
/// Sets all of the LEDs to the chosen RGB colour.
///
/// The red value
/// The green value
/// The blue value
public void SetAllLeds(byte red, byte green, byte blue)
{
string command = "a";
command += ByteToHexString(red);
command += ByteToHexString(green);
command += ByteToHexString(blue);
command += ';';
_serialPort.WriteLine(command);
}
///
/// Turns off all of the LEDs connected to the board.
///
public void TurnOffAllLeds()
{
string command = "a000000;";
_serialPort.WriteLine(command);
}
///
/// Helper function to convert as byte to a hex string used by the arduino.
/// e.g: 255 would become FF
///
/// The byte to be converted.
///
private static string ByteToHexString(byte b)
{
StringBuilder hex = new StringBuilder(2);
hex.AppendFormat("{0:x2}", b);
return hex.ToString();
}
}
}