12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455 |
- using Mini8SlaveSim.Configuration;
- using ModbusSimulationProtocol.Services;
- namespace Mini8SlaveSim.Services
- {
- public class SlaveManagementService : ISlaveManagementService
- {
- private readonly ISharedConfig _sharedConfig;
- private readonly Dictionary<byte, ModbusSlaveService> _slaves = [];
- private byte _currentId = 0;
- public SlaveManagementService(ISharedConfig sharedConfig)
- {
- _sharedConfig = sharedConfig;
- }
- public event EventHandler<byte>? SlaveAdded;
- public Dictionary<byte, ModbusSlaveService> 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);
- }
- }
- }
- }
|