首页 > 解决方案 > 我正在尝试通过 ModBus RTU 协议从时间计数器 OVEN 获取数据,但收到垃圾作为响应

问题描述

我写了一些简单的代码来从我的计时器的 2 个寄存器中获取信息。
我正在向 OVEN 发送下一个命令:

10 03 00 16 00 02 26 8E

并期望得到下一个响应(尝试使用 OpenSCADA 进行):

10 03 04 00 BF AE B9 77 04

但相反,我得到了这个:

10 03 04 00 41 52 47 77 04

除了数据块,一切都是正确的,即使是 CRC 也是一样的。为什么呢?

好吧,这是一个代码:

    public static void workFlow(byte[] comm) throws IOException{
        try {
            byte inp [] = new byte [9];
            s = createSocket(address,port);
            s.getOutputStream().write(comm);
            s.setSoTimeout(500);
            Thread.sleep(1000);
            s.getInputStream().read(inp);

            for (int i = 0; i < inp.length; i++) {
                int unsinged = Math.abs(inp[i]);
                System.out.print(" " + Integer.toHexString(unsinged));
            }
            System.out.println("");

            s.close();
        } catch (Exception e) {
                            System.out.println("init error: " + e.getMessage());
                if (e.getMessage().contains("Read timed out")) {
                    System.out.println("Connection lost. Attempting to reconnect");
                    s.close();
                }
        }
    }

标签: java

解决方案


为什么int unsinged = Math.abs(inp[i]);

似乎您知道您需要字节中的无符号整数,但这不是您正在做的;您实际上只是获得了不是您想要的绝对值。

所以改用这个:

for (int i = 0; i < inp.length; i++) {
    System.out.print(" " + Integer.toHexString(Byte.toUnsignedInt(inp[i])));
}

这将避免字节在转换为整数时被字节填充,ff并使您的十六进制字符串准确地表示字节。


推荐阅读