feat: modbus-tcp写功能及测试

This commit is contained in:
2026-03-03 16:17:58 +08:00
parent 30a5f68905
commit 79ce8f976b
6 changed files with 427 additions and 181 deletions

View File

@@ -79,4 +79,76 @@ public class ApiTest {
e.printStackTrace();
}
}
@Test
public void modbusTestWrite() {
// 构建驱动配置(连接配置)
Map<String, AttributeBO> driverConfig = new HashMap<>();
driverConfig.put("host", AttributeBO.builder().value("192.168.81.251").build());
driverConfig.put("port", AttributeBO.builder().value("502").build());
// 构建点位配置 - 写入保持寄存器功能码3
Map<String, AttributeBO> pointConfig = new HashMap<>();
pointConfig.put("slaveId", AttributeBO.builder().value("1").build());
pointConfig.put("offset", AttributeBO.builder().value("40001").build()); // 功能码3保持寄存器地址0
pointConfig.put("data_type", AttributeBO.builder().value("int16").build());
// 构建连接对象
IotConnect connect = IotConnect.builder()
.id(1)
.code("MODBUS_TCP_001")
.host("192.168.81.251")
.port(502)
.protocol("modbus-tcp")
.enabled(true)
.description("测试Modbus TCP写入连接")
.build();
// 构建配置对象
IotConfig config = IotConfig.builder()
.id(1)
.connectId(1)
.alias("temperature")
.aliasName("温度传感器")
.registerAddress("40001")
.dataType("int16")
.readonly(false)
.enabled(true)
.description("测试温度写入")
.build();
try {
// 先读取当前值
System.out.println("=== Modbus写入测试开始 ===");
RValue beforeValue = modBusProtocolDriver.read(driverConfig, pointConfig, connect, config);
System.out.println("写入前的值: " + beforeValue.getValue());
// 构建写入值对象 - 写入新的温度值例如100
org.nl.iot.core.driver.entity.WValue wValue = new org.nl.iot.core.driver.entity.WValue();
wValue.setValue("100");
wValue.setType("int16");
// 调用write方法进行写入测试
Boolean writeResult = modBusProtocolDriver.write(driverConfig, pointConfig, connect, config, wValue);
System.out.println("写入结果: " + (writeResult ? "成功" : "失败"));
// 等待一小段时间后再次读取,验证写入是否成功
Thread.sleep(500);
RValue afterValue = modBusProtocolDriver.read(driverConfig, pointConfig, connect, config);
System.out.println("写入后的值: " + afterValue.getValue());
// 验证写入是否成功
if (writeResult && "100".equals(afterValue.getValue())) {
System.out.println("✓ 写入验证成功!值已更新为: " + afterValue.getValue());
} else {
System.out.println("✗ 写入验证失败!期望值: 100, 实际值: " + afterValue.getValue());
}
System.out.println("=== 测试完成 ===");
} catch (Exception e) {
System.err.println("测试失败: " + e.getMessage());
e.printStackTrace();
}
}
}