SlaveExceptionResponse.cs 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. namespace NModbus.Message
  5. {
  6. internal class SlaveExceptionResponse : AbstractModbusMessage, IModbusMessage
  7. {
  8. private static readonly Dictionary<byte, string> _exceptionMessages = CreateExceptionMessages();
  9. public SlaveExceptionResponse()
  10. {
  11. }
  12. public SlaveExceptionResponse(byte slaveAddress, byte functionCode, byte exceptionCode)
  13. : base(slaveAddress, functionCode)
  14. {
  15. SlaveExceptionCode = exceptionCode;
  16. }
  17. public override int MinimumFrameSize => 3;
  18. public byte SlaveExceptionCode
  19. {
  20. get => MessageImpl.ExceptionCode.Value;
  21. set => MessageImpl.ExceptionCode = value;
  22. }
  23. /// <summary>
  24. /// Returns a <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
  25. /// </summary>
  26. /// <returns>
  27. /// A <see cref="T:System.String"></see> that represents the current <see cref="T:System.Object"></see>.
  28. /// </returns>
  29. public override string ToString()
  30. {
  31. string msg = _exceptionMessages.ContainsKey(SlaveExceptionCode)
  32. ? _exceptionMessages[SlaveExceptionCode]
  33. : Resources.Unknown;
  34. return string.Format(
  35. CultureInfo.InvariantCulture,
  36. Resources.SlaveExceptionResponseFormat,
  37. Environment.NewLine,
  38. FunctionCode,
  39. SlaveExceptionCode,
  40. msg);
  41. }
  42. internal static Dictionary<byte, string> CreateExceptionMessages()
  43. {
  44. return new Dictionary<byte, string>(9)
  45. {
  46. {1, Resources.IllegalFunction},
  47. {2, Resources.IllegalDataAddress},
  48. {3, Resources.IllegalDataValue},
  49. {4, Resources.SlaveDeviceFailure},
  50. {5, Resources.Acknowlege},
  51. {6, Resources.SlaveDeviceBusy},
  52. {8, Resources.MemoryParityError},
  53. {10, Resources.GatewayPathUnavailable},
  54. {11, Resources.GatewayTargetDeviceFailedToRespond}
  55. };
  56. }
  57. protected override void InitializeUnique(byte[] frame)
  58. {
  59. if (FunctionCode <= Modbus.ExceptionOffset)
  60. {
  61. throw new FormatException(Resources.SlaveExceptionResponseInvalidFunctionCode);
  62. }
  63. SlaveExceptionCode = frame[2];
  64. }
  65. }
  66. }