| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293 |
- using System.IO.Ports;
- namespace crusherScanner
- {
- /// <summary>
- /// For sending data to Prepmaster via serial.
- /// nb; The concept here is to NOT hold the serial port open.
- /// </summary>
- internal class SerialAccess
- {
- private static bool SerialReady = false;
- private static SerialPort? _serialPort;
- /// <summary>
- /// Send sample ID to the serial port for Prepmaster to receive.
- /// </summary>
- /// <param name="barcode">The sample ID to send.</param>
- 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);
- }
- }
- /// <summary>
- /// Setup and test the serial port.
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// Send data to the serial connection.
- /// </summary>
- /// <param name="data">The sample ID to send to Prepmaster.</param>
- 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!");
- }
- }
- }
- }
|