SerialAccess.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. using System.IO.Ports;
  2. namespace crusherScanner
  3. {
  4. /// <summary>
  5. /// For sending data to Prepmaster via serial.
  6. /// nb; The concept here is to NOT hold the serial port open.
  7. /// </summary>
  8. internal class SerialAccess
  9. {
  10. private static bool SerialReady = false;
  11. private static SerialPort? _serialPort;
  12. /// <summary>
  13. /// Send sample ID to the serial port for Prepmaster to receive.
  14. /// </summary>
  15. /// <param name="barcode">The sample ID to send.</param>
  16. public static void SendToPrepmaster(string barcode)
  17. {
  18. if (barcode != "" && !Properties.Settings.Default.PrepmasterConnection)
  19. {
  20. MessageBox.Show($"The crusher flap would\nhave just opened to\naccept sample {barcode}", "Crusher Input");
  21. }
  22. else if (barcode != "")
  23. {
  24. if (!SerialReady)
  25. {
  26. SetupSerial();
  27. }
  28. SendSerial(barcode);
  29. }
  30. }
  31. /// <summary>
  32. /// Setup and test the serial port.
  33. /// </summary>
  34. private static void SetupSerial()
  35. {
  36. //TODO: use settings for connection
  37. _serialPort = new SerialPort("COM1", 19200, Parity.None, 8, StopBits.One);
  38. _serialPort.Handshake = Handshake.None;
  39. try
  40. {
  41. // Opens serial port as a quick test
  42. _serialPort.Open();
  43. }
  44. catch (Exception ex)
  45. {
  46. Logging.Append("Error opening serial port :: " + ex.Message);
  47. MessageBox.Show("Error opening serial port :: " + ex.Message, "Error!");
  48. }
  49. finally
  50. {
  51. _serialPort.Close();
  52. SerialReady = true;
  53. }
  54. }
  55. /// <summary>
  56. /// Send data to the serial connection.
  57. /// </summary>
  58. /// <param name="data">The sample ID to send to Prepmaster.</param>
  59. private static void SendSerial(string data)
  60. {
  61. if (_serialPort == null)
  62. {
  63. Logging.Append("Error opening serial port :: _serialPort is null");
  64. MessageBox.Show("Error opening serial port :: Serial device may have been unpluged.", "Error!");
  65. SerialReady = false;
  66. return;
  67. }
  68. // Makes sure serial port is open before trying to write
  69. try
  70. {
  71. if (!_serialPort.IsOpen)
  72. {
  73. _serialPort.Open();
  74. _serialPort.Write(data + "\r\n");
  75. }
  76. }
  77. catch (Exception ex)
  78. {
  79. Logging.Append("Error opening serial port :: " + ex.Message);
  80. MessageBox.Show("Error opening/writing to serial port :: " + ex.Message, "Error!");
  81. }
  82. }
  83. }
  84. }