1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283 |
- 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<Guid, IModbusTcpMaster> _modbusTcpMasters;
- private readonly Dictionary<Guid, IModbusSerialMaster> _modbusSerialMasters;
- public ModbusMasterFactory()
- {
- _modbusTcpMasters = new Dictionary<Guid, IModbusTcpMaster>();
- _modbusSerialMasters = new Dictionary<Guid, IModbusSerialMaster>();
- }
- 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];
- }
- }
- }
|