using NModbus; using NModbus.Serial; using System; using System.Collections.Generic; using System.IO.Ports; using System.Net.Sockets; namespace Team.Communicate.Modbus { public class ModbusMasterFactory: IModbusMasterFactory { private readonly Dictionary _modbusTcpMasters; private readonly Dictionary _modbusSerialMasters; public ModbusMasterFactory() { _modbusTcpMasters = new Dictionary(); _modbusSerialMasters = new Dictionary(); } public IModbusSerialMaster CreateModbusSerialMaster(Guid id, string portName) { var modbus = new ModbusFactory(); if (_modbusSerialMasters.ContainsKey(id)) { return _modbusSerialMasters[id]; } var serialPort = new SerialPort(portName); var master= modbus.CreateRtuMaster(serialPort); _modbusSerialMasters.Add(id, master); return master; } public IModbusSerialMaster CreateModbusSerialMaster(Guid id, SerialPort serialPort) { var modbus = new ModbusFactory(); if (_modbusSerialMasters.ContainsKey(id)) { return _modbusSerialMasters[id]; } var master = modbus.CreateRtuMaster(serialPort); _modbusSerialMasters.Add(id, master); return master; } public IModbusTcpMaster CreateModbusTcpMaster(Guid id, string ip, int port) { var modbus=new ModbusTcpMaster(ip,port); if (_modbusTcpMasters.ContainsKey(id)) { return _modbusTcpMasters[id]; } _modbusTcpMasters.Add(id, modbus); return modbus; } public IModbusTcpMaster CreateModbusTcpMaster(Guid id, TcpClient tcpClient) { var modbus = new ModbusTcpMaster(tcpClient); if (_modbusTcpMasters.ContainsKey(id)) { return _modbusTcpMasters[id]; } _modbusTcpMasters.Add(id, modbus); return modbus; } public IModbusSerialMaster GetModbusSerialMaster(Guid id) { if (!_modbusSerialMasters.ContainsKey(id)) { return null; } return _modbusSerialMasters[id]; } public IModbusTcpMaster GetModbusTcpMaster(Guid id) { return _modbusTcpMasters[id]; } } }