SlaveManagementService.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using Mini8SlaveSim.Configuration;
  2. using ModbusSimulationProtocol.Services;
  3. namespace Mini8SlaveSim.Services
  4. {
  5. public class SlaveManagementService : ISlaveManagementService
  6. {
  7. private readonly ISharedConfig _sharedConfig;
  8. private readonly Dictionary<byte, ModbusSlaveService> _slaves = [];
  9. private byte _currentId = 0;
  10. public SlaveManagementService(ISharedConfig sharedConfig)
  11. {
  12. _sharedConfig = sharedConfig;
  13. }
  14. public event EventHandler<byte>? SlaveAdded;
  15. public Dictionary<byte, ModbusSlaveService> Slaves => _slaves;
  16. public byte WaitingForCreating => _currentId;
  17. public void AddSlave(byte slaveId)
  18. {
  19. if(_slaves.ContainsKey(slaveId))
  20. {
  21. return;
  22. }
  23. string ip = _sharedConfig.HardwareAddress.Mini8sAddress[slaveId].Address!;
  24. int port = _sharedConfig.HardwareAddress.Mini8sAddress[slaveId].Port;
  25. ModbusSlaveService modbusSlaveService = new(null);
  26. if (!modbusSlaveService.Initialize(ip, (ushort)port, slaveId))
  27. {
  28. modbusSlaveService.Dispose();
  29. return;
  30. }
  31. if (!modbusSlaveService.Open())
  32. {
  33. modbusSlaveService.Dispose();
  34. return;
  35. }
  36. if (_slaves.TryAdd(slaveId, modbusSlaveService))
  37. {
  38. _currentId = slaveId;
  39. SlaveAdded?.Invoke(this, slaveId);
  40. }
  41. }
  42. }
  43. }