温馨提示:本文翻译自stackoverflow.com,查看原文请点击:其他 - How do I send signal to modbus over TCP/IP in java?
modbus-tcp

其他 - 如何在Java中通过TCP / IP将信号发送到Modbus?

发布于 2020-03-27 10:52:21

我正在一个客户端应用程序上工作,该客户端应用程序应该将信号发送到modbus,该设备使用ip地址和不可更改的端口号502打开和关闭门。该指令说要创建一个win-socket客户端应用程序并发送命令缓冲区。我不明白如何发送命令缓冲区。这是命令的快照。 Modbus命令

我已经创建了Java套接字客户端类,但是我不知道要发送什么消息以及要使用什么数据类型来发送消息。还是我应该使用其中一个Modbus库发送信号。谢谢!

                socket = new Socket("192.168.0.8, 502);
                OutputStream output = socket.getOutputStream();
                OutputStreamWriter writer = new OutputStreamWriter(output);
                BufferedWriter bw = new BufferedWriter(writer);

                short buffer = ??; // don't know what to send here

                //String sendMesage = buffer;
                bw.write(buffer);
                bw.flush();
                System.out.println("Message sent to the server: " + buffer);

                InputStream receive = socket.getInputStream();
                InputStreamReader reader = new InputStreamReader(receive);
                BufferedReader bufferedReader = new BufferedReader(reader);

查看更多

查看更多

提问者
sanki
被浏览
52
Marcos G. 2019-07-12 14:45

Based on the code snippet you show on your question, one gets the impression you are attempting to write a Modbus client from scratch.

Modbus is a quite simple protocol but it would take quite an effort to write an debug a new client and, since the protocol is open, there is plenty of code already written, debugged and tested. See, for instance, here.

On what command to send it's not easy to tell if you don't mention what device, in particular, you're connecting to and what exactly you want to do with it. In a frequent scenario, you have a machine or a sensor in a remote area of your factory that is logging data from its sensors and reacting from that data in a certain manner. With Modbus, you can send requests for data to your machine (reading coils/bits or registers/numeric values) to monitor what it's doing and send commands to control it (writing Modbus coils or registers) from a distant control room with an HMI or any other kind of computer.

编辑:既然您已经决定使用EasyModbus,那么您将更接近您想要的东西。但是看来您正在寻找的是从设备中读取数据,因此您无需写入寄存器。您可以尝试使用以下代码片段(源代码):

public static void main(String[] args) 
    {
        ModbusClient modbusClient = new ModbusClient("127.0.0.1", 1536);
        try
        {
            modbusClient.Connect();
            //Read Int value from register 0 (Barrier Command)
            System.out.println(modbusClient.ReadHoldingRegisters(0, 1));
            //Read Float Value from Register 1 and 2 (Barrier Status)
            System.out.println(ModbusClient.ConvertRegistersToFloat(modbusClient.ReadHoldingRegisters(1, 2)));

        }
        catch (Exception e)
        {
        System.out.println(e.toString());
        }   
    }

如果您从设备上查看Modbus地址映射(我从本手册中获取了它,并假设您的设备是该设备):

在此处输入图片说明

要注意的一件事是设备上同时具有16位和32位值。由于Modbus寄存器是16位的,因此对于32位数据类型,您需要读取两个寄存器。这仅适用于编号为1的寄存器(根据以上映射的屏障状态)。对于所有其他内容,您可以读取并显示为整数值。