ModbusMasterFactory.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. using NModbus;
  2. using NModbus.Serial;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO.Ports;
  6. using System.Net.Sockets;
  7. namespace Team.Communicate.Modbus
  8. {
  9. public class ModbusMasterFactory: IModbusMasterFactory
  10. {
  11. private readonly Dictionary<Guid, IModbusTcpMaster> _modbusTcpMasters;
  12. private readonly Dictionary<Guid, IModbusSerialMaster> _modbusSerialMasters;
  13. public ModbusMasterFactory()
  14. {
  15. _modbusTcpMasters = new Dictionary<Guid, IModbusTcpMaster>();
  16. _modbusSerialMasters = new Dictionary<Guid, IModbusSerialMaster>();
  17. }
  18. public IModbusSerialMaster CreateModbusSerialMaster(Guid id, string portName)
  19. {
  20. var modbus = new ModbusFactory();
  21. if (_modbusSerialMasters.ContainsKey(id))
  22. {
  23. return _modbusSerialMasters[id];
  24. }
  25. var serialPort = new SerialPort(portName);
  26. var master= modbus.CreateRtuMaster(serialPort);
  27. _modbusSerialMasters.Add(id, master);
  28. return master;
  29. }
  30. public IModbusSerialMaster CreateModbusSerialMaster(Guid id, SerialPort serialPort)
  31. {
  32. var modbus = new ModbusFactory();
  33. if (_modbusSerialMasters.ContainsKey(id))
  34. {
  35. return _modbusSerialMasters[id];
  36. }
  37. var master = modbus.CreateRtuMaster(serialPort);
  38. _modbusSerialMasters.Add(id, master);
  39. return master;
  40. }
  41. public IModbusTcpMaster CreateModbusTcpMaster(Guid id, string ip, int port)
  42. {
  43. var modbus=new ModbusTcpMaster(ip,port);
  44. if (_modbusTcpMasters.ContainsKey(id))
  45. {
  46. return _modbusTcpMasters[id];
  47. }
  48. _modbusTcpMasters.Add(id, modbus);
  49. return modbus;
  50. }
  51. public IModbusTcpMaster CreateModbusTcpMaster(Guid id, TcpClient tcpClient)
  52. {
  53. var modbus = new ModbusTcpMaster(tcpClient);
  54. if (_modbusTcpMasters.ContainsKey(id))
  55. {
  56. return _modbusTcpMasters[id];
  57. }
  58. _modbusTcpMasters.Add(id, modbus);
  59. return modbus;
  60. }
  61. public IModbusSerialMaster GetModbusSerialMaster(Guid id)
  62. {
  63. if (!_modbusSerialMasters.ContainsKey(id))
  64. {
  65. return null;
  66. }
  67. return _modbusSerialMasters[id];
  68. }
  69. public IModbusTcpMaster GetModbusTcpMaster(Guid id)
  70. {
  71. return _modbusTcpMasters[id];
  72. }
  73. }
  74. }