using System.IO.Ports;
namespace crusherScanner
{
///
/// For sending data to Prepmaster via serial.
/// nb; The concept here is to NOT hold the serial port open.
///
internal class SerialAccess
{
private static bool SerialReady = false;
private static SerialPort? _serialPort;
///
/// Send sample ID to the serial port for Prepmaster to receive.
///
/// The sample ID to send.
public static void SendToPrepmaster(string barcode)
{
if (barcode != "" && !Properties.Settings.Default.PrepmasterConnection)
{
MessageBox.Show($"The crusher flap would\nhave just opened to\naccept sample {barcode}", "Crusher Input");
}
else if (barcode != "")
{
if (!SerialReady)
{
SetupSerial();
}
SendSerial(barcode);
}
}
///
/// Setup and test the serial port.
///
private static void SetupSerial()
{
//TODO: use settings for connection
_serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
_serialPort.Handshake = Handshake.None;
try
{
// Opens serial port as a quick test
_serialPort.Open();
}
catch (Exception ex)
{
Logging.Append("Error opening serial port :: " + ex.Message);
MessageBox.Show("Error opening serial port :: " + ex.Message, "Error!");
}
finally
{
_serialPort.Close();
SerialReady = true;
}
}
///
/// Send data to the serial connection.
///
/// The sample ID to send to Prepmaster.
private static void SendSerial(string data)
{
if (_serialPort == null)
{
Logging.Append("Error opening serial port :: _serialPort is null");
MessageBox.Show("Error opening serial port :: Serial device may have been unpluged.", "Error!");
SerialReady = false;
return;
}
// Makes sure serial port is open before trying to write
try
{
if (!_serialPort.IsOpen)
{
_serialPort.Open();
_serialPort.Write(data + "\r\n");
}
}
catch (Exception ex)
{
Logging.Append("Error opening serial port :: " + ex.Message);
MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
}
}
}
}