ModbusTcpMessage.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace MECF.Framework.RT.Core.IoProviders.Common.IMessage
  6. {
  7. /// <summary>
  8. /// Modbus-Tcp协议支持的消息解析类
  9. /// </summary>
  10. public class ModbusTcpMessage : INetMessage
  11. {
  12. /// <summary>
  13. /// 消息头的指令长度
  14. /// </summary>
  15. public int ProtocolHeadBytesLength
  16. {
  17. get { return 8; }
  18. }
  19. /// <summary>
  20. /// 从当前的头子节文件中提取出接下来需要接收的数据长度
  21. /// </summary>
  22. /// <returns>返回接下来的数据内容长度</returns>
  23. public int GetContentLengthByHeadBytes( )
  24. {
  25. /************************************************************************
  26. *
  27. * 说明:为了应对有些特殊的设备,在整个指令的开端会增加一个额外的数据的时候
  28. *
  29. ************************************************************************/
  30. if (HeadBytes?.Length >= ProtocolHeadBytesLength)
  31. {
  32. int length = HeadBytes[4] * 256 + HeadBytes[5];
  33. if (length == 0)
  34. {
  35. byte[] buffer = new byte[ProtocolHeadBytesLength - 1];
  36. for (int i = 0; i < buffer.Length; i++)
  37. {
  38. buffer[i] = HeadBytes[i + 1];
  39. }
  40. HeadBytes = buffer;
  41. return HeadBytes[5] * 256 + HeadBytes[6] - 1;
  42. }
  43. else
  44. {
  45. return length - 2;
  46. }
  47. }
  48. else
  49. {
  50. return 0;
  51. }
  52. }
  53. /// <summary>
  54. /// 检查头子节的合法性
  55. /// </summary>
  56. /// <param name="token">特殊的令牌,有些特殊消息的验证</param>
  57. /// <returns>是否成功的结果</returns>
  58. public bool CheckHeadBytesLegal( byte[] token )
  59. {
  60. if (HeadBytes == null) return false;
  61. if (SendBytes[0] != HeadBytes[0] || SendBytes[1] != HeadBytes[1]) return false;
  62. return HeadBytes[2] == 0x00 && HeadBytes[3] == 0x00;
  63. }
  64. /// <summary>
  65. /// 获取头子节里的消息标识
  66. /// </summary>
  67. /// <returns>消息标识</returns>
  68. public int GetHeadBytesIdentity( )
  69. {
  70. return HeadBytes[0] * 256 + HeadBytes[1];
  71. }
  72. /// <summary>
  73. /// 消息头字节
  74. /// </summary>
  75. public byte[] HeadBytes { get; set; }
  76. /// <summary>
  77. /// 消息内容字节
  78. /// </summary>
  79. public byte[] ContentBytes { get; set; }
  80. /// <summary>
  81. /// 发送的字节信息
  82. /// </summary>
  83. public byte[] SendBytes { get; set; }
  84. }
  85. }