SkyPumpConnection.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Collections.Generic;
  2. using System.IO.Ports;
  3. using System.Linq;
  4. using System.Text;
  5. using Aitex.Core.RT.Log;
  6. using MECF.Framework.Common.Communications;
  7. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Pumps.SkyPump
  8. {
  9. public class SkyPumpMessage : AsciiMessage
  10. {
  11. public string Data { get; set; }
  12. public string Address { get; set; }
  13. }
  14. public class SkyPumpConnection : SerialPortConnectionBase
  15. {
  16. private static string _endLine = "\r\n";
  17. private string _cachedBuffer = string.Empty;
  18. public SkyPumpConnection(string portName, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One)
  19. : base(portName, baudRate, dataBits, parity, stopBits, _endLine, true)
  20. {
  21. }
  22. public override bool SendMessage(string message)
  23. {
  24. return base.SendMessage(message);
  25. }
  26. protected override MessageBase ParseResponse(string rawText)
  27. {
  28. SkyPumpMessage msg = new SkyPumpMessage();
  29. msg.RawMessage = rawText;
  30. if (rawText.Length <= 0)
  31. {
  32. LOG.Error($"empty response,");
  33. msg.IsFormatError = true;
  34. return msg;
  35. }
  36. if (rawText.Length <= 4)
  37. {
  38. LOG.Error($"too short response,");
  39. msg.IsFormatError = true;
  40. return msg;
  41. }
  42. rawText = rawText.Substring(1, rawText.Length - 4);//remove start char and end char
  43. msg.Address = rawText.Substring(0,2);
  44. msg.Data = rawText.Substring(2);
  45. msg.IsResponse = true;
  46. msg.IsAck = true;
  47. return msg;
  48. }
  49. private bool CheckSum(string responseContent)
  50. {
  51. string responseSum = responseContent.Substring(responseContent.Length - 2);
  52. string checkContent = responseContent.Substring(0, responseContent.Length - 2);
  53. var charArray = checkContent.ToArray();
  54. int sum = charArray.Sum(chr => (int)chr);
  55. string sSum = sum.ToString("X");
  56. if (sSum.Length < 2)
  57. sSum = "0" + sSum;
  58. else
  59. sSum = sSum.Substring(sSum.Length - 2);
  60. return responseSum == sSum;
  61. }
  62. }
  63. }