MelsecA1EBinaryMessage.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. namespace HslCommunication.Core.IMessage
  6. {
  7. /// <summary>
  8. /// 三菱的A兼容1E帧协议解析规则
  9. /// </summary>
  10. public class MelsecA1EBinaryMessage : INetMessage
  11. {
  12. /// <summary>
  13. /// 消息头的指令长度
  14. /// </summary>
  15. public int ProtocolHeadBytesLength
  16. {
  17. get
  18. {
  19. return 2; //副标题 + 结束代码(结束代码用于判断后续需要接收的数据长度)
  20. }
  21. }
  22. /// <summary>
  23. /// 从当前的头子节文件中提取出接下来需要接收的数据长度
  24. /// </summary>
  25. /// <returns>返回接下来的数据内容长度</returns>
  26. public int GetContentLengthByHeadBytes()
  27. {
  28. int contentLength = 0;
  29. if (HeadBytes[1] == 0x5B)
  30. {
  31. contentLength = 2; //结束代码 + 0x00
  32. return contentLength;
  33. }
  34. else
  35. {
  36. int length = (SendBytes[10] % 2 == 0) ? SendBytes[10] : SendBytes[10] + 1;
  37. switch (HeadBytes[0])
  38. {
  39. case 0x80: //位单位成批读出后,回复副标题
  40. contentLength = length / 2;
  41. break;
  42. case 0x81: //字单位成批读出后,回复副标题
  43. contentLength = SendBytes[10] * 2;
  44. break;
  45. case 0x82: //位单位成批写入后,回复副标题
  46. break;
  47. case 0x83: //字单位成批写入后,回复副标题
  48. break;
  49. default:
  50. break;
  51. }
  52. //在A兼容1E协议中,写入值后,若不发生异常,只返回副标题 + 结束代码(0x00)
  53. //这已经在协议头部读取过了,后面要读取的长度为0(contentLength=0)
  54. }
  55. return contentLength;
  56. }
  57. /// <summary>
  58. /// 检查头子节的合法性
  59. /// </summary>
  60. /// <param name="token">特殊的令牌,有些特殊消息的验证</param>
  61. /// <returns></returns>
  62. public bool CheckHeadBytesLegal( byte[] token )
  63. {
  64. if (HeadBytes != null)
  65. {
  66. if ((HeadBytes[0] - SendBytes[0]) == 0x80) { return true; }
  67. }
  68. return false;
  69. }
  70. /// <summary>
  71. /// 获取头子节里的消息标识
  72. /// </summary>
  73. /// <returns></returns>
  74. public int GetHeadBytesIdentity()
  75. {
  76. return 0;
  77. }
  78. /// <summary>
  79. /// 消息头字节
  80. /// </summary>
  81. public byte[] HeadBytes { get; set; }
  82. /// <summary>
  83. /// 消息内容字节
  84. /// </summary>
  85. public byte[] ContentBytes { get; set; }
  86. /// <summary>
  87. /// 发送的字节信息
  88. /// </summary>
  89. public byte[] SendBytes { get; set; }
  90. }
  91. }