Java通过jlibmodbus 库实现的Modbus TCP协议 取值

文章详细描述了如何在Java中使用jlibmodbus库连接到ModbusTCP设备,执行读取线圈、离散输入、输入寄存器和保持寄存器的操作,并指出jlibmodbus在处理deviceid=0时可能出现的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

pom

<dependency>
    <groupId>com.intelligt.modbus</groupId>
    <artifactId>jlibmodbus</artifactId>
    <version>1.2.9.9</version>
</dependency>

代码

    public static void main(String[] args) throws ModbusProtocolException, ModbusNumberException, ModbusIOException {
        TcpParameters tcpParameters = new TcpParameters();
        try {
            tcpParameters.setHost(InetAddress.getByName("127.0.0.1"));
        } catch (UnknownHostException e) {
            throw new RuntimeException(e);
        }
        tcpParameters.setKeepAlive(true);
        tcpParameters.setPort(505);
        ModbusMaster modbusMasterTCP = ModbusMasterFactory.createModbusMasterTCP(tcpParameters);
        Modbus.setAutoIncrementTransactionId(true);
        boolean[] coils = modbusMasterTCP.readCoils(1, 0, 8);
        for (boolean b : coils) {
            System.out.println("线圈"+b);
        }

        boolean[] discreteInputs = modbusMasterTCP.readDiscreteInputs(1, 0, 8);
        for (boolean b : discreteInputs) {
            System.out.println("离散"+b);
        }

        int[] inputRegisters = modbusMasterTCP.readInputRegisters(1, 0, 2);//输入
        for (int anInt : inputRegisters) {
            System.out.println("输入"+anInt);
        }

        int[] holdingRegisters = modbusMasterTCP.readHoldingRegisters(1, 0, 2);//保持
        for (int anInt : holdingRegisters) {
            System.out.println("保持"+anInt);
        }
        
    }

线圈true
线圈false
线圈false
线圈false
线圈false
线圈false
线圈true
线圈false
离散false
离散true
离散false
离散false
离散false
离散false
离散true
离散false
输入1
输入2
保持0
保持17402

用这个需要注意  jlibmodbus  好像不能取值 device id = 0的   没深入研究

final static public int BROADCAST_ID = 0x00;


 synchronized public ModbusResponse processRequest(ModbusRequest request) throws ModbusProtocolException, ModbusIOException {
        try {
            sendRequest(request);
            if (request.getServerAddress() != Modbus.BROADCAST_ID) {
                do {
                    try {
                        ModbusResponse msg = (ModbusResponse) readResponse(request);
                        request.validateResponse(msg);
                        /*
                         * if you have received an ACKNOWLEDGE,
                         * it means that operation is in processing and you should be waiting for the answer
                         */
                        if (msg.getModbusExceptionCode() != ModbusExceptionCode.ACKNOWLEDGE) {
                            if (msg.isException())
                                throw new ModbusProtocolException(msg.getModbusExceptionCode());
                            return msg;
                        }
                    } catch (ModbusNumberException mne) {
                        Modbus.log().warning(mne.getLocalizedMessage());
                    }
                } while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - requestTimeNs) < getConnection().getReadTimeout());
                /*
                 * throw an exception if there is a response timeout
                 */
                throw new ModbusIOException("Response timeout.");
            } else {
            /*
             return because slaves do not respond broadcast requests

            返回无效的

             */
                broadcastResponse.setFunction(request.getFunction());
                return broadcastResponse;
            }
        } catch (ModbusIOException mioe) {
            disconnect();
            throw mioe;
        }
    }

Java可以通过jlibmodbus连接modbus tcp获取数据的步骤如下: 1. 导入jlibmodbusJava项目中。 2. 创建一个ModbusMasterTcp类的实例,用于连接到modbus tcp服务器。可以通过指定服务器的IP地址和端口号来创建实例。 3. 使用ModbusMasterTcp类的readInputRegisters方法或readHoldingRegisters方法来读取modbus设备上的寄存器值。需要指定寄存器的地址和数量。 4. 处理读取到的寄存器值,可以将它们转换为所需的数据类型。 以下是一个简单的示例代码,演示如何使用jlibmodbus连接modbus tcp服务器并读取寄存器值: ``` import com.intelligt.modbus.jlibmodbus.master.ModbusMasterTcp; public class ModbusTcpClient { public static void main(String[] args) { try { // 创建一个ModbusMasterTcp实例,连接到modbus tcp服务器 ModbusMasterTcp master = new ModbusMasterTcp("192.168.1.1", 502); // 读取寄存器值 int[] rawValues = master.readInputRegisters(0, 10); // 处理寄存器值 float temperature = decodeTemperature(rawValues[0], rawValues[1]); int pressure = decodePressure(rawValues[2], rawValues[3]); // 输出结果 System.out.println("Temperature: " + temperature); System.out.println("Pressure: " + pressure); } catch (Exception e) { e.printStackTrace(); } } private static float decodeTemperature(int highWord, int lowWord) { // 根据协议解析温度值 return 0.0f; } private static int decodePressure(int highWord, int lowWord) { // 根据协议解析压力值 return 0; } } ``` 请注意,以上代码中的decodeTemperature和decodePressure方法需要根据实际的协议进行实现,以正确解析寄存器值。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值