BaecChillerConnection.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. using Aitex.Core.RT.Log;
  2. using MECF.Framework.Common.Communications;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO.Ports;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace MECF.Framework.RT.EquipmentLibrary.HardwareUnits.Chillers.BaecChiller
  10. {
  11. public class RisshiChillerMessage : BinaryMessage
  12. {
  13. public string Command { get; set; }
  14. public string ErrorCode { get; set; }
  15. public byte[] Data { get; set; }
  16. }
  17. //Modbus RTU
  18. public class BaecChillerConnection : SerialPortConnectionBase
  19. {
  20. private List<byte> _msgBuffer = new List<byte>();
  21. public BaecChillerConnection(string portName, int baudRate = 9600, int dataBits = 8, Parity parity = Parity.None, StopBits stopBits = StopBits.One)
  22. : base(portName, baudRate, dataBits, parity, stopBits, "", false)
  23. {
  24. }
  25. public override bool SendMessage(byte[] message)
  26. {
  27. return base.SendMessage(message);
  28. }
  29. protected override MessageBase ParseResponse(byte[] rawMessage)
  30. {
  31. RisshiChillerMessage msg = new RisshiChillerMessage();
  32. if (rawMessage == null || rawMessage.Length < 1)
  33. {
  34. return null;
  35. }
  36. _msgBuffer.AddRange(rawMessage);
  37. if (_msgBuffer.Count < 5)
  38. {
  39. return msg;
  40. }
  41. if (_msgBuffer[1] == 0x03)
  42. {
  43. var dataLength = _msgBuffer[2];
  44. if (_msgBuffer.Count < 3 + dataLength + 2)
  45. {
  46. return msg;
  47. }
  48. else
  49. {
  50. msg.RawMessage = _msgBuffer.Take(3 + dataLength + 2).ToArray();
  51. msg.Data = _msgBuffer.Skip(3).Take(dataLength).ToArray();
  52. _msgBuffer.RemoveRange(0, msg.RawMessage.Length);
  53. msg.IsResponse = true;
  54. msg.IsAck = true;
  55. msg.IsComplete = true;
  56. return msg;
  57. }
  58. }
  59. else if (_msgBuffer[1] == 0x10 || _msgBuffer[1] == 0x06)
  60. {
  61. //SlaveAddress,FunctionCode,StartingAddressHigh,StartingAddressLow,NumberAddressHigh,NumberAddressLow,CRC,CRC
  62. if (_msgBuffer.Count < 8)
  63. {
  64. return msg;
  65. }
  66. else
  67. {
  68. msg.RawMessage = _msgBuffer.Take(8).ToArray();
  69. _msgBuffer.RemoveRange(0, msg.RawMessage.Length);
  70. msg.IsResponse = true;
  71. msg.IsAck = true;
  72. msg.IsComplete = true;
  73. return msg;
  74. }
  75. }
  76. else
  77. {
  78. msg.IsFormatError = true;
  79. LOG.Error($"invalid response");
  80. return msg;
  81. }
  82. }
  83. }
  84. }