ModbusFactoryExtensions.cs 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. namespace NModbus.Extensions
  2. {
  3. using System;
  4. using Logging;
  5. internal static class ModbusFactoryExtensions
  6. {
  7. private const int MinRequestFrameLength = 3;
  8. public static IModbusMessage CreateModbusRequest(this IModbusFactory factory, byte[] frame)
  9. {
  10. if (frame.Length < MinRequestFrameLength)
  11. {
  12. string msg = $"Argument 'frame' must have a length of at least {MinRequestFrameLength} bytes.";
  13. throw new FormatException(msg);
  14. }
  15. byte functionCode = frame[1];
  16. var functionService = factory.GetFunctionService(functionCode);
  17. return functionService.CreateRequest(frame);
  18. }
  19. public static IModbusFunctionService GetFunctionServiceOrThrow(this IModbusFactory factory, byte functionCode)
  20. {
  21. IModbusFunctionService service = factory.GetFunctionService(functionCode);
  22. if (service == null)
  23. {
  24. string msg = $"Function code {functionCode} not supported.";
  25. factory.Logger.Warning(msg);
  26. throw new NotImplementedException(msg);
  27. }
  28. return service;
  29. }
  30. }
  31. }