java - 我正在尝试通过 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();
}
}
}
解决方案
为什么int unsinged = Math.abs(inp[i]);
?
似乎您知道您需要字节中的无符号整数,但这不是您正在做的;您实际上只是获得了不是您想要的绝对值。
所以改用这个:
for (int i = 0; i < inp.length; i++) {
System.out.print(" " + Integer.toHexString(Byte.toUnsignedInt(inp[i])));
}
这将避免字节在转换为整数时被字节填充,ff
并使您的十六进制字符串准确地表示字节。
推荐阅读
- javascript - webpack 4 - HMR 不刷新 html 和 scss (ReactJS)
- typescript - 在 .then() 中分配 Typescript 参数
- c# - Path. 组合两个相对路径字符串以创建新的相对路径
- sql-server - 如何填充仅包含标识列的表?
- javascript - 识别移动设备的纵向或横向模式和缩放级别(但不特定于浏览器)
- c# - 在对 odata 相关实体过滤请求的高效 EF 生成查询中,不使用 And 子句应用 Inner Join
- javascript - 如何在 nuxtServerInit() 中获取 cookie?
- module - 导入带有打开的头文件:命名空间/模块错误
- mysql - 通过单个查询从多个表中返回数据
- php - 如何通过PHP在我的txt文件中显示员工记录的搜索结果?