ModbusTcpMaster.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package com.jwk.spring.boot.modbus4j;
  2. import com.serotonin.modbus4j.ModbusFactory;
  3. import com.serotonin.modbus4j.ModbusMaster;
  4. import com.serotonin.modbus4j.exception.ModbusInitException;
  5. import com.serotonin.modbus4j.ip.IpParameters;
  6. import lombok.Data;
  7. import lombok.extern.slf4j.Slf4j;
  8. import java.util.concurrent.Executors;
  9. import java.util.concurrent.locks.Lock;
  10. import java.util.concurrent.locks.ReentrantLock;
  11. /**
  12. * @author JWK
  13. * @version 1.0
  14. * @date 2022/9/7 17:00
  15. */
  16. @Slf4j
  17. @Data
  18. public class ModbusTcpMaster {
  19. private ModbusMaster master = null;
  20. private ModbusFactory modbusFactory = null;
  21. private ModbusMasterUtil modbusMasterUtil = null;
  22. private Lock lock = new ReentrantLock();
  23. private String host;
  24. private Integer port;
  25. /**
  26. * 初始化
  27. *
  28. * @param host
  29. * @param port
  30. * @throws ModbusInitException
  31. */
  32. public ModbusTcpMaster(String host, Integer port) {
  33. this.host = host;
  34. this.port = port;
  35. modbusFactory = new ModbusFactory();
  36. }
  37. /**
  38. * 打开串口 异步
  39. *
  40. * @throws ModbusInitException
  41. */
  42. public void connectAsync() {
  43. Executors.newSingleThreadExecutor().execute(() -> this.connect());
  44. }
  45. /**
  46. * 连接
  47. *
  48. * @throws ModbusInitException
  49. */
  50. public void connect() {
  51. for (; ; ) {
  52. try {
  53. if (!lock.tryLock()) {
  54. break;
  55. }
  56. IpParameters params = new IpParameters();
  57. params.setHost(host);
  58. params.setPort(port);
  59. master = modbusFactory.createTcpMaster(params, true);
  60. master.init();
  61. modbusMasterUtil = new ModbusMasterUtil(master);
  62. break;
  63. } catch (Exception e) {
  64. log.error("当前串口:{},打开失败!", getPort(), e);
  65. try {
  66. Thread.sleep(3000);
  67. } catch (InterruptedException ee) {
  68. }
  69. } finally {
  70. lock.unlock();
  71. }
  72. }
  73. }
  74. /**
  75. * 重新连接串口
  76. */
  77. public void reConnect() {
  78. try {
  79. master = null;
  80. connect();
  81. Thread.sleep(1000);
  82. } catch (Exception e) {
  83. }
  84. connect();
  85. }
  86. }