LightHelper.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. using System;
  2. using System.IO.Ports;
  3. using System.Text;
  4. namespace Team.Communicate
  5. {
  6. public class LightHelper
  7. {
  8. private SerialPort _serialPort;
  9. public string PortName { get; private set; }
  10. public void Init(string name)
  11. {
  12. _serialPort = new SerialPort
  13. {
  14. BaudRate = 9600,
  15. PortName = name
  16. };
  17. _serialPort.DataReceived += _serialPort_DataReceived;
  18. }
  19. private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
  20. {
  21. }
  22. public void OpenPort()
  23. {
  24. if (_serialPort.IsOpen)
  25. {
  26. return;
  27. }
  28. _serialPort.Open();
  29. }
  30. //public bool GetLightStatus(int port)
  31. //{
  32. //}
  33. public void SetLightValue(int port,int value)
  34. {
  35. var valueContent = value.ToString("X");
  36. if (valueContent.Length == 2)
  37. {
  38. valueContent = "0" + valueContent;
  39. }
  40. var sendValue = $"$3{port}{valueContent}";
  41. var bytes = Encoding.ASCII.GetBytes(sendValue);
  42. byte ret = 0;
  43. for (int i = 0; i < bytes.Length; i++)
  44. {
  45. if (i == 0)
  46. {
  47. ret = bytes[0];
  48. continue;
  49. }
  50. ret ^= bytes[i];
  51. }
  52. var end = ret.ToString("X");
  53. sendValue += end;
  54. _serialPort.Write(sendValue);
  55. }
  56. public void OpenLight(int port)
  57. {
  58. var s = $"$1{port}064";
  59. var bytes = Encoding.ASCII.GetBytes(s);
  60. byte ret = 0;
  61. for (int i = 0; i < bytes.Length; i++)
  62. {
  63. if (i == 0)
  64. {
  65. ret = bytes[0];
  66. continue;
  67. }
  68. ret ^= bytes[i];
  69. }
  70. var end = ret.ToString("X");
  71. _serialPort.Write(s + end);
  72. }
  73. public void CloseLight(int port)
  74. {
  75. var s = $"$2{port}029";
  76. var bytes = Encoding.ASCII.GetBytes(s);
  77. byte ret = 0;
  78. for (int i = 0; i < bytes.Length; i++)
  79. {
  80. if (i == 0)
  81. {
  82. ret = bytes[0];
  83. continue;
  84. }
  85. ret ^= bytes[i];
  86. }
  87. var end = ret.ToString("X");
  88. _serialPort.Write(s + end);
  89. }
  90. }
  91. }