using Mini8SlaveSim.Configuration; using ModbusSimulationProtocol.Services; namespace Mini8SlaveSim.Services { public class SlaveManagementService : ISlaveManagementService { private readonly ISharedConfig _sharedConfig; private readonly Dictionary _slaves = []; private byte _currentId = 0; public SlaveManagementService(ISharedConfig sharedConfig) { _sharedConfig = sharedConfig; } public event EventHandler? SlaveAdded; public Dictionary Slaves => _slaves; public byte WaitingForCreating => _currentId; public void AddSlave(byte slaveId) { if(_slaves.ContainsKey(slaveId)) { return; } string ip = _sharedConfig.HardwareAddress.Mini8sAddress[slaveId].Address!; int port = _sharedConfig.HardwareAddress.Mini8sAddress[slaveId].Port; ModbusSlaveService modbusSlaveService = new(null); if (!modbusSlaveService.Initialize(ip, (ushort)port, slaveId)) { modbusSlaveService.Dispose(); return; } if (!modbusSlaveService.Open()) { modbusSlaveService.Dispose(); return; } if (_slaves.TryAdd(slaveId, modbusSlaveService)) { _currentId = slaveId; SlaveAdded?.Invoke(this, slaveId); } } } }