100% open-source IoT Platform - Integrate your devices, add intelligence, build custom apps
Java asset-managementbuildingdashboarddataplatformdevice-managementedge-computingenergyenergy-managementenergy-monitorfleet-managementfleet-telematicsiotiot-applicationiot-platformmodbusmqttmqtt-brokerota-updaterules-enginesmartcity
MODBUS protocol refactor to use NettyIOClients (#2097)
Wouter Voorbergd7f110a66f74
diff --git a/agent/build.gradle b/agent/build.gradleindex 5d6129569..5b1d3c764 100644--- a/agent/build.gradle+++ b/agent/build.gradle@@ -21,9 +21,6 @@ dependencies {api "net.sf.saxon:Saxon-HE:$saxonHEVersion"- implementation "org.apache.plc4x:plc4j-api:$plc4xVersion"- runtimeOnly "org.apache.plc4x:plc4j-driver-modbus:$plc4xVersion"-//IKEA Tradfri agent dependenciesapi "org.eclipse.californium:californium-core:$californiumCoreVersion"api "org.eclipse.californium:scandium:$californiumScandiumVersion"diff --git a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIOClientProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIOClientProtocol.javaindex 322902a79..17f16ecf7 100644--- a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIOClientProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractIOClientProtocol.java@@ -57,7 +57,7 @@ public abstract class AbstractIOClientProtocol<T extends AbstractIOClientProtoco/*** Supplies a set of encoders/decoders that convert from/to {@link String} to/from {@link ByteBuf} based on the generic protocol {@link Attribute}s*/- public static Supplier<ChannelHandler[]> getGenericStringEncodersAndDecoders(AbstractNettyIOClient<String, ?> client, IOAgent<?, ?, ?> agent) {+ public static Supplier<ChannelHandler[]> getGenericStringEncodersAndDecoders(AbstractNettyIOClient<String> client, IOAgent<?, ?, ?> agent) {boolean hexMode = agent.getMessageConvertHex().orElse(false);boolean binaryMode = agent.getMessageConvertBinary().orElse(false);diff --git a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIOClient.javaindex 53d20fe39..304d87cc6 100644--- a/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/io/AbstractNettyIOClient.java@@ -33,7 +33,6 @@ import org.openremote.container.Container;import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.syslog.SyslogCategory;-import java.net.SocketAddress;import java.time.Duration;import java.util.ArrayList;import java.util.Arrays;@@ -76,7 +75,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;* <b>NOTE: Care must be taken when working with Netty {@link ByteBuf} as Netty uses reference counting to manage their* lifecycle. Refer to the Netty documentation for more information.</b>*/-public abstract class AbstractNettyIOClient<T, U extends SocketAddress> implements NettyIOClient<T> {+public abstract class AbstractNettyIOClient<T> implements NettyIOClient<T> {public static long RECONNECT_DELAY_INITIAL_MILLIS = 1000L;public static long RECONNECT_DELAY_MAX_MILLIS = 5*60000L;@@ -88,10 +87,10 @@ public abstract class AbstractNettyIOClient<T, U extends SocketAddress> implemen*/public static class ByteToMessageDecoder<T> extends io.netty.handler.codec.ByteToMessageDecoder {protected List<T> messages = new ArrayList<>(1);- protected AbstractNettyIOClient<T, ?> client;+ protected NettyIOClient<T> client;protected BiConsumer<ByteBuf, List<T>> decoder;- public ByteToMessageDecoder(AbstractNettyIOClient<T, ?> client, @NotNull BiConsumer<ByteBuf, List<T>> decoder) {+ public ByteToMessageDecoder(NettyIOClient<T> client, @NotNull BiConsumer<ByteBuf, List<T>> decoder) {this.client = client;this.decoder = decoder;}@@ -112,9 +111,9 @@ public abstract class AbstractNettyIOClient<T, U extends SocketAddress> implemen* This is intended to be used at the end of a decoder chain where the previous decoder outputs messages of type <T>.*/public static class MessageToMessageDecoder<T> extends SimpleChannelInboundHandler<T> {- protected AbstractNettyIOClient<T,?> client;+ protected NettyIOClient<T> client;- public MessageToMessageDecoder(Class<? extends T> typeClazz, AbstractNettyIOClient<T, ?> client) {+ public MessageToMessageDecoder(Class<? extends T> typeClazz, NettyIOClient<T> client) {super(typeClazz);this.client = client;}@@ -129,10 +128,10 @@ public abstract class AbstractNettyIOClient<T, U extends SocketAddress> implemen* Concrete implementations must provide an encoder to fill the {@link ByteBuf} ready to be sent `over the wire`.*/public static class MessageToByteEncoder<T> extends io.netty.handler.codec.MessageToByteEncoder<T> {- protected AbstractNettyIOClient<T, ?> client;+ protected NettyIOClient<T> client;protected BiConsumer<T, ByteBuf> encoder;- public MessageToByteEncoder(Class<? extends T> typeClazz, AbstractNettyIOClient<T, ?> client, BiConsumer<T, ByteBuf> encoder) {+ public MessageToByteEncoder(Class<? extends T> typeClazz, AbstractNettyIOClient<T> client, BiConsumer<T, ByteBuf> encoder) {super(typeClazz);this.client = client;this.encoder = encoder;@@ -498,7 +497,8 @@ public abstract class AbstractNettyIOClient<T, U extends SocketAddress> implemen}}- protected void onMessageReceived(T message) {+ @Override+ public void onMessageReceived(T message) {LOG.finest("Message received notifying consumers: " + getClientUri());messageConsumers.forEach(consumer -> {try {diff --git a/agent/src/main/java/org/openremote/agent/protocol/io/NettyIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/io/NettyIOClient.javaindex 7a67978e4..e239e1862 100644--- a/agent/src/main/java/org/openremote/agent/protocol/io/NettyIOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/io/NettyIOClient.java@@ -36,4 +36,10 @@ public interface NettyIOClient<T> extends IOClient<T> {* support this then an {@link UnsupportedOperationException} will be thrown, consult the {@link IOClient}'s documentation.*/void setEncoderDecoderProvider(Supplier<ChannelHandler[]> encoderDecoderProvider) throws UnsupportedOperationException;++ /**+ *+ * @param message+ */+ void onMessageReceived(T message);}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/AbstractModbusProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/AbstractModbusProtocol.javaindex 6d11c855c..e7a857317 100644--- a/agent/src/main/java/org/openremote/agent/protocol/modbus/AbstractModbusProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/AbstractModbusProtocol.java@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -19,159 +19,628 @@*/package org.openremote.agent.protocol.modbus;-import org.apache.plc4x.java.api.PlcConnection;-import org.apache.plc4x.java.api.messages.PlcReadRequest;-import org.apache.plc4x.java.api.messages.PlcReadResponse;-import org.apache.plc4x.java.api.messages.PlcWriteRequest;-import org.apache.plc4x.java.api.messages.PlcWriteResponse;-import org.apache.plc4x.java.api.types.PlcResponseCode;+import io.netty.channel.ChannelHandler;import org.openremote.agent.protocol.AbstractProtocol;+import org.openremote.agent.protocol.io.NettyIOClient;+import org.openremote.agent.protocol.modbus.util.BatchReadRequest;+import org.openremote.agent.protocol.modbus.util.ModbusDataConverter;+import org.openremote.agent.protocol.modbus.util.ModbusFrame;+import org.openremote.agent.protocol.modbus.util.ModbusPduBuilder;+import org.openremote.agent.protocol.modbus.util.RegisterRange;import org.openremote.model.Container;+import org.openremote.model.asset.agent.AgentLink;import org.openremote.model.asset.agent.ConnectionStatus;import org.openremote.model.attribute.Attribute;import org.openremote.model.attribute.AttributeEvent;import org.openremote.model.attribute.AttributeRef;import org.openremote.model.syslog.SyslogCategory;-import java.util.HashMap;-import java.util.Map;-import java.util.Optional;+import java.util.*;+import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.ScheduledFuture;import java.util.concurrent.TimeUnit;+import java.util.concurrent.TimeoutException;+import java.util.function.Supplier;import java.util.logging.Level;import java.util.logging.Logger;+import java.util.stream.Collectors;-import static org.openremote.model.asset.agent.AgentLink.getOrThrowAgentLinkProperty;-import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;--public abstract class AbstractModbusProtocol<S extends AbstractModbusProtocol<S,T>, T extends ModbusAgent<T, S>>- extends AbstractProtocol<T, ModbusAgentLink>{+/**+ * Abstract base class for Modbus protocol implementations (TCP and Serial/RTU).+ * Manages the IO client lifecycle and contains shared Modbus logic for batching,+ * polling, data conversion, and PDU building.+ *+ * @param <T> the concrete protocol type+ * @param <U> the agent type+ * @param <F> the frame type (ModbusTcpFrame or ModbusSerialFrame)+ */+public abstract class AbstractModbusProtocol<T extends AbstractModbusProtocol<T, U, F>, U extends ModbusAgent<U, T>, F extends ModbusFrame>+ extends AbstractProtocol<U, ModbusAgentLink> {- public static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, AbstractModbusProtocol.class);+ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, AbstractModbusProtocol.class);- protected final Map<AttributeRef, ScheduledFuture<?>> pollingMap = new HashMap<>();+ protected NettyIOClient<F> client;+ protected final Object requestLock = new Object();+ protected int timeoutMs = 3000;- PlcConnection client = null;+ // Batching and scheduling state+ final Map<String, Map<AttributeRef, ModbusAgentLink>> batchGroups = new ConcurrentHashMap<>();+ final Map<String, List<BatchReadRequest>> cachedBatches = new ConcurrentHashMap<>();+ private final Map<String, ScheduledFuture<?>> batchReadIntervalTasks = new ConcurrentHashMap<>();+ final Map<AttributeRef, ScheduledFuture<?>> writeIntervalMap = new HashMap<>();- public AbstractModbusProtocol(T agent) {+ protected AbstractModbusProtocol(U agent) {super(agent);}- @Override- protected void doStart(Container container) throws Exception {+ // ========== Abstract methods for subclasses ==========- try {- setConnectionStatus(ConnectionStatus.CONNECTING);+ /**+ * Create the transport-specific IO client.+ */+ protected abstract NettyIOClient<F> doCreateIoClient() throws Exception;- client = createIoClient(agent);+ /**+ * Get the Netty encoder/decoder pipeline for this transport.+ */+ protected abstract Supplier<ChannelHandler[]> getEncoderDecoderProvider();- client.connect();+ /**+ * Handle a received message from the IO client.+ */+ protected abstract void onMessageReceived(F message);++ /**+ * Send a Modbus request and wait for the response.+ * This is transport-specific (TCP uses transaction IDs, Serial uses timing).+ */+ public abstract F sendModbusRequest(int unitId, byte[] pdu, long timeoutMs) throws Exception;++ // ========== Lifecycle ==========- setConnectionStatus(client.isConnected() ? ConnectionStatus.CONNECTED : ConnectionStatus.ERROR);+ @Override+ public String getProtocolInstanceUri() {+ return client != null ? client.getClientUri() : "";+ }++ @Override+ protected void doStart(Container container) throws Exception {+ try {+ client = doCreateIoClient();+ if (client == null) {+ throw new IllegalStateException("IO client should not be null");+ }+ client.setEncoderDecoderProvider(getEncoderDecoderProvider());+ client.addConnectionStatusConsumer(this::setConnectionStatus);+ client.addMessageConsumer(this::onMessageReceived);+ LOG.fine("Created IO client '" + client.getClientUri() + "' for protocol: " + this);+ client.connect();} catch (Exception e) {- LOG.log(Level.SEVERE, "Failed to create PLC4X connection for protocol instance: " + agent, e);+ LOG.warning(getProtocolName() + " - Failed to start: " + e.getMessage());setConnectionStatus(ConnectionStatus.ERROR);- throw e;+ return;+ }++ // Initialize deviceConfig if empty+ Optional<ModbusAgent.DeviceConfigMap> deviceConfigOpt = agent.getDeviceConfig();+ if (deviceConfigOpt.isEmpty() || deviceConfigOpt.get().isEmpty()) {+ LOG.info(getProtocolName() + " - Initializing deviceConfig with default configuration for agent: " + agent.getName());+ ModbusAgent.DeviceConfigMap defaultConfig = new ModbusAgent.DeviceConfigMap();+ defaultConfig.put("default", ModbusAgent.ModbusDeviceConfig.createDefault());+ agent.addOrReplaceAttributes(new Attribute<>(ModbusAgent.DEVICE_CONFIG, defaultConfig));+ sendAttributeEvent(new AttributeEvent(agent.getId(), ModbusAgent.DEVICE_CONFIG, defaultConfig));}}+@Overrideprotected void doStop(Container container) throws Exception {- pollingMap.forEach((key, value) -> value.cancel(false));+ // Cancel scheduled tasks+ batchReadIntervalTasks.values().forEach(future -> future.cancel(false));+ batchReadIntervalTasks.clear();+ batchGroups.clear();+ cachedBatches.clear();+ writeIntervalMap.forEach((key, value) -> value.cancel(false));+ writeIntervalMap.clear();- client.close();+ doTransportStop();++ if (client != null) {+ client.removeAllMessageConsumers();+ client.removeAllConnectionStatusConsumers();+ client.disconnect();+ }+ client = null;}+ /**+ * Override in subclasses to clean up transport-specific state during stop.+ */+ protected void doTransportStop() {+ // Default no-op+ }++ // ========== Attribute linking ==========+@Override- protected void doLinkAttribute(String assetId, Attribute<?> attribute, ModbusAgentLink agentLink) throws RuntimeException {+ protected void doLinkAttribute(String assetId, Attribute<?> attribute, ModbusAgentLink agentLink) {AttributeRef ref = new AttributeRef(assetId, attribute.getName());- pollingMap.put(ref,- scheduleModbusPollingReadRequest(- ref,- agentLink.getPollingMillis(),- agentLink.getReadMemoryArea(),- agentLink.getReadValueType(),- agentLink.getReadRegistersAmount(),- agentLink.getReadAddress()- )- );++ // Check if read configuration is present (all required parameters)+ boolean hasReadConfig = agentLink.getReadMemoryArea() != null+ && agentLink.getReadValueType() != null+ && agentLink.getReadAddress() != null+ && agentLink.getUnitId() != null;++ if (hasReadConfig) {+ if (agentLink.getRequestInterval() != null) {+ // Setup continuous read interval using batching+ String groupKey = agent.getId() + "_" + agentLink.getUnitId() + "_" + agentLink.getReadMemoryArea() + "_" + agentLink.getRequestInterval();++ batchGroups.computeIfAbsent(groupKey, k -> new ConcurrentHashMap<>()).put(ref, agentLink);+ synchronized (cachedBatches) {+ cachedBatches.remove(groupKey); // Invalidate cache+ }++ // Only schedule task if one doesn't exist yet for this group+ if (!batchReadIntervalTasks.containsKey(groupKey)) {+ ScheduledFuture<?> batchTask = scheduleBatchedReadIntervalTask(groupKey, agentLink.getReadMemoryArea(), agentLink.getRequestInterval(), agentLink.getUnitId());+ batchReadIntervalTasks.put(groupKey, batchTask);+ LOG.fine(getProtocolName() + " - Scheduled new read interval task for batch group " + groupKey);+ }++ LOG.fine(getProtocolName() + " - Added attribute " + ref + " to batch group " + groupKey + " (total attributes in group: " + batchGroups.get(groupKey).size() + ")");+ } else {+ // No requestInterval: execute one-time read on connection+ LOG.fine(getProtocolName() + " - Scheduling one-time read on connection for " + ref);+ scheduleOneTimeRead(ref, agentLink);+ }+ } else {+ LOG.fine(getProtocolName() + " - Skipping read interval for " + ref + " - read configuration incomplete (unitId, readMemoryArea, readValueType, and readAddress all required)");+ }++ // Check if write interval is enabled (requestInterval set, writeAddress present, no read address)+ if (agentLink.getRequestInterval() != null && agentLink.getWriteAddress() != null && agentLink.getReadAddress() == null) {+ ScheduledFuture<?> writeTask = scheduleModbusWriteRequestInterval(ref, agentLink);+ writeIntervalMap.put(ref, writeTask);+ LOG.fine(getProtocolName() + " - Scheduled write interval task for attribute " + ref + " every " + agentLink.getRequestInterval() + "ms");+ }}@Overrideprotected void doUnlinkAttribute(String assetId, Attribute<?> attribute, ModbusAgentLink agentLink) {AttributeRef attributeRef = new AttributeRef(assetId, attribute.getName());- ScheduledFuture<?> pollTask = pollingMap.remove(attributeRef);- if (pollTask != null) {- pollTask.cancel(false);++ // Remove from write interval+ ScheduledFuture<?> writeTask = writeIntervalMap.remove(attributeRef);+ if (writeTask != null) {+ writeTask.cancel(false);+ }++ // Remove from batch group (if read config was present)+ if (agentLink.getReadMemoryArea() != null) {+ String groupKey = agent.getId() + "_" + agentLink.getUnitId() + "_" + agentLink.getReadMemoryArea() + "_" + agentLink.getRequestInterval();+ Map<AttributeRef, ModbusAgentLink> group = batchGroups.get(groupKey);+ if (group != null) {+ group.remove(attributeRef);+ synchronized (cachedBatches) {+ cachedBatches.remove(groupKey); // Invalidate cache+ }++ // If group is empty, cancel batch task+ if (group.isEmpty()) {+ batchGroups.remove(groupKey);+ synchronized (cachedBatches) {+ cachedBatches.remove(groupKey);+ }+ ScheduledFuture<?> task = batchReadIntervalTasks.remove(groupKey);+ if (task != null) {+ task.cancel(false);+ }+ LOG.fine(getProtocolName() + " - Removed empty batch group " + groupKey);+ } else {+ LOG.fine(getProtocolName() + " - Removed attribute " + attributeRef + " from batch group " + groupKey + " (remaining attributes: " + group.size() + ")");+ }+ }}}+ // ========== Write handling ==========+@Overrideprotected void doLinkedAttributeWrite(ModbusAgentLink agentLink, AttributeEvent event, Object processedValue) {+ // Check connection status before attempting write+ if (getConnectionStatus() != ConnectionStatus.CONNECTED) {+ LOG.fine("Skipping write operation - not connected (status: " + getConnectionStatus() + ")");+ return;+ }++ int unitId = agentLink.getUnitId() != null ? agentLink.getUnitId() : 1;+ int writeAddress = AgentLink.getOrThrowAgentLinkProperty(Optional.ofNullable(agentLink.getWriteAddress()), "write address");+ int registersCount = Optional.ofNullable(agentLink.getRegistersAmount()).orElse(1);++ // Convert 1-based user address to 0-based protocol address+ int protocolAddress = writeAddress - 1;++ try {+ byte[] pdu;++ switch (agentLink.getWriteMemoryArea()) {+ case COIL -> {+ boolean value = processedValue instanceof Boolean ? (Boolean) processedValue : false;+ pdu = ModbusPduBuilder.buildWriteSingleCoilPDU(protocolAddress, value);+ LOG.fine(getProtocolName() + " Write Coil - UnitId: " + unitId + ", Address: " + writeAddress + " (0x" + Integer.toHexString(protocolAddress) + "), Value: " + value);+ }+ case HOLDING -> {+ if (registersCount == 1) {+ int value = processedValue instanceof Number ? ((Number) processedValue).intValue() : 0;+ pdu = ModbusPduBuilder.buildWriteSingleRegisterPDU(protocolAddress, value);+ LOG.fine(getProtocolName() + " Write Single Register - UnitId: " + unitId + ", Address: " + writeAddress + " (0x" + Integer.toHexString(protocolAddress) + "), Value: " + value);+ } else {+ ModbusAgent.EndianFormat endianFormat = getEndianFormat(unitId);+ byte[] registerData = ModbusDataConverter.convertValueToRegisterBytes(processedValue, registersCount, agentLink.getReadValueType(), endianFormat);+ pdu = ModbusPduBuilder.buildWriteMultipleRegistersPDU(protocolAddress, registerData);+ LOG.fine(getProtocolName() + " Write Multiple Registers - UnitId: " + unitId + ", Address: " + writeAddress + " (0x" + Integer.toHexString(protocolAddress) + "), RegisterCount: " + registersCount + ", DataType: " + agentLink.getReadValueType());+ }+ }+ default -> throw new IllegalStateException("Only COIL and HOLDING memory areas are supported for writing");+ }++ // Send request and wait for response+ F response = sendModbusRequest(unitId, pdu, timeoutMs);++ if (response.isException()) {+ byte exceptionCode = response.getPdu()[1];+ String exceptionDesc = ModbusPduBuilder.getModbusExceptionDescription(exceptionCode);+ LOG.warning(getProtocolName() + " - Write failed for address=" + writeAddress + " UnitId= " + unitId + ": " + exceptionDesc + " Event: " + event);+ return;+ }++ LOG.fine(getProtocolName() + " Write Success - UnitId: " + unitId + ", Address: " + writeAddress);++ // Handle attribute update based on read configuration+ if (event.getSource() != null) {+ if (agentLink.getReadAddress() == null) {+ // Write-only: update the local linkedAttributes cache and notify the system+ Attribute<?> attribute = linkedAttributes.get(event.getRef());+ if (attribute != null) {+ @SuppressWarnings("unchecked")+ Attribute<Object> attr = (Attribute<Object>) attribute;+ attr.setValue(processedValue);+ }+ updateLinkedAttribute(event.getRef(), processedValue);+ LOG.finest(getProtocolName() + " - Write-only attribute updated: " + event.getRef());+ } else {+ // Write + Read: trigger immediate read to verify write+ LOG.finest(getProtocolName() + " - Triggering verification read after write for " + event.getRef());+ triggerImmediateRead(event.getRef(), agentLink);+ }+ }+ } catch (Exception e) {+ String operation = "write address=" + writeAddress;+ if (e instanceof TimeoutException) {+ LOG.warning(getProtocolName() + " - " + operation + " timed out: " + e.getMessage());+ } else {+ LOG.log(Level.WARNING, getProtocolName() + " - " + operation + " failed: " + e.getMessage() + " Event: " + event, e);+ }+ throw (e instanceof RuntimeException) ? (RuntimeException) e : new RuntimeException(e);+ }+ }++ // ========== Batching logic ==========++ protected List<BatchReadRequest> createBatchRequests(+ Map<AttributeRef, ModbusAgentLink> attributeLinks,+ Set<RegisterRange> illegalRanges,+ int maxRegisterLength) {++ Map<ModbusAgentLink.ReadMemoryArea, List<Map.Entry<AttributeRef, ModbusAgentLink>>> groupedByMemoryArea =+ attributeLinks.entrySet().stream()+ .collect(Collectors.groupingBy(e -> e.getValue().getReadMemoryArea()));++ List<BatchReadRequest> batches = new ArrayList<>();++ for (Map.Entry<ModbusAgentLink.ReadMemoryArea, List<Map.Entry<AttributeRef, ModbusAgentLink>>> group : groupedByMemoryArea.entrySet()) {+ List<Map.Entry<AttributeRef, ModbusAgentLink>> sortedAttributes = group.getValue().stream()+ .sorted(Comparator.comparingInt(e -> Optional.ofNullable(e.getValue().getReadAddress()).orElse(0)))+ .collect(Collectors.toList());++ BatchReadRequest currentBatch = null;+ int currentEnd = -1;++ for (Map.Entry<AttributeRef, ModbusAgentLink> entry : sortedAttributes) {+ ModbusAgentLink link = entry.getValue();+ int address = Optional.ofNullable(link.getReadAddress()).orElse(0);+ int registerCount = Optional.ofNullable(link.getRegistersAmount()).orElse(link.getReadValueType().getRegisterCount());++ if (currentBatch != null) {+ boolean hasIllegalInGap = false;+ int firstIllegalRegister = -1;++ for (int i = currentEnd; i < address; i++) {+ if (isIllegalRegister(i, illegalRanges)) {+ hasIllegalInGap = true;+ firstIllegalRegister = i;+ break;+ }+ }++ int newQuantity = address + registerCount - currentBatch.getStartAddress();++ if (!hasIllegalInGap && newQuantity <= maxRegisterLength) {+ int offset = address - currentBatch.getStartAddress();+ currentBatch.addAttribute(entry.getKey(), offset);+ currentBatch.setQuantity(newQuantity);+ currentEnd = address + registerCount;+ LOG.finest(getProtocolName() + " - Added register " + address + " to batch starting at " + currentBatch.getStartAddress() + " (new quantity=" + newQuantity + ")");+ continue;+ } else {+ batches.add(currentBatch);+ String reason = hasIllegalInGap+ ? "illegal register " + firstIllegalRegister + " detected in gap (registers " + currentEnd + "-" + (address - 1) + ")"+ : "would exceed maxRegisterLength (" + newQuantity + " > " + maxRegisterLength + ")";+ LOG.fine(getProtocolName() + " - Split batch before register " + address + ": " + reason);+ }+ }- // Look at comment in schedulePollingRequest for an explanation to this- int writeAddress = getOrThrowAgentLinkProperty(agentLink.getWriteAddress(), "write address");+ currentBatch = new BatchReadRequest(address, registerCount);+ currentBatch.addAttribute(entry.getKey(), 0);+ currentEnd = address + registerCount;+ LOG.fine(getProtocolName() + " - Started new batch at address " + address);+ }- PlcWriteRequest.Builder builder = client.writeRequestBuilder();+ if (currentBatch != null) {+ batches.add(currentBatch);+ LOG.fine(getProtocolName() + " - Finalized batch: startAddress=" + currentBatch.getStartAddress() + ", quantity=" + currentBatch.getQuantity() + ", attributes=" + currentBatch.getAttributes().size());+ }+ }++ return batches;+ }++ protected ScheduledFuture<?> scheduleBatchedReadIntervalTask(String groupKey, ModbusAgentLink.ReadMemoryArea memoryArea, long requestInterval, Integer unitId) {+ LOG.fine(getProtocolName() + " - Scheduling batched read interval task for group " + groupKey + " every " + requestInterval + "ms");++ return scheduledExecutorService.scheduleWithFixedDelay(() -> {+ try {+ Map<AttributeRef, ModbusAgentLink> group = batchGroups.get(groupKey);+ if (group == null || group.isEmpty()) {+ return;+ }- switch (agentLink.getWriteMemoryArea()){- case COIL -> builder.addTagAddress("coil", "coil:" + writeAddress, processedValue);- case HOLDING -> builder.addTagAddress("holdingRegisters", "holding-register:" + writeAddress, processedValue);- default -> throw new IllegalStateException("No other memory area is allowed to write to a Modbus server");+ List<BatchReadRequest> batches;+ synchronized (cachedBatches) {+ batches = cachedBatches.get(groupKey);+ if (batches == null) {+ int maxRegisterLength = getMaxRegisterLength(unitId);+ String illegalRegistersStr = getIllegalRegistersString(unitId);+ Set<RegisterRange> illegalRegistersForUnit = parseIllegalRegisters(illegalRegistersStr);++ LOG.fine(getProtocolName() + " - Creating batch requests for group " + groupKey + " with " + group.size() + " attribute(s) (unitId=" + unitId + ", maxRegisterLength=" + maxRegisterLength + ")");+ batches = createBatchRequests(group, illegalRegistersForUnit, maxRegisterLength);+ cachedBatches.put(groupKey, batches);+ }+ }++ for (int i = 0; i < batches.size(); i++) {+ BatchReadRequest batch = batches.get(i);+ int endAddress = batch.getStartAddress() + batch.getQuantity() - 1;+ LOG.finest(getProtocolName() + " - Executing batch " + (i + 1) + "/" + batches.size() + ": registers=" + batch.getStartAddress() + "-" + endAddress + " (quantity=" + batch.getQuantity() + ", attributes=" + batch.getAttributes().size() + ")");+ executeBatchRead(batch, memoryArea, group, unitId);+ }++ } catch (Exception e) {+ LOG.log(Level.FINE, "Exception during batched reading interval: " + e.getMessage(), e);+ }+ }, 0, requestInterval, TimeUnit.MILLISECONDS);+ }++ protected void executeBatchRead(BatchReadRequest batch, ModbusAgentLink.ReadMemoryArea memoryArea, Map<AttributeRef, ModbusAgentLink> group, Integer unitId) {+ if (getConnectionStatus() != ConnectionStatus.CONNECTED) {+ LOG.fine("Skipping batch read operation - not connected (status: " + getConnectionStatus() + ")");+ return;}- PlcWriteRequest request = builder.build();+ int effectiveUnitId = unitId != null ? unitId : 1;try {- PlcWriteResponse response = request.execute().get(3, TimeUnit.SECONDS);- if (response.getResponseCode(response.getTagNames().stream().findFirst().orElseThrow()) != PlcResponseCode.OK){- throw new IllegalStateException("PLC Write Response code is something other than \"OK\"");+ int protocolAddress = batch.getStartAddress() - 1;++ byte functionCode = switch (memoryArea) {+ case COIL -> (byte) 0x01;+ case DISCRETE -> (byte) 0x02;+ case HOLDING -> (byte) 0x03;+ case INPUT -> (byte) 0x04;+ };++ byte[] pdu = ModbusPduBuilder.buildReadRequestPDU(functionCode, protocolAddress, batch.getQuantity());++ LOG.fine(getProtocolName() + " Read Request - MemoryArea: " + memoryArea + ", UnitId: " + effectiveUnitId + ", StartAddress: " + batch.getStartAddress() + " (0x" + Integer.toHexString(protocolAddress) + "), Quantity: " + batch.getQuantity() + ", AttributeCount: " + batch.getAttributes().size());+ F response = sendModbusRequest(effectiveUnitId, pdu, timeoutMs);++ if (response.isException()) {+ byte exceptionCode = response.getPdu()[1];+ String exceptionDesc = ModbusPduBuilder.getModbusExceptionDescription(exceptionCode);+ LOG.warning(getProtocolName() + " - Batch read " + memoryArea + ", UnitId: " + effectiveUnitId + " address=" + batch.getStartAddress() + " quantity=" + batch.getQuantity() + " failed: " + exceptionDesc);+ return;+ }++ byte[] data = ModbusPduBuilder.extractDataFromResponsePDU(response.getPdu(), functionCode);+ if (data == null) {+ LOG.warning(getProtocolName() + " - Batch read " + memoryArea + " address=" + batch.getStartAddress() + " failed: Invalid response format");+ return;}++ LOG.finest(getProtocolName() + " Read Success - MemoryArea: " + memoryArea + ", UnitId: " + effectiveUnitId + ", DataBytes: " + data.length);++ for (int i = 0; i < batch.getAttributes().size(); i++) {+ AttributeRef ref = batch.getAttributes().get(i);+ int offset = batch.getOffsets().get(i);+ ModbusAgentLink agentLink = group.get(ref);++ if (agentLink == null) {+ continue;+ }++ try {+ int registerCount = Optional.ofNullable(agentLink.getRegistersAmount())+ .orElse(agentLink.getReadValueType().getRegisterCount());+ ModbusAgentLink.ModbusDataType dataType = agentLink.getReadValueType();++ LOG.fine(getProtocolName() + " - Extracting value for " + ref + " - DataType: " + dataType + ", RegisterCount: " + registerCount + ", Offset: " + offset + ", ReadAddress: " + agentLink.getReadAddress());+ ModbusAgent.EndianFormat endianFormat = getEndianFormat(effectiveUnitId);+ Object value = ModbusDataConverter.extractValueFromBatchResponse(data, offset, registerCount, dataType, endianFormat, functionCode);++ if (value != null) {+ LOG.finest(getProtocolName() + " - Successfully extracted value for " + ref + " - Value: " + value + ", DataType: " + dataType + ", RegisterCount: " + registerCount);+ updateLinkedAttribute(ref, value);+ } else {+ LOG.warning(getProtocolName() + " - Extracted null value for " + ref + " - DataType: " + dataType + ", RegisterCount: " + registerCount + ", Offset: " + offset);+ }+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Failed to extract value for " + ref + " at offset " + offset + " (DataType: " + agentLink.getReadValueType() + ", RegisterCount: " + agentLink.getRegistersAmount() + "): " + e.getMessage(), e);+ }+ }+} catch (Exception e) {- throw new RuntimeException(e);+ String operation = "batch read " + memoryArea + " address=" + batch.getStartAddress() + " quantity=" + batch.getQuantity() + ", AttrGroup: " + group;+ if (e instanceof TimeoutException) {+ LOG.warning(getProtocolName() + " - " + operation + " timed out: " + e.getMessage());+ } else {+ LOG.log(Level.WARNING, getProtocolName() + " - " + operation + " failed: " + e.getMessage(), e);+ }}}- protected ScheduledFuture<?> scheduleModbusPollingReadRequest(AttributeRef ref,- long pollingMillis,- ModbusAgentLink.ReadMemoryArea readType,- ModbusAgentLink.ModbusDataType dataType,- Optional<Integer> amountOfRegisters,- Optional<Integer> readAddress) {+ protected void scheduleOneTimeRead(AttributeRef ref, ModbusAgentLink agentLink) {+ scheduledExecutorService.execute(() -> {+ try {+ int registerCount = Optional.ofNullable(agentLink.getRegistersAmount()).orElse(agentLink.getReadValueType().getRegisterCount());+ BatchReadRequest batch = new BatchReadRequest(agentLink.getReadAddress(), registerCount);+ batch.addAttribute(ref, 0);- PlcReadRequest.Builder builder = client.readRequestBuilder();+ Map<AttributeRef, ModbusAgentLink> tempGroup = new ConcurrentHashMap<>();+ tempGroup.put(ref, agentLink);- int readAmountOfRegisters = (amountOfRegisters.isEmpty() || amountOfRegisters.get() < 1)- ? dataType.getRegisterCount() : amountOfRegisters.get();- String amountOfRegistersString = readAmountOfRegisters <= 1 ? "" : "["+readAmountOfRegisters+"]";+ executeBatchRead(batch, agentLink.getReadMemoryArea(), tempGroup, agentLink.getUnitId());- int address = readAddress.orElseThrow(() -> new RuntimeException("Read Address is empty! Unable to schedule read request."));+ LOG.fine(getProtocolName() + " - One-time read executed for " + ref);+ } catch (Exception e) {+ LOG.log(Level.WARNING, getProtocolName() + " - Exception during one-time read for " + ref + ": " + e.getMessage(), e);+ }+ });+ }- switch (readType) {- case COIL -> builder.addTagAddress("coils", "coil:" + address + ":" + dataType + amountOfRegistersString);- case DISCRETE -> builder.addTagAddress("discreteInputs", "discrete-input:" + address + ":" + dataType + amountOfRegistersString);- case HOLDING -> builder.addTagAddress("holdingRegisters", "holding-register:" + address + ":" + dataType + amountOfRegistersString);- case INPUT -> builder.addTagAddress("inputRegisters", "input-register:" + address + ":" + dataType + amountOfRegistersString);- default -> throw new IllegalArgumentException("Unsupported read type: " + readType);- }- PlcReadRequest readRequest = builder.build();+ protected ScheduledFuture<?> scheduleModbusWriteRequestInterval(AttributeRef ref, ModbusAgentLink agentLink) {+ LOG.fine("Scheduling " + getProtocolName() + " Write interval request to execute every " + agentLink.getRequestInterval() + "ms for attributeRef: " + ref);- LOG.log(Level.FINE,"Scheduling Modbus Read Value polling request '" + "clientRequest" + "' to execute every " + pollingMillis + "ms for attributeRef: " + ref);return scheduledExecutorService.scheduleWithFixedDelay(() -> {try {- PlcReadResponse response = readRequest.execute().get(3, TimeUnit.SECONDS);+ Attribute<?> attribute = linkedAttributes.get(ref);+ if (attribute == null || attribute.getValue().isEmpty()) {+ LOG.finest(getProtocolName() + " - Skipping write interval for " + ref + " - no value available");+ return;+ }++ Object currentValue = attribute.getValue().orElse(null);+ if (currentValue == null) {+ return;+ }- // We currently only request one thing (with the above tag), so we get it from there. If it doesn't exist,- // we can assume that the request failed.- String responseTag = response.getTagNames().stream().findFirst()- .orElseThrow(() -> new RuntimeException("Could not retrieve the requested value from the response"));+ AttributeEvent syntheticEvent = new AttributeEvent(ref, currentValue);+ doLinkedAttributeWrite(agentLink, syntheticEvent, currentValue);- Object responseValue = response.getObject(responseTag, readAmountOfRegisters-1);- updateLinkedAttribute(ref, responseValue);+ LOG.finest(getProtocolName() + " - Write interval executed for " + ref + " with value: " + currentValue);} catch (Exception e) {- LOG.log(Level.FINE,"Exception thrown during Modbus Read Value polling request '" + readRequest.toString());+ LOG.log(Level.WARNING, getProtocolName() + " - Exception during write interval for " + ref + ": " + e.getMessage(), e);+ }+ }, 0, agentLink.getRequestInterval(), TimeUnit.MILLISECONDS);+ }++ protected void triggerImmediateRead(AttributeRef ref, ModbusAgentLink agentLink) {+ scheduledExecutorService.execute(() -> {+ try {+ int registerCount = Optional.ofNullable(agentLink.getRegistersAmount())+ .orElse(agentLink.getReadValueType().getRegisterCount());+ BatchReadRequest batch = new BatchReadRequest(agentLink.getReadAddress(), registerCount);+ batch.addAttribute(ref, 0);++ Map<AttributeRef, ModbusAgentLink> tempGroup = new ConcurrentHashMap<>();+ tempGroup.put(ref, agentLink);++ executeBatchRead(batch, agentLink.getReadMemoryArea(), tempGroup, agentLink.getUnitId());+ LOG.finest(getProtocolName() + " - Verification read completed for " + ref);+ } catch (Exception e) {+ LOG.log(Level.WARNING, getProtocolName() + " - Failed to execute verification read for " + ref + ": " + e.getMessage(), e);+ }+ });+ }++ // ========== Connection status ==========++ public ConnectionStatus getConnectionStatus() {+ return client != null ? client.getConnectionStatus() : ConnectionStatus.DISCONNECTED;+ }++ // ========== Device config helpers ==========++ protected ModbusAgent.ModbusDeviceConfig getDeviceConfigForUnitId(Integer unitId) {+ ModbusAgent.DeviceConfigMap configMap = agent.getDeviceConfig().orElse(null);++ if (configMap == null || configMap.isEmpty()) {+ return ModbusAgent.ModbusDeviceConfig.createDefault();+ }++ if (unitId != null && configMap.containsKey(String.valueOf(unitId))) {+ return configMap.get(String.valueOf(unitId));+ }+ return configMap.getOrDefault("default", ModbusAgent.ModbusDeviceConfig.createDefault());+ }++ protected int getMaxRegisterLength(Integer unitId) {+ return getDeviceConfigForUnitId(unitId).getMaxRegisterLength();+ }++ protected String getIllegalRegistersString(Integer unitId) {+ return getDeviceConfigForUnitId(unitId).getIllegalRegisters();+ }++ protected ModbusAgent.EndianFormat getEndianFormat(Integer unitId) {+ return getDeviceConfigForUnitId(unitId).getEndianFormat();+ }++ // ========== Utilities ==========++ protected Set<RegisterRange> parseIllegalRegisters(String illegalRegistersStr) {+ Set<RegisterRange> ranges = new HashSet<>();+ if (illegalRegistersStr == null || illegalRegistersStr.trim().isEmpty()) {+ return ranges;+ }++ String[] parts = illegalRegistersStr.split(",");+ for (String part : parts) {+ part = part.trim();+ if (part.contains("-")) {+ String[] rangeParts = part.split("-");+ try {+ int start = Integer.parseInt(rangeParts[0].trim());+ int end = Integer.parseInt(rangeParts[1].trim());+ ranges.add(new RegisterRange(start, end));+ } catch (NumberFormatException e) {+ LOG.warning(getProtocolName() + " - Invalid register range format: " + part);+ }+ } else {+ try {+ int register = Integer.parseInt(part);+ ranges.add(new RegisterRange(register, register));+ } catch (NumberFormatException e) {+ LOG.warning(getProtocolName() + " - Invalid register format: " + part);+ }}- }, 0, pollingMillis, TimeUnit.MILLISECONDS);+ }+ return ranges;}- protected abstract PlcConnection createIoClient(T agent) throws RuntimeException;+ protected boolean isIllegalRegister(int register, Set<RegisterRange> illegalRanges) {+ return illegalRanges.stream().anyMatch(range -> range.contains(register));+ }}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgent.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgent.javaindex 2d00145c7..964ef680b 100644--- a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgent.java+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgent.java@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -19,18 +19,72 @@*/package org.openremote.agent.protocol.modbus;+import com.fasterxml.jackson.annotation.JsonCreator;import jakarta.persistence.Entity;import org.openremote.model.asset.agent.Agent;-import org.openremote.model.attribute.MetaItem;import org.openremote.model.value.AttributeDescriptor;-import org.openremote.model.value.MetaItemType;-import org.openremote.model.value.ValueConstraint;-import org.openremote.model.value.ValueType;+import org.openremote.model.value.ValueDescriptor;++import java.util.HashMap;+import java.util.Optional;@Entity-public abstract class ModbusAgent<T extends ModbusAgent<T, U>, U extends AbstractModbusProtocol<U, T>> extends Agent<T, U, ModbusAgentLink> {+public abstract class ModbusAgent<T extends ModbusAgent<T, U>, U extends AbstractModbusProtocol<U, T, ?>> extends Agent<T, U, ModbusAgentLink> {++ public enum EndianFormat {+ BIG_ENDIAN, // ABCD - Big byte order, Big word order+ LITTLE_ENDIAN, // DCBA - Little byte order, Little word order+ BIG_ENDIAN_BYTE_SWAP, // BADC - Big byte order, Little word order+ LITTLE_ENDIAN_BYTE_SWAP; // CDAB - Little byte order, Big word order+ }++ /**+ * Configuration for a Modbus device (per unit ID).+ * Contains all device-specific settings.+ */+ public static class ModbusDeviceConfig implements java.io.Serializable {+ private EndianFormat endianFormat;+ private String illegalRegisters;+ private int maxRegisterLength;++ @JsonCreator+ public ModbusDeviceConfig(+ EndianFormat endianFormat,+ String illegalRegisters,+ Integer maxRegisterLength) {+ this.endianFormat = endianFormat != null ? endianFormat : EndianFormat.BIG_ENDIAN;+ this.illegalRegisters = illegalRegisters;+ this.maxRegisterLength = maxRegisterLength != null ? maxRegisterLength : 1;+ }++ /**+ * Default configuration factory method+ */+ public static ModbusDeviceConfig createDefault() {+ return new ModbusDeviceConfig(EndianFormat.BIG_ENDIAN, null, 1);+ }++ public EndianFormat getEndianFormat() {+ return endianFormat;+ }- public static final AttributeDescriptor<Integer> UNIT_ID = new AttributeDescriptor<>("unitId", ValueType.INTEGER, new MetaItem<>(MetaItemType.CONSTRAINTS, ValueConstraint.constraints(new ValueConstraint.Min(1), new ValueConstraint.Max(255))));+ public String getIllegalRegisters() {+ return illegalRegisters;+ }++ public int getMaxRegisterLength() {+ return maxRegisterLength;+ }++ }++ // Map type for per-unitId device configuration (unitId string -> ModbusDeviceConfig)+ public static class DeviceConfigMap extends HashMap<String, ModbusDeviceConfig> {}+ public static final ValueDescriptor<DeviceConfigMap> VALUE_DEVICE_CONFIG_MAP = new ValueDescriptor<>("DeviceConfigMap", DeviceConfigMap.class);++ // Shared device configuration attribute descriptor+ public static final AttributeDescriptor<DeviceConfigMap> DEVICE_CONFIG =+ new AttributeDescriptor<>("deviceConfig", VALUE_DEVICE_CONFIG_MAP);// For Hydratorsprotected ModbusAgent() {}@@ -39,11 +93,11 @@ public abstract class ModbusAgent<T extends ModbusAgent<T, U>, U extends Abstracsuper(name);}- public Integer getUnitId(){- return getAttributes().getValue(UNIT_ID).get();- }-- public void setUnitId(Integer unitId) {- getAttributes().getOrCreate(UNIT_ID).setValue(unitId);+ /**+ * Get the device configuration map for this agent.+ * @return Optional containing the device config map if configured+ */+ public Optional<DeviceConfigMap> getDeviceConfig() {+ return getAttributes().getValue(DEVICE_CONFIG);}}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.javaindex ab2f44ff7..8d2ee6a44 100644--- a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.java+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusAgentLink.java@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -19,46 +19,55 @@*/package org.openremote.agent.protocol.modbus;+import com.fasterxml.jackson.annotation.JsonAlias;import com.fasterxml.jackson.annotation.JsonPropertyDescription;-import jakarta.validation.constraints.NotNull;+import jakarta.validation.constraints.Min;import org.openremote.model.asset.agent.AgentLink;-import java.math.BigInteger;-import java.util.Optional;public class ModbusAgentLink extends AgentLink<ModbusAgentLink> {- @NotNull()- @JsonPropertyDescription("Poll interval in milliseconds")- private Long pollingMillis;+ @JsonPropertyDescription("Modbus unit ID (1-255). Required for Serial, optional for TCP (defaults to 1)")+ @Min(1)+ private Integer unitId;++ @JsonPropertyDescription("Request interval in milliseconds. If not set: reads execute once on connection, writes execute on demand only.")+ @Min(1000)+ private Long requestInterval;- @NotNull()@JsonPropertyDescription("Memory area to read from during read request")private ReadMemoryArea readMemoryArea;- @NotNull()- @JsonPropertyDescription("Type to convert the returned data to. As specified by the PLC4X Modbus data types.")+ @JsonPropertyDescription("Type to convert the returned data to.")private ModbusDataType readValueType;- @NotNull()- @JsonPropertyDescription("Zero based address from which the value is read from")+ @JsonPropertyDescription("1-based address from which the value is read from (e.g., HOLDING register 1 = 40001)")private Integer readAddress;@JsonPropertyDescription("Memory area to write to. \"HOLDING\" or \"COIL\" allowed.")private WriteMemoryArea writeMemoryArea;- @JsonPropertyDescription("Zero-based address to which the value sent is written to")+ @JsonPropertyDescription("1-based address to which the value is written to (e.g., HOLDING register 1 = 40001)")private Integer writeAddress;- @JsonPropertyDescription("Set amount of registers to read. If left empty or less than 1, will use the default size for the corresponding data-type.")- private Integer readRegistersAmount;+ @JsonPropertyDescription("Set amount of registers to read/write. If left empty or less than 1, will use the default size for the corresponding data-type.")+ @JsonAlias("readRegisterAmount") // Support old field name for backward compatibility+ private Integer registersAmount;++ public Integer getUnitId() {+ return unitId;+ }- public long getPollingMillis() {- return pollingMillis;+ public void setUnitId(Integer unitId) {+ this.unitId = unitId;}- public void setPollingMillis(long pollingMillis) {- this.pollingMillis = pollingMillis;+ public Long getRequestInterval() {+ return requestInterval;+ }++ public void setRequestInterval(Long requestInterval) {+ this.requestInterval = requestInterval;}public ReadMemoryArea getReadMemoryArea() {@@ -77,8 +86,8 @@ public class ModbusAgentLink extends AgentLink<ModbusAgentLink> {this.readValueType = readValueType;}- public Optional<Integer> getReadAddress() {- return Optional.ofNullable(readAddress);+ public Integer getReadAddress() {+ return readAddress;}public void setReadAddress(Integer readAddress) {@@ -93,20 +102,20 @@ public class ModbusAgentLink extends AgentLink<ModbusAgentLink> {this.writeMemoryArea = writeMemoryArea;}- public Optional<Integer> getWriteAddress() {- return Optional.ofNullable(writeAddress);+ public Integer getWriteAddress() {+ return writeAddress;}public void setWriteAddress(Integer writeAddress) {this.writeAddress = writeAddress;}- public Optional<Integer> getReadRegistersAmount() {- return Optional.ofNullable(readRegistersAmount);+ public Integer getRegistersAmount() {+ return registersAmount;}- public void setReadRegistersAmount(Integer readRegistersAmount) {- this.readRegistersAmount = writeAddress;+ public void setRegistersAmount(Integer registersAmount) {+ this.registersAmount = registersAmount;}public enum ReadMemoryArea {@@ -153,7 +162,6 @@ public class ModbusAgentLink extends AgentLink<ModbusAgentLink> {COIL, HOLDING}-public ModbusAgentLink(String id) {super(id);}protected ModbusAgentLink() {diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialAgent.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialAgent.javaindex 66a636c5e..7c3a49103 100644--- a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialAgent.java+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialAgent.java@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -20,36 +20,30 @@package org.openremote.agent.protocol.modbus;import jakarta.persistence.Entity;+import org.openremote.agent.protocol.serial.JSerialCommChannelConfig.Paritybit;+import org.openremote.agent.protocol.serial.JSerialCommChannelConfig.Stopbits;import org.openremote.model.asset.agent.Agent;import org.openremote.model.asset.agent.AgentDescriptor;import org.openremote.model.value.AttributeDescriptor;+import org.openremote.model.value.ValueDescriptor;import org.openremote.model.value.ValueType;+import java.util.Optional;/**- * This Modbus serial agent is currently untested, due to difficulties in testing Modbus serial agents (especially the- * absence of automated Modbus serial testing libraries)+ * This Modbus serial agent has been tested with USB-UART-RS485 converters with chips CH341 and CP2104. RS232 remains untested.*/@Entity-public class ModbusSerialAgent extends ModbusAgent<ModbusSerialAgent, ModbusSerialProtocol>{+public class ModbusSerialAgent extends ModbusAgent<ModbusSerialAgent, ModbusSerialProtocol> {public static final AttributeDescriptor<String> SERIAL_PORT = Agent.SERIAL_PORT.withOptional(false);public static final AttributeDescriptor<Integer> BAUD_RATE = Agent.SERIAL_BAUDRATE.withOptional(false);public static final AttributeDescriptor<Integer> DATA_BITS = new AttributeDescriptor<>("dataBits", ValueType.POSITIVE_INTEGER);- public static final AttributeDescriptor<Integer> STOP_BITS = new AttributeDescriptor<>("stopBits", ValueType.POSITIVE_INTEGER);- //TODO: Doesn't work, getting a frontend error TypeError: Cannot read properties of undefined (reading 'units') at getValueFormatConstraintOrUnits-// public static final AttributeDescriptor<ModbusClientParity> PARITY = new AttributeDescriptor<ModbusClientParity>("parity",-// new ValueDescriptor<ModbusClientParity>("modbusClientParity", ModbusClientParity.class)-// );+ public static final ValueDescriptor<Stopbits> VALUE_STOPBITS = new ValueDescriptor<>("Stopbits", Stopbits.class);+ public static final AttributeDescriptor<Stopbits> STOP_BITS = new AttributeDescriptor<>("stopbits", VALUE_STOPBITS);-- public enum ModbusClientParity {- NO_PARITY,- ODD_PARITY,- EVEN_PARITY,- MARK_PARITY,- SPACE_PARITY,- }+ public static final ValueDescriptor<Paritybit> VALUE_PARITY = new ValueDescriptor<>("Paritybit", Paritybit.class);+ public static final AttributeDescriptor<Paritybit> PARITY = new AttributeDescriptor<>("parity", VALUE_PARITY);public static final AgentDescriptor<ModbusSerialAgent, ModbusSerialProtocol, ModbusAgentLink> DESCRIPTOR = new AgentDescriptor<>(ModbusSerialAgent.class, ModbusSerialProtocol.class, ModbusAgentLink.class@@ -65,22 +59,25 @@ public class ModbusSerialAgent extends ModbusAgent<ModbusSerialAgent, ModbusSerisuper(name);}- public Integer getBaudRate() {- return getAttribute(BAUD_RATE).get().getValue().get();+ public Optional<String> getSerialPort() {+ return getAttributes().getValue(SERIAL_PORT);}- public Integer getDataBits() {- return getAttribute(DATA_BITS).get().getValue().get();+ public int getBaudRate() {+ return getAttributes().getValue(BAUD_RATE).orElse(9600);}- public Integer getStopBits() {- return getAttribute(STOP_BITS).get().getValue().get();+ public int getDataBits() {+ return getAttributes().getValue(DATA_BITS).orElse(8);}-// public ModbusClientParity getParity() {-// return getAttribute(PARITY).get().getValue().get();-// }+ public Stopbits getStopBits() {+ return getAttributes().getValue(STOP_BITS).orElse(Stopbits.STOPBITS_1);+ }+ public Paritybit getParity() {+ return getAttributes().getValue(PARITY).orElse(Paritybit.EVEN);+ }@Overridepublic ModbusSerialProtocol getProtocolInstance() {diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialProtocol.javaindex 9bea283ab..357be7908 100644--- a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusSerialProtocol.java@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -19,41 +19,138 @@*/package org.openremote.agent.protocol.modbus;-import org.apache.plc4x.java.api.PlcConnection;-import org.apache.plc4x.java.api.PlcDriverManager;-import org.apache.plc4x.java.api.exceptions.PlcConnectionException;+import io.netty.channel.ChannelHandler;+import org.openremote.agent.protocol.io.AbstractNettyIOClient;+import org.openremote.agent.protocol.io.NettyIOClient;+import org.openremote.agent.protocol.modbus.util.ModbusRTUDecoder;+import org.openremote.agent.protocol.modbus.util.ModbusRTUEncoder;+import org.openremote.agent.protocol.modbus.util.ModbusSerialFrame;+import org.openremote.agent.protocol.serial.SerialIOClient;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.syslog.SyslogCategory;++import java.util.concurrent.*;+import java.util.function.Supplier;+import java.util.logging.Logger;++/**+ * Modbus Serial (RTU) protocol implementation.+ * Handles Serial-specific transport: half-duplex communication with timing gaps.+ */+public class ModbusSerialProtocol extends AbstractModbusProtocol<ModbusSerialProtocol, ModbusSerialAgent, ModbusSerialFrame> {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, ModbusSerialProtocol.class);++ // Single pending request (RTU is half-duplex, no transaction IDs)+ private volatile CompletableFuture<ModbusSerialFrame> pendingRequest = null;+ private long lastRequestTime = 0;+ private static final long MIN_REQUEST_INTERVAL_MS = 10; // Gap between requests per modbus.org+ private final Object sendLock = new Object();-public class ModbusSerialProtocol extends AbstractModbusProtocol<ModbusSerialProtocol, ModbusSerialAgent>{public ModbusSerialProtocol(ModbusSerialAgent agent) {super(agent);}- private String connectionString;+ // ========== Transport-specific implementations ==========@Override- protected PlcConnection createIoClient(ModbusSerialAgent agent) throws RuntimeException {-- connectionString = "modbus-rtu://"+agent.getSerialPort() +- "?serial.baud-rate=" + agent.getBaudRate() +- "&unit-identifier=" + agent.getUnitId() +- "&serial.num-data-bits=" + agent.getDataBits() +- "&serial.num-stop-bits=" + agent.getStopBits();- PlcConnection plcConnection;- try {- plcConnection = PlcDriverManager.getDefault().getConnectionManager().getConnection(connectionString);- } catch (PlcConnectionException e) {- throw new RuntimeException(e);+ protected NettyIOClient<ModbusSerialFrame> doCreateIoClient() throws Exception {+ String portName = agent.getSerialPort().orElseThrow(() -> new RuntimeException("Serial port not specified"));+ int baudRate = agent.getBaudRate();+ int dataBits = agent.getDataBits();+ var stopBits = agent.getStopBits();+ var parity = agent.getParity();++ return new SerialIOClient<>(portName, baudRate, dataBits, stopBits, parity);+ }++ @Override+ protected Supplier<ChannelHandler[]> getEncoderDecoderProvider() {+ return () -> new ChannelHandler[] {+ new ModbusRTUEncoder(),+ new ModbusRTUDecoder(),+ new AbstractNettyIOClient.MessageToMessageDecoder<>(ModbusSerialFrame.class, client)+ };+ }++ @Override+ protected void onMessageReceived(ModbusSerialFrame frame) {+ LOG.finest(() -> "Received frame - UnitID: " + frame.getUnitId() ++ ", FC: 0x" + Integer.toHexString(frame.getFunctionCode() & 0xFF));++ synchronized (requestLock) {+ if (pendingRequest != null) {+ pendingRequest.complete(frame);+ } else {+ LOG.warning("Received Modbus Serial response with no pending request");+ }}- return plcConnection;}@Override- public String getProtocolName() {- return "Modbus Serial Protocol";+ protected void doTransportStop() {+ synchronized (requestLock) {+ if (pendingRequest != null) {+ pendingRequest.cancel(true);+ pendingRequest = null;+ }+ }+ }++ @Override+ public ModbusSerialFrame sendModbusRequest(int unitId, byte[] pdu, long timeoutMs) throws Exception {+ // sendLock ensures only one request-response cycle can be active at a time+ synchronized (sendLock) {+ if (client == null || client.getConnectionStatus() != ConnectionStatus.CONNECTED) {+ throw new IllegalStateException("Client not connected");+ }++ // Wait for minimum interval between requests (Modbus RTU requires gaps)+ long timeSinceLastRequest = System.currentTimeMillis() - lastRequestTime;+ if (timeSinceLastRequest < MIN_REQUEST_INTERVAL_MS) {+ try {+ Thread.sleep(MIN_REQUEST_INTERVAL_MS - timeSinceLastRequest);+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ throw new RuntimeException("Interrupted while waiting for request interval", e);+ }+ }++ // Create frame and future for response+ ModbusSerialFrame request = new ModbusSerialFrame(unitId, pdu);+ CompletableFuture<ModbusSerialFrame> responseFuture = new CompletableFuture<>();++ // Register pending request (use requestLock for thread-safe access)+ synchronized (requestLock) {+ pendingRequest = responseFuture;+ }++ try {+ // Send request+ client.sendMessage(request);+ lastRequestTime = System.currentTimeMillis();+ LOG.finest(() -> "Sent Modbus Serial request - UnitID: " + unitId ++ ", FC: 0x" + Integer.toHexString(pdu[0] & 0xFF));++ // Wait for response (NOT holding requestLock so handler can complete the future)+ ModbusSerialFrame response = responseFuture.get(timeoutMs, TimeUnit.MILLISECONDS);+ LOG.finest(() -> "Received Modbus Serial response - UnitID: " + response.getUnitId() ++ ", FC: 0x" + Integer.toHexString(response.getFunctionCode() & 0xFF));+ return response;+ } catch (TimeoutException e) {+ LOG.warning("Modbus Serial request timeout - UnitID: " + unitId);+ throw e;+ } finally {+ // Clear pending request+ synchronized (requestLock) {+ pendingRequest = null;+ }+ }+ }}@Override- public String getProtocolInstanceUri() {- return connectionString;+ public String getProtocolName() {+ return "Modbus Serial";}}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpAgent.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpAgent.javaindex 1eba9447f..574617501 100644--- a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpAgent.java+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpAgent.java@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -18,7 +18,6 @@* along with this program. If not, see <http://www.gnu.org/licenses/>.*/package org.openremote.agent.protocol.modbus;-import jakarta.persistence.Entity;import jakarta.validation.constraints.NotNull;import org.openremote.model.asset.agent.Agent;@@ -26,7 +25,7 @@ import org.openremote.model.asset.agent.AgentDescriptor;import org.openremote.model.value.AttributeDescriptor;@Entity-public class ModbusTcpAgent extends ModbusAgent<ModbusTcpAgent, ModbusTcpProtocol>{+public class ModbusTcpAgent extends ModbusAgent<ModbusTcpAgent, ModbusTcpProtocol> {public static final AgentDescriptor<ModbusTcpAgent, ModbusTcpProtocol, ModbusAgentLink> DESCRIPTOR = new AgentDescriptor<>(ModbusTcpAgent.class, ModbusTcpProtocol.class, ModbusAgentLink.classdiff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpProtocol.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpProtocol.javaindex fec40b327..d5370ac09 100644--- a/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpProtocol.java+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/ModbusTcpProtocol.java@@ -1,5 +1,5 @@/*- * Copyright 2025, OpenRemote Inc.+ * Copyright 2026, OpenRemote Inc.** See the CONTRIBUTORS.txt file in the distribution for a* full listing of individual contributors.@@ -19,36 +19,112 @@*/package org.openremote.agent.protocol.modbus;-import org.apache.plc4x.java.api.PlcConnection;-import org.apache.plc4x.java.api.PlcDriverManager;-import org.apache.plc4x.java.api.exceptions.PlcConnectionException;+import io.netty.channel.ChannelHandler;+import io.netty.handler.timeout.ReadTimeoutHandler;+import org.openremote.agent.protocol.io.AbstractNettyIOClient;+import org.openremote.agent.protocol.io.NettyIOClient;+import org.openremote.agent.protocol.modbus.util.ModbusTcpDecoder;+import org.openremote.agent.protocol.modbus.util.ModbusTcpEncoder;+import org.openremote.agent.protocol.modbus.util.ModbusTcpFrame;+import org.openremote.agent.protocol.tcp.TCPIOClient;+import org.openremote.model.asset.agent.ConnectionStatus;+import org.openremote.model.syslog.SyslogCategory;++import java.util.Map;+import java.util.concurrent.*;+import java.util.concurrent.atomic.AtomicInteger;+import java.util.function.Supplier;+import java.util.logging.Logger;++/**+ * Modbus TCP protocol implementation.+ * Handles TCP-specific transport: transaction ID correlation and full-duplex communication.+ */+public class ModbusTcpProtocol extends AbstractModbusProtocol<ModbusTcpProtocol, ModbusTcpAgent, ModbusTcpFrame> {++ public static final Logger LOG = SyslogCategory.getLogger(SyslogCategory.PROTOCOL, ModbusTcpProtocol.class);++ // Request/response correlation via transaction ID+ private final Map<Integer, CompletableFuture<ModbusTcpFrame>> pendingRequests = new ConcurrentHashMap<>();+ private final AtomicInteger transactionIdCounter = new AtomicInteger(0);-public class ModbusTcpProtocol extends AbstractModbusProtocol<ModbusTcpProtocol, ModbusTcpAgent>{public ModbusTcpProtocol(ModbusTcpAgent agent) {super(agent);}- private String connectionString;+ // ========== Transport-specific implementations ==========@Override- protected PlcConnection createIoClient(ModbusTcpAgent agent) throws RuntimeException {- PlcConnection plcConnection;- connectionString = "modbus-tcp://" + agent.getHost().orElseThrow() + ":" + agent.getPort().orElseThrow()+"?unit-identifier=" + agent.getUnitId();- try {- plcConnection = PlcDriverManager.getDefault().getConnectionManager().getConnection(connectionString);- } catch (PlcConnectionException e) {- throw new RuntimeException(e);+ protected NettyIOClient<ModbusTcpFrame> doCreateIoClient() throws Exception {+ String host = agent.getHost().orElseThrow(() -> new IllegalStateException("Host not configured"));+ int port = agent.getPort().orElseThrow(() -> new IllegalStateException("Port not configured"));+ return new TCPIOClient<>(host, port);+ }++ @Override+ protected Supplier<ChannelHandler[]> getEncoderDecoderProvider() {+ return () -> new ChannelHandler[] {+ new ReadTimeoutHandler(30, TimeUnit.SECONDS),+ new ModbusTcpEncoder(),+ new ModbusTcpDecoder(),+ new AbstractNettyIOClient.MessageToMessageDecoder<>(ModbusTcpFrame.class, client)+ };+ }++ @Override+ protected void onMessageReceived(ModbusTcpFrame frame) {+ LOG.finest(() -> "Received frame - TxID: " + frame.getTransactionId() + ", UnitID: " + frame.getUnitId() ++ ", FC: 0x" + Integer.toHexString(frame.getFunctionCode() & 0xFF));++ int txId = frame.getTransactionId();+ CompletableFuture<ModbusTcpFrame> future = pendingRequests.get(txId);+ if (future != null) {+ future.complete(frame);+ } else {+ LOG.warning("Received Modbus TCP response for unknown or timed out transaction ID: " + txId);}- return plcConnection;}@Override- public String getProtocolName() {- return "Modbus TCP Protocol";+ protected void doTransportStop() {+ pendingRequests.clear();+ }++ @Override+ public ModbusTcpFrame sendModbusRequest(int unitId, byte[] pdu, long timeoutMs) throws Exception {+ int transactionId;+ CompletableFuture<ModbusTcpFrame> responseFuture;++ synchronized (requestLock) {+ if (client == null || client.getConnectionStatus() != ConnectionStatus.CONNECTED) {+ throw new IllegalStateException("Client not connected");+ }++ transactionId = transactionIdCounter.updateAndGet(current -> (current + 1) % 65536);+ ModbusTcpFrame request = new ModbusTcpFrame(transactionId, unitId, pdu);+ responseFuture = new CompletableFuture<>();+ pendingRequests.put(transactionId, responseFuture);++ client.sendMessage(request);+ LOG.finest(() -> "Sent Modbus TCP request - TxID: " + transactionId + ", UnitID: " + unitId ++ ", FC: 0x" + Integer.toHexString(pdu[0] & 0xFF));+ }++ try {+ ModbusTcpFrame response = responseFuture.get(timeoutMs, TimeUnit.MILLISECONDS);+ LOG.finest(() -> "Received Modbus TCP response - TxID: " + response.getTransactionId() ++ ", UnitID: " + response.getUnitId() + ", FC: 0x" + Integer.toHexString(response.getFunctionCode() & 0xFF));+ return response;+ } catch (TimeoutException e) {+ LOG.warning("Modbus TCP request timeout - TxID: " + transactionId + ", UnitID: " + unitId);+ throw e;+ } finally {+ pendingRequests.remove(transactionId);+ }}@Override- public String getProtocolInstanceUri() {- return connectionString;+ public String getProtocolName() {+ return "Modbus TCP";}}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/BatchReadRequest.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/BatchReadRequest.javanew file mode 100644index 000000000..ace76eb82--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/BatchReadRequest.java@@ -0,0 +1,82 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++import org.openremote.model.attribute.AttributeRef;++import java.util.ArrayList;+import java.util.List;++/**+ * Represents a batched Modbus read request that combines multiple attribute reads+ * into a single register read operation for efficiency.+ */+public class BatchReadRequest {+ private final int startAddress;+ private int quantity;+ private final List<AttributeRef> attributes;+ private final List<Integer> offsets; // Offset of each attribute within the batch++ public BatchReadRequest(int startAddress, int quantity) {+ this.startAddress = startAddress;+ this.quantity = quantity;+ this.attributes = new ArrayList<>();+ this.offsets = new ArrayList<>();+ }++ public int getStartAddress() {+ return startAddress;+ }++ public int getQuantity() {+ return quantity;+ }++ public void setQuantity(int quantity) {+ this.quantity = quantity;+ }++ public List<AttributeRef> getAttributes() {+ return attributes;+ }++ public List<Integer> getOffsets() {+ return offsets;+ }++ /**+ * Add an attribute to this batch read request.+ * @param ref the attribute reference+ * @param offset the offset within the batch (in registers/coils from startAddress)+ */+ public void addAttribute(AttributeRef ref, int offset) {+ attributes.add(ref);+ offsets.add(offset);+ }++ @Override+ public String toString() {+ return "BatchReadRequest{" ++ "startAddress=" + startAddress ++ ", quantity=" + quantity ++ ", attributeCount=" + attributes.size() ++ '}';+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusDataConverter.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusDataConverter.javanew file mode 100644index 000000000..51cdaca01--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusDataConverter.java@@ -0,0 +1,281 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++import org.openremote.agent.protocol.modbus.ModbusAgent;+import org.openremote.agent.protocol.modbus.ModbusAgentLink;+import org.openremote.model.syslog.SyslogCategory;++import java.math.BigInteger;+import java.nio.ByteBuffer;+import java.nio.ByteOrder;+import java.util.logging.Level;+import java.util.logging.Logger;++import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;++/**+ * Utility class for converting between Modbus register data and Java values.+ */+public final class ModbusDataConverter {++ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, ModbusDataConverter.class);++ private ModbusDataConverter() {+ // Utility class+ }++ /**+ * Extract a value from a batch response at the specified offset.+ * @param data the response data bytes+ * @param offset the offset in registers/coils+ * @param registerCount the number of registers for this value+ * @param dataType the Modbus data type+ * @param endianFormat the endian format to use+ * @param functionCode the function code (determines coil vs register)+ * @return the extracted value, or null if extraction fails+ */+ public static Object extractValueFromBatchResponse(byte[] data, int offset, int registerCount,+ ModbusAgentLink.ModbusDataType dataType,+ ModbusAgent.EndianFormat endianFormat,+ byte functionCode) {+ try {+ // For coils and discrete inputs, data is bit-packed+ if (functionCode == 0x01 || functionCode == 0x02) {+ int byteIndex = offset / 8;+ int bitIndex = offset % 8;+ if (byteIndex < data.length) {+ return ((data[byteIndex] >> bitIndex) & 0x01) == 1;+ }+ return null;+ }++ // For registers (holding/input), data is word-based (2 bytes per register)+ int byteOffset = offset * 2;+ if (byteOffset + (registerCount * 2) > data.length) {+ LOG.warning("Not enough data in response: need " + (byteOffset + registerCount * 2) + " bytes, have " + data.length);+ return null;+ }++ // Extract register bytes+ byte[] registerBytes = new byte[registerCount * 2];+ System.arraycopy(data, byteOffset, registerBytes, 0, registerBytes.length);++ // Parse multi-register value+ return parseMultiRegisterValue(registerBytes, registerCount, dataType, endianFormat);+ } catch (Exception e) {+ LOG.log(Level.WARNING, "Failed to extract value from batch response at offset " + offset + ": " + e.getMessage(), e);+ return null;+ }+ }++ /**+ * Convert a Java value to register bytes for writing.+ * @param value the value to convert+ * @param registerCount the number of registers+ * @param dataType the Modbus data type+ * @param endianFormat the endian format to use+ * @return the register bytes+ */+ public static byte[] convertValueToRegisterBytes(Object value, int registerCount,+ ModbusAgentLink.ModbusDataType dataType,+ ModbusAgent.EndianFormat endianFormat) {+ byte[] bytes = new byte[registerCount * 2];+ ByteBuffer buffer = ByteBuffer.wrap(bytes);++ // Apply byte order+ buffer.order(endianFormat == ModbusAgent.EndianFormat.BIG_ENDIAN ||+ endianFormat == ModbusAgent.EndianFormat.BIG_ENDIAN_BYTE_SWAP+ ? ByteOrder.BIG_ENDIAN : ByteOrder.LITTLE_ENDIAN);++ // Convert based on register count and data type+ if (registerCount == 1) {+ // Single register (16-bit)+ if (value instanceof Number) {+ int intValue = ((Number) value).intValue();+ buffer.putShort((short) (intValue & 0xFFFF));+ } else {+ throw new IllegalArgumentException("Cannot convert value to register: " + value);+ }+ } else if (registerCount == 2) {+ // Two registers (32-bit int or float)+ if (dataType == ModbusAgentLink.ModbusDataType.REAL) {+ buffer.putFloat(((Number) value).floatValue());+ } else if (value instanceof Number) {+ buffer.putInt(((Number) value).intValue());+ } else {+ throw new IllegalArgumentException("Cannot convert value to 2 registers: " + value);+ }+ } else if (registerCount == 4) {+ // Four registers (64-bit int or double)+ if (dataType == ModbusAgentLink.ModbusDataType.LREAL) {+ buffer.putDouble(((Number) value).doubleValue());+ } else if (value instanceof Number) {+ buffer.putLong(((Number) value).longValue());+ } else {+ throw new IllegalArgumentException("Cannot convert value to 4 registers: " + value);+ }+ } else {+ throw new IllegalArgumentException("Unsupported register count for write: " + registerCount);+ }++ // Apply word order (byte swap for multi-register values)+ if (registerCount > 1 && (endianFormat == ModbusAgent.EndianFormat.BIG_ENDIAN_BYTE_SWAP ||+ endianFormat == ModbusAgent.EndianFormat.LITTLE_ENDIAN_BYTE_SWAP)) {+ bytes = applyWordOrder(bytes, registerCount, endianFormat);+ }++ return bytes;+ }++ /**+ * Apply word order transformation for byte-swap endian formats.+ * @param data the data bytes+ * @param registerCount the number of registers+ * @param format the endian format+ * @return the transformed bytes+ */+ public static byte[] applyWordOrder(byte[] data, int registerCount, ModbusAgent.EndianFormat format) {+ // No swap for single register or non-byte-swap formats+ if (registerCount <= 1 || format == ModbusAgent.EndianFormat.BIG_ENDIAN || format == ModbusAgent.EndianFormat.LITTLE_ENDIAN) {+ return data;+ }+ // BYTE_SWAP - swap word order+ byte[] result = new byte[data.length];+ for (int i = 0; i < registerCount; i++) {+ int srcIdx = i * 2;+ int dstIdx = (registerCount - 1 - i) * 2;+ result[dstIdx] = data[srcIdx];+ result[dstIdx + 1] = data[srcIdx + 1];+ }+ return result;+ }++ /**+ * Parse a multi-register value from bytes.+ * @param dataBytes the register bytes+ * @param registerCount the number of registers+ * @param dataType the Modbus data type+ * @param endianFormat the endian format+ * @return the parsed value+ */+ public static Object parseMultiRegisterValue(byte[] dataBytes, int registerCount,+ ModbusAgentLink.ModbusDataType dataType,+ ModbusAgent.EndianFormat endianFormat) {+ if (registerCount == 1) {+ // Single 16-bit register - interpret based on dataType+ int high = (dataBytes[0] & 0xFF) << 8;+ int low = dataBytes[1] & 0xFF;+ int unsignedValue = high | low;++ return switch (dataType) {+ case BOOL -> unsignedValue != 0;+ case SINT -> {+ // Signed 8-bit: use low byte only, sign-extend+ yield (int) (byte) low;+ }+ case USINT, BYTE -> {+ // Unsigned 8-bit: use low byte only+ yield low;+ }+ case INT -> {+ // Signed 16-bit: sign-extend to int+ yield (int) (short) unsignedValue;+ }+ case UINT, WORD -> {+ // Unsigned 16-bit+ yield unsignedValue;+ }+ case CHAR -> (char) (unsignedValue & 0xFF);+ case WCHAR -> String.valueOf((char) unsignedValue);+ default -> unsignedValue; // Fallback to unsigned+ };+ } else if (registerCount == 2) {+ // Two registers - could be IEEE754 float or 32-bit integer+ byte[] processedBytes = applyWordOrder(dataBytes, 2, endianFormat);+ ByteBuffer buffer = ByteBuffer.wrap(processedBytes);+ buffer.order(getJavaByteOrder(endianFormat));++ return switch (dataType) {+ case REAL -> {+ float value = buffer.getFloat();+ // Filter out NaN and Infinity values+ if (Float.isNaN(value) || Float.isInfinite(value)) {+ LOG.warning("Invalid float value (NaN or Infinity), ignoring");+ yield null;+ }+ yield value;+ }+ case DINT -> {+ // Signed 32-bit integer+ yield buffer.getInt();+ }+ case UDINT, DWORD -> {+ // Unsigned 32-bit integer - return as long to preserve full range+ yield buffer.getInt() & 0xFFFFFFFFL;+ }+ default -> buffer.getInt(); // Fallback to signed 32-bit+ };+ } else if (registerCount == 4) {+ // Four registers - could be 64-bit integer or double precision float+ byte[] processedBytes = applyWordOrder(dataBytes, 4, endianFormat);+ ByteBuffer buffer = ByteBuffer.wrap(processedBytes);+ buffer.order(getJavaByteOrder(endianFormat));++ return switch (dataType) {+ case LREAL -> {+ double value = buffer.getDouble();+ if (Double.isNaN(value) || Double.isInfinite(value)) {+ LOG.warning("Invalid double value (NaN or Infinity), ignoring");+ yield null;+ }+ yield value;+ }+ case LINT -> {+ // Signed 64-bit integer+ yield buffer.getLong();+ }+ case ULINT, LWORD -> {+ // Unsigned 64-bit integer - return as BigInteger to preserve full range+ long signedValue = buffer.getLong();+ if (signedValue >= 0) {+ yield BigInteger.valueOf(signedValue);+ } else {+ yield BigInteger.valueOf(signedValue).add(BigInteger.ONE.shiftLeft(64));+ }+ }+ default -> buffer.getLong(); // Fallback to signed 64-bit+ };+ }++ return null;+ }++ /**+ * Get the Java ByteOrder for a Modbus endian format.+ * @param format the endian format+ * @return the corresponding ByteOrder+ */+ public static ByteOrder getJavaByteOrder(ModbusAgent.EndianFormat format) {+ return (format == ModbusAgent.EndianFormat.BIG_ENDIAN || format == ModbusAgent.EndianFormat.BIG_ENDIAN_BYTE_SWAP)+ ? ByteOrder.BIG_ENDIAN+ : ByteOrder.LITTLE_ENDIAN;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusFrame.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusFrame.javanew file mode 100644index 000000000..0cda76e71--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusFrame.java@@ -0,0 +1,51 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++/**+ * Interface representing a Modbus frame (response).+ * Implemented by both ModbusTcpFrame and ModbusSerialFrame.+ */+public interface ModbusFrame {++ /**+ * Check if this frame represents a Modbus exception response.+ * @return true if the function code has the exception bit set (0x80)+ */+ boolean isException();++ /**+ * Get the Protocol Data Unit (PDU) of the frame.+ * @return the PDU bytes (function code + data)+ */+ byte[] getPdu();++ /**+ * Get the unit/slave ID this frame is addressed to.+ * @return the unit ID+ */+ int getUnitId();++ /**+ * Get the Modbus function code from the PDU.+ * @return the function code byte+ */+ byte getFunctionCode();+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusPduBuilder.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusPduBuilder.javanew file mode 100644index 000000000..185f79714--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusPduBuilder.java@@ -0,0 +1,140 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++/**+ * Utility class for building and parsing Modbus Protocol Data Units (PDUs).+ */+public final class ModbusPduBuilder {++ private ModbusPduBuilder() {+ // Utility class+ }++ /**+ * Build a read request PDU.+ * @param functionCode the function code (0x01-0x04)+ * @param startAddress the starting address (0-based)+ * @param quantity the number of registers/coils to read+ * @return the PDU bytes+ */+ public static byte[] buildReadRequestPDU(byte functionCode, int startAddress, int quantity) {+ byte[] pdu = new byte[5];+ pdu[0] = functionCode;+ pdu[1] = (byte) (startAddress >> 8);+ pdu[2] = (byte) (startAddress & 0xFF);+ pdu[3] = (byte) (quantity >> 8);+ pdu[4] = (byte) (quantity & 0xFF);+ return pdu;+ }++ /**+ * Build a write single coil PDU (function code 0x05).+ * @param address the coil address (0-based)+ * @param value true for ON, false for OFF+ * @return the PDU bytes+ */+ public static byte[] buildWriteSingleCoilPDU(int address, boolean value) {+ byte[] pdu = new byte[5];+ pdu[0] = (byte) 0x05;+ pdu[1] = (byte) (address >> 8);+ pdu[2] = (byte) (address & 0xFF);+ pdu[3] = value ? (byte) 0xFF : (byte) 0x00;+ pdu[4] = (byte) 0x00;+ return pdu;+ }++ /**+ * Build a write single register PDU (function code 0x06).+ * @param address the register address (0-based)+ * @param value the 16-bit value to write+ * @return the PDU bytes+ */+ public static byte[] buildWriteSingleRegisterPDU(int address, int value) {+ byte[] pdu = new byte[5];+ pdu[0] = (byte) 0x06;+ pdu[1] = (byte) (address >> 8);+ pdu[2] = (byte) (address & 0xFF);+ pdu[3] = (byte) (value >> 8);+ pdu[4] = (byte) (value & 0xFF);+ return pdu;+ }++ /**+ * Build a write multiple registers PDU (function code 0x10).+ * @param startAddress the starting address (0-based)+ * @param registerData the register data bytes (2 bytes per register)+ * @return the PDU bytes+ */+ public static byte[] buildWriteMultipleRegistersPDU(int startAddress, byte[] registerData) {+ int registerCount = registerData.length / 2;+ byte[] pdu = new byte[6 + registerData.length];+ pdu[0] = (byte) 0x10;+ pdu[1] = (byte) (startAddress >> 8);+ pdu[2] = (byte) (startAddress & 0xFF);+ pdu[3] = (byte) (registerCount >> 8);+ pdu[4] = (byte) (registerCount & 0xFF);+ pdu[5] = (byte) registerData.length;+ System.arraycopy(registerData, 0, pdu, 6, registerData.length);+ return pdu;+ }++ /**+ * Extract data bytes from a response PDU.+ * @param responsePDU the response PDU+ * @param functionCode the expected function code+ * @return the data bytes, or null if invalid+ */+ public static byte[] extractDataFromResponsePDU(byte[] responsePDU, byte functionCode) {+ if (responsePDU == null || responsePDU.length < 2) {+ return null;+ }++ // Response format: [Function Code][Byte Count][Data...]+ int byteCount = responsePDU[1] & 0xFF;+ if (responsePDU.length < 2 + byteCount) {+ return null;+ }++ byte[] data = new byte[byteCount];+ System.arraycopy(responsePDU, 2, data, 0, byteCount);+ return data;+ }++ /**+ * Get a human-readable description for a Modbus exception code.+ * @param exceptionCode the exception code byte+ * @return the description string+ */+ public static String getModbusExceptionDescription(byte exceptionCode) {+ return switch (exceptionCode & 0xFF) {+ case 0x01 -> "Response code: Illegal Function";+ case 0x02 -> "Response code: Illegal Data Address";+ case 0x03 -> "Response code: Illegal Data Value";+ case 0x04 -> "Response code: Slave Device Failure";+ case 0x05 -> "Response code: Acknowledge (request in queue)";+ case 0x06 -> "Response code: Slave Device Busy";+ case 0x08 -> "Response code: Memory Parity Error";+ case 0x0A -> "Response code: Gateway Path Unavailable";+ case 0x0B -> "Response code: Gateway Target Device Failed to Respond";+ default -> "Response code: Unknown Exception";+ };+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusRTUDecoder.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusRTUDecoder.javanew file mode 100644index 000000000..285cd41ff--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusRTUDecoder.java@@ -0,0 +1,127 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++import io.netty.buffer.ByteBuf;+import io.netty.channel.ChannelHandlerContext;+import io.netty.handler.codec.ByteToMessageDecoder;+import org.openremote.model.syslog.SyslogCategory;+import java.util.List;+import java.util.logging.Logger;++import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;++/**+ * Decodes Modbus RTU frames from bytes.+ * Frame format: [Unit ID (1 byte)][PDU (variable)][CRC16 (2 bytes)]+ */+public class ModbusRTUDecoder extends ByteToMessageDecoder {++ private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, ModbusRTUDecoder.class);++ @Override+ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {+ // Need at least 4 bytes: Unit ID (1) + Function Code (1) + CRC (2)+ if (in.readableBytes() < 4) {+ return;+ }++ in.markReaderIndex();++ int unitId = in.getUnsignedByte(in.readerIndex());+ int functionCode = in.getUnsignedByte(in.readerIndex() + 1);+ int expectedLength = determineExpectedLength(in, functionCode);++ if (expectedLength < 0) {+ return;+ }++ if (in.readableBytes() < expectedLength) {+ // Wait for complete frame+ in.resetReaderIndex();+ return;+ }++ // Read complete frame+ byte[] frameBytes = new byte[expectedLength];+ in.readBytes(frameBytes);++ if (!ModbusSerialFrame.isValidCRC(frameBytes)) {+ LOG.warning("Invalid CRC in Modbus RTU frame, discarding: UnitId=" + unitId ++ ", FunctionCode=0x" + Integer.toHexString(functionCode));+ return;+ }++ ModbusSerialFrame frame = ModbusSerialFrame.fromBytes(frameBytes);+ if (frame != null) {+ out.add(frame);+ LOG.finest("Decoded Modbus RTU frame: " + frame);+ }+ }++ private int determineExpectedLength(ByteBuf in, int functionCode) {+ // For exception responses (function code with 0x80 bit set)+ if ((functionCode & 0x80) != 0) {+ // Exception response: Unit ID + Function Code + Exception Code + CRC = 5 bytes+ return 5;+ }++ // For normal responses, we need to read the byte count field+ switch (functionCode) {+ case 0x01: // Read Coils+ case 0x02: // Read Discrete Inputs+ case 0x03: // Read Holding Registers+ case 0x04: // Read Input Registers+ // Response format: Unit ID + FC + Byte Count + Data + CRC+ if (in.readableBytes() >= 3) {+ int byteCount = in.getUnsignedByte(in.readerIndex() + 2);+ return 1 + 1 + 1 + byteCount + 2; // Unit ID + FC + Byte Count + Data + CRC+ }+ return -1; // Need more data++ case 0x05: // Write Single Coil+ case 0x06: // Write Single Register+ // Response format: Unit ID + FC + Address (2) + Value (2) + CRC = 8 bytes+ return 8;++ case 0x0F: // Write Multiple Coils+ case 0x10: // Write Multiple Registers+ // Response format: Unit ID + FC + Address (2) + Quantity (2) + CRC = 8 bytes+ return 8;++ case 0x16: // Mask Write Register+ // Response format: Unit ID + FC + Address (2) + AND Mask (2) + OR Mask (2) + CRC = 10 bytes+ return 10;++ case 0x17: // Read/Write Multiple Registers+ // Response format: Unit ID + FC + Byte Count + Data + CRC+ if (in.readableBytes() >= 3) {+ int byteCount = in.getUnsignedByte(in.readerIndex() + 2);+ return 1 + 1 + 1 + byteCount + 2;+ }+ return -1;++ default:+ LOG.warning("Unknown Modbus function code: 0x" + Integer.toHexString(functionCode));+ // Try to read a reasonable minimum frame+ return -1;+ }+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusRTUEncoder.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusRTUEncoder.javanew file mode 100644index 000000000..975da7419--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusRTUEncoder.java@@ -0,0 +1,36 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++import io.netty.buffer.ByteBuf;+import io.netty.channel.ChannelHandlerContext;+import io.netty.handler.codec.MessageToByteEncoder;++/**+ * Encodes Modbus RTU frames to bytes (Unit ID + PDU + CRC16)+ */+public class ModbusRTUEncoder extends MessageToByteEncoder<ModbusSerialFrame> {++ @Override+ protected void encode(ChannelHandlerContext ctx, ModbusSerialFrame frame, ByteBuf out) throws Exception {+ byte[] frameBytes = frame.pack();+ out.writeBytes(frameBytes);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusSerialFrame.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusSerialFrame.javanew file mode 100644index 000000000..1ac33cf06--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusSerialFrame.java@@ -0,0 +1,118 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++/**+ * Represents a Modbus RTU frame (Unit ID + PDU + CRC16)+ */+public class ModbusSerialFrame implements ModbusFrame {+ private final int unitId;+ private final byte[] pdu;+ private byte[] fullFrame; // Cached full frame with CRC++ public ModbusSerialFrame(int unitId, byte[] pdu) {+ this.unitId = unitId;+ this.pdu = pdu;+ }++ public static ModbusSerialFrame fromBytes(byte[] frameBytes) {+ if (frameBytes == null || frameBytes.length < 4) {+ // Minimum: 1 byte unit ID + 1 byte function code + 2 bytes CRC+ return null;+ }++ int unitId = frameBytes[0] & 0xFF;+ int pduLength = frameBytes.length - 3; // Exclude unit ID and 2-byte CRC+ byte[] pdu = new byte[pduLength];+ System.arraycopy(frameBytes, 1, pdu, 0, pduLength);++ return new ModbusSerialFrame(unitId, pdu);+ }++ public int getUnitId() {+ return unitId;+ }++ public byte[] getPdu() {+ return pdu;+ }++ public byte getFunctionCode() {+ return pdu != null && pdu.length > 0 ? pdu[0] : 0;+ }++ public boolean isException() {+ return pdu != null && pdu.length > 0 && (pdu[0] & 0x80) != 0;+ }++ public byte[] pack() {+ if (fullFrame != null) {+ return fullFrame;+ }++ fullFrame = new byte[1 + pdu.length + 2];+ fullFrame[0] = (byte) unitId;+ System.arraycopy(pdu, 0, fullFrame, 1, pdu.length);++ int crc = calculateCRC16(fullFrame, 0, 1 + pdu.length);+ fullFrame[1 + pdu.length] = (byte) (crc & 0xFF); // CRC Low+ fullFrame[2 + pdu.length] = (byte) ((crc >> 8) & 0xFF); // CRC High++ return fullFrame;+ }++ public static boolean isValidCRC(byte[] frameBytes) {+ if (frameBytes == null || frameBytes.length < 4) {+ return false;+ }++ int receivedCRC = (frameBytes[frameBytes.length - 2] & 0xFF) |+ ((frameBytes[frameBytes.length - 1] & 0xFF) << 8);+ int calculatedCRC = calculateCRC16(frameBytes, 0, frameBytes.length - 2);++ return receivedCRC == calculatedCRC;+ }++ private static int calculateCRC16(byte[] data, int offset, int length) {+ int crc = 0xFFFF;+ for (int i = offset; i < offset + length; i++) {+ crc ^= (data[i] & 0xFF);+ for (int j = 0; j < 8; j++) {+ if ((crc & 1) != 0) {+ crc = (crc >> 1) ^ 0xA001;+ } else {+ crc = crc >> 1;+ }+ }+ }+ return crc;+ }++ @Override+ public String toString() {+ StringBuilder sb = new StringBuilder();+ sb.append("ModbusSerialFrame{unitId=").append(unitId);+ sb.append(", functionCode=0x").append(String.format("%02X", getFunctionCode()));+ sb.append(", pduLength=").append(pdu.length);+ sb.append(", exception=").append(isException());+ sb.append("}");+ return sb.toString();+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpDecoder.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpDecoder.javanew file mode 100644index 000000000..f90e0f703--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpDecoder.java@@ -0,0 +1,72 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++import io.netty.buffer.ByteBuf;+import io.netty.channel.ChannelHandlerContext;+import org.openremote.model.syslog.SyslogCategory;+import java.util.List;+import java.util.logging.Logger;++import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;++public class ModbusTcpDecoder extends io.netty.handler.codec.ByteToMessageDecoder {++ public static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, ModbusTcpDecoder.class);++ @Override+ protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) {+ // Need at least 7 bytes for MBAP header+ if (in.readableBytes() < 7) {+ return;+ }++ in.markReaderIndex();++ // Read MBAP header+ int transactionId = in.readUnsignedShort();+ int protocolId = in.readUnsignedShort();+ int length = in.readUnsignedShort();+ int unitId = in.readUnsignedByte();+ int pduLength = length - 1; // Length includes unit ID++ if (pduLength <= 0) {+ LOG.warning("Received Modbus TCP frame with invalid length: " + length);+ return;+ }++ if (in.readableBytes() < pduLength) {+ // Not enough data yet, reset and wait+ in.resetReaderIndex();+ return;+ }++ byte[] pdu = new byte[pduLength];+ in.readBytes(pdu);++ ModbusTcpFrame frame = new ModbusTcpFrame(transactionId, protocolId, length, unitId, pdu);++ LOG.finest(() -> String.format("Decoded Modbus TCP frame: TxID=%d, UnitID=%d, FC=0x%02X, PDU length=%d, Exception=%b",+ frame.getTransactionId(), frame.getUnitId(), frame.getFunctionCode(),+ frame.getPdu().length, frame.isException()));++ out.add(frame);+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpEncoder.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpEncoder.javanew file mode 100644index 000000000..cbe4f104c--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpEncoder.java@@ -0,0 +1,49 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++import io.netty.buffer.ByteBuf;+import io.netty.channel.ChannelHandlerContext;+import org.openremote.model.syslog.SyslogCategory;+import java.util.logging.Logger;+import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;++public class ModbusTcpEncoder extends io.netty.handler.codec.MessageToByteEncoder<ModbusTcpFrame> {++ public static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, ModbusTcpEncoder.class);++ @Override+ protected void encode(ChannelHandlerContext ctx, ModbusTcpFrame frame, ByteBuf out) {+ // MBAP Header (7 bytes)+ out.writeShort(frame.getTransactionId()); // Transaction ID+ out.writeShort(frame.getProtocolId()); // Protocol ID (0 for Modbus)+ out.writeShort(frame.getLength()); // Length (Unit ID + PDU)+ out.writeByte(frame.getUnitId()); // Unit ID++ // PDU+ if (frame.getPdu() != null) {+ out.writeBytes(frame.getPdu());+ }++ LOG.finest(() -> String.format("Encoded Modbus TCP frame: TxID=%d, UnitID=%d, FC=0x%02X, PDU length=%d",+ frame.getTransactionId(), frame.getUnitId(), frame.getFunctionCode(),+ frame.getPdu() != null ? frame.getPdu().length : 0));+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpFrame.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpFrame.javanew file mode 100644index 000000000..29aedb389--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/ModbusTcpFrame.java@@ -0,0 +1,81 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++/**+ * Represents a Modbus TCP frame (MBAP header + PDU)+ */+public class ModbusTcpFrame implements ModbusFrame {+ private final int transactionId;+ private final int protocolId;+ private final int length;+ private final int unitId;+ private final byte[] pdu;++ public ModbusTcpFrame(int transactionId, int unitId, byte[] pdu) {+ this.transactionId = transactionId;+ this.protocolId = 0; // Always 0 for Modbus TCP+ this.length = 1 + pdu.length; // Unit ID + PDU+ this.unitId = unitId;+ this.pdu = pdu;+ }++ public ModbusTcpFrame(int transactionId, int protocolId, int length, int unitId, byte[] pdu) {+ this.transactionId = transactionId;+ this.protocolId = protocolId;+ this.length = length;+ this.unitId = unitId;+ this.pdu = pdu;+ }++ public int getTransactionId() {+ return transactionId;+ }++ public int getProtocolId() {+ return protocolId;+ }++ public int getLength() {+ return length;+ }++ public int getUnitId() {+ return unitId;+ }++ public byte[] getPdu() {+ return pdu;+ }++ public byte getFunctionCode() {+ return pdu != null && pdu.length > 0 ? pdu[0] : 0;+ }++ public boolean isException() {+ return pdu != null && pdu.length > 0 && (pdu[0] & 0x80) != 0;+ }++ @Override+ public String toString() {+ return String.format("ModbusTcpFrame{txId=%d, unitId=%d, fc=0x%02X, pduLen=%d, exception=%b}",+ transactionId, unitId, getFunctionCode(), pdu != null ? pdu.length : 0, isException());+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/modbus/util/RegisterRange.java b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/RegisterRange.javanew file mode 100644index 000000000..fb517227b--- /dev/null+++ b/agent/src/main/java/org/openremote/agent/protocol/modbus/util/RegisterRange.java@@ -0,0 +1,68 @@+/*+ * Copyright 2026, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.agent.protocol.modbus.util;++/**+ * Represents a range of Modbus registers (used for defining illegal/inaccessible registers).+ */+public class RegisterRange {+ private final int start;+ private final int end;++ public RegisterRange(int start, int end) {+ this.start = start;+ this.end = end;+ }++ public int getStart() {+ return start;+ }++ public int getEnd() {+ return end;+ }++ /**+ * Check if a register address falls within this range.+ * @param register the register address to check+ * @return true if the register is within [start, end] inclusive+ */+ public boolean contains(int register) {+ return register >= start && register <= end;+ }++ @Override+ public String toString() {+ return "RegisterRange{" + start + "-" + end + "}";+ }++ @Override+ public boolean equals(Object o) {+ if (this == o) return true;+ if (o == null || getClass() != o.getClass()) return false;+ RegisterRange that = (RegisterRange) o;+ return start == that.start && end == that.end;+ }++ @Override+ public int hashCode() {+ return 31 * start + end;+ }+}diff --git a/agent/src/main/java/org/openremote/agent/protocol/serial/SerialIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/serial/SerialIOClient.javaindex 9cad0bcc6..9e0851258 100644--- a/agent/src/main/java/org/openremote/agent/protocol/serial/SerialIOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/serial/SerialIOClient.java@@ -40,16 +40,26 @@ import static org.openremote.agent.protocol.serial.JSerialCommChannelOption.*;* to this client via {@link AbstractNettyIOClient#onMessageReceived} (see {@link ByteToMessageDecoder} and* {@link MessageToMessageDecoder}).*/-public class SerialIOClient<T> extends AbstractNettyIOClient<T, JSerialCommDeviceAddress> {+public class SerialIOClient<T> extends AbstractNettyIOClient<T> {protected String port;protected int baudRate;+ protected int dataBits;+ protected JSerialCommChannelConfig.Stopbits stopBits;+ protected JSerialCommChannelConfig.Paritybit parity;public static int DEFAULT_BAUD_RATE = 38400;public SerialIOClient(String port, Integer baudRate) {+ this(port, baudRate, 8, STOPBITS_1, NONE);+ }++ public SerialIOClient(String port, Integer baudRate, int dataBits, JSerialCommChannelConfig.Stopbits stopBits, JSerialCommChannelConfig.Paritybit parity) {TextUtil.requireNonNullAndNonEmpty(port);this.port = port;this.baudRate = baudRate == null ? DEFAULT_BAUD_RATE : baudRate;+ this.dataBits = dataBits;+ this.stopBits = stopBits;+ this.parity = parity;}@Override@@ -79,8 +89,8 @@ public class SerialIOClient<T> extends AbstractNettyIOClient<T, JSerialCommDevicprotected void configureChannel() {super.configureChannel();bootstrap.option(BAUD_RATE, baudRate);- bootstrap.option(DATA_BITS, 8);- bootstrap.option(STOP_BITS, STOPBITS_1);- bootstrap.option(PARITY_BIT, NONE);+ bootstrap.option(DATA_BITS, dataBits);+ bootstrap.option(STOP_BITS, stopBits);+ bootstrap.option(PARITY_BIT, parity);}}diff --git a/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPIOClient.javaindex 96d78e74b..5f7727a2c 100644--- a/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPIOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/tcp/TCPIOClient.java@@ -38,7 +38,7 @@ import java.util.concurrent.CompletableFuture;* to this client via {@link AbstractNettyIOClient#onMessageReceived} (see {@link ByteToMessageDecoder} and* {@link MessageToMessageDecoder}).*/-public class TCPIOClient<T> extends AbstractNettyIOClient<T, InetSocketAddress> {+public class TCPIOClient<T> extends AbstractNettyIOClient<T> {protected String host;protected int port;diff --git a/agent/src/main/java/org/openremote/agent/protocol/udp/UDPIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/udp/UDPIOClient.javaindex 52f8864e6..845ed60c3 100644--- a/agent/src/main/java/org/openremote/agent/protocol/udp/UDPIOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/udp/UDPIOClient.java@@ -45,7 +45,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;* to this client via {@link AbstractNettyIOClient#onMessageReceived} (see {@link ByteToMessageDecoder} and* {@link MessageToMessageDecoder}).*/-public class UDPIOClient<T> extends AbstractNettyIOClient<T, InetSocketAddress> {+public class UDPIOClient<T> extends AbstractNettyIOClient<T> {private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, UDPIOClient.class);protected String host;diff --git a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.javaindex a0192f329..0dd6d373c 100644--- a/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java+++ b/agent/src/main/java/org/openremote/agent/protocol/websocket/WebsocketIOClient.java@@ -63,7 +63,7 @@ import static org.openremote.model.syslog.SyslogCategory.PROTOCOL;* For custom decoders, the initial message type is of type {@link String}.* For custom encoders, the final message type must be of type {@link String}.*/-public class WebsocketIOClient<T> extends AbstractNettyIOClient<T, InetSocketAddress> {+public class WebsocketIOClient<T> extends AbstractNettyIOClient<T> {private static final Logger LOG = SyslogCategory.getLogger(PROTOCOL, WebsocketIOClient.class);protected static ResteasyClient client;diff --git a/gradle.properties b/gradle.propertiesindex 1f1eb702c..6407fd0bb 100644--- a/gradle.properties+++ b/gradle.properties@@ -50,7 +50,6 @@ typescriptGeneratorVersion = 3.2.1263californiumCoreVersion = 3.14.0californiumScandiumVersion = 3.14.0zwaveVersion = 3.4.0-plc4xVersion = 0.12.0niftyModbusVersion = 0.17.0reflectionsVersion=0.10.2swaggerVersion=2.2.45diff --git a/test/build.gradle b/test/build.gradleindex 4539e9182..226c5f9c1 100644--- a/test/build.gradle+++ b/test/build.gradle@@ -19,7 +19,8 @@ dependencies {api 'org.spockframework:spock-core'// optional dependencies for using Spock- testRuntimeOnly "net.bytebuddy:byte-buddy:$byteBuddyVersion" // allows mocking of classes (in addition to interfaces)+ testImplementation "net.bytebuddy:byte-buddy:$byteBuddyVersion" // allows mocking of classes (in addition to interfaces)+ testImplementation "net.bytebuddy:byte-buddy-agent:$byteBuddyVersion" // for runtime class redefinitiontestRuntimeOnly "org.objenesis:objenesis:$objenesisVersion" // allows mocking of classes without default constructor (together with ByteBuddy or CGLIB)testImplementation("com.github.calimero:calimero-server:$calimeroVersion") {diff --git a/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusBasicTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusBasicTest.groovydeleted file mode 100644index d69d60994..000000000--- a/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusBasicTest.groovy+++ /dev/null@@ -1,276 +0,0 @@-/*- * Copyright 2025, OpenRemote Inc.- *- * See the CONTRIBUTORS.txt file in the distribution for a- * full listing of individual contributors.- *- * This program is free software: you can redistribute it and/or modify- * it under the terms of the GNU Affero General Public License as- * published by the Free Software Foundation, either version 3 of the- * License, or (at your option) any later version.- *- * This program is distributed in the hope that it will be useful,- * but WITHOUT ANY WARRANTY; without even the implied warranty of- * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the- * GNU Affero General Public License for more details.- *- * You should have received a copy of the GNU Affero General Public License- * along with this program. If not, see <http://www.gnu.org/licenses/>.- */-package org.openremote.test.protocol.modbus--import net.solarnetwork.io.modbus.BitsModbusMessage-import net.solarnetwork.io.modbus.ModbusBlockType-import net.solarnetwork.io.modbus.ModbusErrorCode-import net.solarnetwork.io.modbus.ModbusFunctionCode-import net.solarnetwork.io.modbus.ModbusMessage-import net.solarnetwork.io.modbus.RegistersModbusMessage-import net.solarnetwork.io.modbus.netty.msg.BaseModbusMessage-import net.solarnetwork.io.modbus.tcp.netty.NettyTcpModbusServer-import org.openremote.agent.protocol.modbus.ModbusAgentLink-import org.openremote.agent.protocol.modbus.ModbusTcpAgent-import org.openremote.agent.protocol.modbus.ModbusTcpProtocol-import org.openremote.manager.agent.AgentService-import org.openremote.manager.asset.AssetProcessingService-import org.openremote.manager.asset.AssetStorageService-import org.openremote.model.asset.agent.Agent-import org.openremote.model.asset.agent.ConnectionStatus-import org.openremote.model.asset.impl.ShipAsset-import org.openremote.model.attribute.Attribute-import org.openremote.model.attribute.AttributeEvent-import org.openremote.model.attribute.MetaItem-import org.openremote.model.attribute.MetaMap-import org.openremote.model.value.ValueType-import org.openremote.test.ManagerContainerTrait-import spock.lang.Shared-import spock.lang.Specification-import spock.util.concurrent.PollingConditions--import java.util.concurrent.atomic.AtomicReference--import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_COIL-import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_COILS-import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_HOLDING_REGISTER-import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_HOLDING_REGISTERS-import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.readCoilsResponse-import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.readDiscretesResponse-import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.writeCoilResponse-import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.writeCoilsResponse-import static net.solarnetwork.io.modbus.netty.msg.RegistersModbusMessage.*-import static org.openremote.model.Constants.MASTER_REALM-import static org.openremote.model.value.MetaItemType.AGENT_LINK--class ModbusBasicTest extends Specification implements ManagerContainerTrait {-- @Shared- int modbusServerPort-- @Shared- NettyTcpModbusServer server-- @Shared- AtomicReference<ModbusMessage> latestReadMessage = new AtomicReference(null)-- @Shared- AtomicReference<ModbusMessage> latestWriteMessage = new AtomicReference(null)-// @Shared-// Map<, Number> messageMap = [:]-- def setupSpec() {- modbusServerPort = findEphemeralPort()- server = new NettyTcpModbusServer(modbusServerPort)- server.setMessageHandler((msg, sender) -> {- ModbusMessage modbusMessage = null- switch (msg.getFunction().blockType()) {- case ModbusBlockType.Coil -> {- BitsModbusMessage tcpRequest = msg.unwrap(BitsModbusMessage.class)- if (msg.getFunction().isReadFunction()) {- modbusMessage = readCoilsResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), tcpRequest.getCount(), BigInteger.valueOf(0xFFFF))- } else {- if (tcpRequest.getFunction().getCode() == WRITE_COILS) {- modbusMessage = writeCoilsResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), tcpRequest.getCount())- } else if (tcpRequest.getFunction().getCode() == WRITE_COIL) {- modbusMessage = writeCoilResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), true)- }- }- }- case ModbusBlockType.Discrete -> {- BitsModbusMessage tcpRequest = msg.unwrap(BitsModbusMessage.class)- modbusMessage = readDiscretesResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), tcpRequest.getCount(), BigInteger.valueOf(0xFFFF))- }- case ModbusBlockType.Holding -> {- RegistersModbusMessage registerRequest = msg.unwrap(RegistersModbusMessage.class)- if (msg.getFunction().isReadFunction()) {- modbusMessage = readHoldingsResponse(registerRequest.getUnitId(), registerRequest.getAddress(), new short[]{1, 2, 3, 4, 5, 6, 7, 8, 12.3f, 10})- } else {- if (registerRequest.getFunction().getCode() == WRITE_HOLDING_REGISTERS) {- modbusMessage = writeHoldingsResponse(registerRequest.getUnitId(), registerRequest.getAddress(), registerRequest.getCount())- } else if (registerRequest.getFunction().getCode() == WRITE_HOLDING_REGISTER) {- modbusMessage = writeHoldingResponse(registerRequest.getUnitId(), registerRequest.getAddress(), 21)- }- }- }- case ModbusBlockType.Input -> {- RegistersModbusMessage registerRequest = msg.unwrap(RegistersModbusMessage.class)- modbusMessage = readInputsResponse(registerRequest.getUnitId(), registerRequest.getAddress(), new short[]{11, 12, 13, 14, 15, 16, 17, 18, 19, 20})- }- case ModbusBlockType.Diagnostic -> {- modbusMessage = new BaseModbusMessage(msg.getUnitId(), msg.getFunction(), ModbusErrorCode.Acknowledge)- }- }-- if (msg.getFunction().isReadFunction()) {- latestReadMessage.set(msg)- } else {- latestWriteMessage.set(msg)- }- sender.accept(modbusMessage)-- })- server.start()- }-- def cleanupSpec() {- server.stop()- }--- def "Modbus Integration Test"() {- given: "expected conditions"- def conditions = new PollingConditions(timeout: 10, delay: 0.2)-- when: "the container starts"- def container = startContainer(defaultConfig(), defaultServices())- def assetStorageService = container.getService(AssetStorageService.class)- def assetProcessingService = container.getService(AssetProcessingService.class)- def agentService = container.getService(AgentService.class)-- and: "a mock Modbus agent is created"- def agent = new ModbusTcpAgent("Modbus")- agent.setRealm(MASTER_REALM)-- agent.setHost("127.0.0.1")- agent.setPort(modbusServerPort)- agent.setUnitId(1)-- agent = assetStorageService.merge(agent)-- then: "the protocol instance for the agent should be created"- conditions.eventually {- assert agentService.getProtocolInstance(agent.id) != null- assert ((ModbusTcpProtocol)agentService.getProtocolInstance(agent.id)) != null- }-- and: "the connection status should be CONNECTED"- conditions.eventually {- agent = assetStorageService.find(agent.getId())- agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED- }-- when: "A ShipAsset is created with an agent link"- ShipAsset ship = new ShipAsset("testAsset")- ship.setRealm(MASTER_REALM)- ship.addOrReplaceAttributes(new Attribute<Object>(ShipAsset.SPEED).addOrReplaceMeta(new MetaItem<>(- AGENT_LINK,- new ModbusAgentLink(- id: agent.getId(),- pollingMillis: 1000,- readMemoryArea: ModbusAgentLink.ReadMemoryArea.HOLDING,- readValueType: ModbusAgentLink.ModbusDataType.UINT,- readAddress: 2,- writeMemoryArea: ModbusAgentLink.WriteMemoryArea.HOLDING,- writeAddress: 3- )- )))- ship = assetStorageService.merge(ship)- ModbusAgentLink agentLink-- then: "a client should be created and the pollingMap is populated"- conditions.eventually {-- assert agentService.getProtocolInstance(agent.id) != null- assert ((ModbusTcpProtocol)agentService.getProtocolInstance(agent.id)) != null- assert ((ModbusTcpProtocol)agentService.getProtocolInstance(agent.id)).pollingMap.size() == 1-- ship = assetStorageService.find(ship.getId(), true)- agentLink = ship.getAttribute(ShipAsset.SPEED).get().getMetaItem(AGENT_LINK).get().getValue(ModbusAgentLink.class).get()- assert ship.getAttribute(ShipAsset.SPEED).flatMap { it.getValue() }.orElse(null) == 1-- assert (latestReadMessage.get() as ModbusMessage).getUnitId() === 1- assert (latestReadMessage.get() as ModbusMessage).getFunction() === ModbusFunctionCode.ReadHoldingRegisters- assert (latestReadMessage.get() as ModbusMessage).unwrap(RegistersModbusMessage.class).getAddress() == agentLink.getReadAddress().get()-1- assert (latestReadMessage.get() as ModbusMessage).unwrap(RegistersModbusMessage.class).getCount() == 1- }-- when: "the attribute is updated"- assetProcessingService.sendAttributeEvent(new AttributeEvent(ship.getId(), ShipAsset.SPEED, 123D))- ship.addOrReplaceAttributes(new Attribute<?>(ShipAsset.SPEED, 10))-- then: "the value is sent to the Modbus server"-- conditions.eventually {- def msg = (latestWriteMessage.get() as ModbusMessage).unwrap(RegistersModbusMessage)- assert msg != null- assert msg.getCount() == 1- assert msg.getAddress() == agentLink.getWriteAddress().get()-1- assert msg.dataDecodeUnsigned() == [123] as int[]-- ship = assetStorageService.find(ship.getId(), true)- assert ship.getAttribute(ShipAsset.SPEED).get().getValue().orElse(0) == 1.0- }-- when: "I add a new coil attribute and remove the Agent Link from the speed attribute"- ship.addOrReplaceAttributes(new Attribute<Integer>("coil1", ValueType.BOOLEAN).addOrReplaceMeta(new MetaItem<>(- AGENT_LINK,- new ModbusAgentLink(- id: agent.getId(),- pollingMillis: 1000,- readMemoryArea: ModbusAgentLink.ReadMemoryArea.COIL,- readValueType: ModbusAgentLink.ModbusDataType.BOOL,- readAddress: 5,- writeMemoryArea: ModbusAgentLink.WriteMemoryArea.COIL,- writeAddress: 6- )- )))- ship.addOrReplaceAttributes(new Attribute<Object>(ShipAsset.SPEED).setMeta(Map.of() as MetaMap))- latestReadMessage.set(null)- latestWriteMessage.set(null)-- and: "I merge it"- ship = assetStorageService.merge(ship)-- then: "I should receive the correct value in the coil"-- conditions.eventually {- agentLink = ship.getAttribute("coil1").get().getMetaItem(AGENT_LINK).get().getValue(ModbusAgentLink.class).get()-- assert agentService.getProtocolInstance(agent.id) != null- assert ((ModbusTcpProtocol)agentService.getProtocolInstance(agent.id)) != null-- def msg = (latestReadMessage.get() as ModbusMessage).unwrap(BitsModbusMessage)- assert msg != null- assert msg.getCount() == 1- assert msg.getAddress() == agentLink.getReadAddress().get()-1-- ship = assetStorageService.find(ship.getId(), true)- assert ship.getAttribute("coil1").flatMap { it.getValue() }.orElse(null) == true- }-- when: "I update the value of the coil"-- assetProcessingService.sendAttributeEvent(new AttributeEvent(ship.getId(), "coil1", true))-- then: "the coil is read properly"-- conditions.eventually {- def msg = (latestWriteMessage.get() as ModbusMessage).unwrap(BitsModbusMessage)- assert msg != null- assert msg.getCount() == 1- assert msg.getAddress() == 5- assert msg.getBits() == BigInteger.valueOf(0x0001)-- ship = assetStorageService.find(ship.getId(), true)- assert ship.getAttribute("coil1").flatMap { it.getValue() }.orElse(null) == true- }- }-}diff --git a/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusSerialTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusSerialTest.groovynew file mode 100644index 000000000..a8997c3da--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusSerialTest.groovy@@ -0,0 +1,1085 @@+/*+ * Copyright 2025, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test.protocol.modbus++import net.bytebuddy.agent.ByteBuddyAgent+import net.bytebuddy.agent.builder.AgentBuilder+import net.bytebuddy.asm.Advice+import net.bytebuddy.matcher.ElementMatchers+import org.openremote.agent.protocol.modbus.ModbusAgent+import org.openremote.agent.protocol.modbus.ModbusAgentLink+import org.openremote.agent.protocol.modbus.ModbusSerialAgent+import org.openremote.agent.protocol.modbus.ModbusSerialProtocol+import org.openremote.agent.protocol.serial.SerialIOClient+import org.openremote.agent.protocol.serial.JSerialCommChannelConfig.Paritybit+import org.openremote.agent.protocol.serial.JSerialCommChannelConfig.Stopbits+import org.openremote.manager.agent.AgentService+import org.openremote.manager.asset.AssetProcessingService+import org.openremote.manager.asset.AssetStorageService+import org.openremote.model.asset.agent.Agent+import org.openremote.model.asset.agent.ConnectionStatus+import org.openremote.model.asset.impl.ThingAsset+import org.openremote.model.attribute.Attribute+import org.openremote.model.attribute.AttributeEvent+import org.openremote.model.attribute.MetaItem+import org.openremote.model.value.ValueType+import org.openremote.test.ManagerContainerTrait+import org.openremote.test.protocol.MockSerialChannel+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++import java.nio.ByteBuffer+import java.nio.ByteOrder++import static org.openremote.model.Constants.MASTER_REALM+import static org.openremote.model.value.MetaItemType.AGENT_LINK+import static org.openremote.model.value.MetaItemType.STORE_DATA_POINTS+[email protected](count = 5)+class ModbusSerialTest extends Specification implements ManagerContainerTrait {++ static byte[] latestRequest = null+ static byte[] latestWriteRequest = null+ static ByteArrayOutputStream frameBuffer = new ByteArrayOutputStream()++ def setupSpec() {+ // retransform SerialIOClient.getChannelClass() to return MockSerialChannel instead of JSerialCommChannel+ def instrumentation = ByteBuddyAgent.install()+ new AgentBuilder.Default()+ .disableClassFormatChanges()+ .with(AgentBuilder.RedefinitionStrategy.RETRANSFORMATION)+ .type(ElementMatchers.is(SerialIOClient.class))+ .transform { builder, typeDescription, classLoader, module, protectionDomain ->+ builder.visit(Advice.to(MockSerialChannel.GetChannelClassAdvice.class)+ .on(ElementMatchers.named("getChannelClass")))+ }+ .installOn(instrumentation)++ instrumentation.retransformClasses(SerialIOClient.class)++ // Set up mock serial channel to handle Modbus RTU frames+ MockSerialChannel.setDataHandler { byte[] data, MockSerialChannel.ResponseCallback responseCallback ->+ synchronized (frameBuffer) {+ frameBuffer.write(data, 0, data.length)+ byte[] buffer = frameBuffer.toByteArray()++ if (buffer.length >= 8) {+ latestRequest = buffer.clone()++ // Check if it's a write request+ int functionCode = buffer[1] & 0xFF+ if (functionCode == 0x05 || functionCode == 0x06 ||+ functionCode == 0x0F || functionCode == 0x10) {+ latestWriteRequest = buffer.clone()+ }++ // Generate and send response+ byte[] response = generateModbusResponse(buffer, 0, buffer.length)+ if (response != null && response.length > 0) {+ responseCallback.sendResponse(response)+ }++ frameBuffer.reset()+ }+ }+ }+ }++ def cleanupSpec() {+ MockSerialChannel.setDataHandler(null)+ }++ def setup() {+ // Reset mock state before each test+ latestRequest = null+ latestWriteRequest = null+ synchronized (frameBuffer) {+ frameBuffer.reset()+ }+ }++ def "Modbus Serial Integration Test - Basic Operations"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 30, delay: 0.5)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus Serial agent is created"+ def agent = new ModbusSerialAgent("Modbus RTU Device")+ agent.setRealm(MASTER_REALM)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusSerialAgent.SERIAL_PORT, "/dev/ttyUSB0"),+ new Attribute<>(ModbusSerialAgent.BAUD_RATE, 9600),+ new Attribute<>(ModbusSerialAgent.DATA_BITS, 8),+ new Attribute<>(ModbusSerialAgent.STOP_BITS, Stopbits.STOPBITS_1),+ new Attribute<>(ModbusSerialAgent.PARITY, Paritybit.EVEN),+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(ModbusAgent.EndianFormat.BIG_ENDIAN, "101,151-161", 30)+ ] as ModbusAgent.DeviceConfigMap)+ )++ agent = assetStorageService.merge(agent)++ then: "the protocol instance should be created"+ conditions.eventually {+ assert agentService.getProtocolInstance(agent.id) != null+ assert agentService.getProtocolInstance(agent.id) instanceof ModbusSerialProtocol+ }++ and: "the connection status should be CONNECTED"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with partial read configuration is created (missing readValueType)"+ def device0 = new ThingAsset("Partial Config Device")+ device0.setRealm(MASTER_REALM)+ device0.addOrReplaceAttributes(+ // Partial read config - has readMemoryArea and readAddress but missing readValueType+ new Attribute<>("partialReadConfig", ValueType.INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadAddress(50)+ // Missing: readValueType+ }+ ))+ )+ device0 = assetStorageService.merge(device0)++ then: "the attribute should be linked without creating read polling tasks"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusSerialProtocol+ assert protocol != null+ // No batch groups should be created for incomplete read config+ assert protocol.batchGroups.isEmpty()+ }++ when: "the partial config device is removed"+ assetStorageService.delete([device0.getId()])++ and: "we wait for cleanup to complete"+ Thread.sleep(500)++ and: "A Thing asset is created with multiple agent links"+ ThingAsset device = new ThingAsset("Test Modbus Device")+ device.setRealm(MASTER_REALM)++ // Add various data type attributes+ device.addOrReplaceAttributes(+ // UINT16 register+ new Attribute<>("register1", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(1)+ it.setRegistersAmount(1)+ }+ )),+ // UINT16 register+ new Attribute<>("register2", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(3)+ it.setRegistersAmount(1)+ }+ )),+ // Float (REAL) value+ new Attribute<>("temperature", ValueType.NUMBER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.INPUT)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.REAL)+ it.setReadAddress(201)+ it.setRegistersAmount(2)+ }+ )),+ // Coil+ new Attribute<>("switch1", ValueType.BOOLEAN).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.COIL)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.BOOL)+ it.setReadAddress(6)+ it.setWriteMemoryArea(ModbusAgentLink.WriteMemoryArea.COIL)+ it.setWriteAddress(6)+ }+ ))+ )++ device = assetStorageService.merge(device)++ then: "register batches should be created and attributes should receive values"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusSerialProtocol+ assert protocol != null++ // Check that batch groups were created+ assert protocol.batchGroups.size() > 0++ device = assetStorageService.find(device.getId(), true)++ // Verify values were read+ assert device.getAttribute("register1").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("register2").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("temperature").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("switch1").flatMap { it.getValue() }.isPresent()++ // Check float value (should be 23.5 from mock)+ assert Math.abs((device.getAttribute("temperature").flatMap { it.getValue() }.get() as Double) - 23.5) < 0.1+ }++ when: "a write operation is performed"+ assetProcessingService.sendAttributeEvent(new AttributeEvent(device.getId(), "switch1", true))++ then: "the write should be sent to the device"+ conditions.eventually {+ def lastWriteRequest = latestWriteRequest+ assert lastWriteRequest != null+ assert lastWriteRequest[0] == (byte) 1 // Unit ID+ assert lastWriteRequest[1] == (byte) 0x05 // Write single coil function+ }++ }++ def "Modbus Serial Test - Batching with Illegal Registers"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.5)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus Serial agent with illegal registers is created"+ def agent = new ModbusSerialAgent("Modbus RTU with Illegal Regs")+ agent.setRealm(MASTER_REALM)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusSerialAgent.SERIAL_PORT, "/dev/ttyUSB0"),+ new Attribute<>(ModbusSerialAgent.BAUD_RATE, 9600),+ new Attribute<>(ModbusSerialAgent.DATA_BITS, 8),+ new Attribute<>(ModbusSerialAgent.STOP_BITS, Stopbits.STOPBITS_1),+ new Attribute<>(ModbusSerialAgent.PARITY, Paritybit.EVEN),+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(ModbusAgent.EndianFormat.BIG_ENDIAN, "6-11,21-26", 30)+ ] as ModbusAgent.DeviceConfigMap)+ )++ agent = assetStorageService.merge(agent)++ and: "attributes are created that would span illegal register ranges"+ ThingAsset device = new ThingAsset("Batching Test Device")+ device.setRealm(MASTER_REALM)++ device.addOrReplaceAttributes(+ new Attribute<>("reg0", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(1)+ it.setRegistersAmount(2)+ }+ )),+ new Attribute<>("reg15", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(16)+ it.setRegistersAmount(2)+ }+ )),+ new Attribute<>("reg30", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(31)+ it.setRegistersAmount(2)+ }+ ))+ )++ device = assetStorageService.merge(device)++ then: "batches should be split due to illegal registers"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusSerialProtocol+ assert protocol != null++ def cachedBatches = protocol.cachedBatches+ // Should have created multiple batches due to illegal register gaps+ def allBatches = cachedBatches.values().flatten()+ assert allBatches.size() >= 2 // At least 2 batches due to illegal register splits++ device = assetStorageService.find(device.getId(), true)+ // All attributes should still receive values+ assert device.getAttribute("reg0").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("reg15").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("reg30").flatMap { it.getValue() }.isPresent()+ }+ }++ def "Modbus Serial Test - Multiple Unit IDs via AgentLink"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.5)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)++ and: "a single Modbus Serial agent is created for the serial port"+ def agent = new ModbusSerialAgent("Modbus RTU Agent")+ agent.setRealm(MASTER_REALM)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusSerialAgent.SERIAL_PORT, "/dev/ttyUSB0"),+ new Attribute<>(ModbusSerialAgent.BAUD_RATE, 9600),+ new Attribute<>(ModbusSerialAgent.DATA_BITS, 8),+ new Attribute<>(ModbusSerialAgent.STOP_BITS, Stopbits.STOPBITS_1),+ new Attribute<>(ModbusSerialAgent.PARITY, Paritybit.EVEN),+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(ModbusAgent.EndianFormat.BIG_ENDIAN, "", 30)+ ] as ModbusAgent.DeviceConfigMap)+ )++ agent = assetStorageService.merge(agent)++ then: "agent should connect"+ conditions.eventually {+ assert agentService.getProtocolInstance(agent.id) != null++ agent = assetStorageService.find(agent.getId())+ assert agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "devices are created with different unit IDs via agentLink"+ ThingAsset device1 = new ThingAsset("Device on Unit 1")+ device1.setRealm(MASTER_REALM)+ device1.addOrReplaceAttributes(+ new Attribute<>("register1", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1) // Unit ID 1 via agentLink+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(1)+ it.setRegistersAmount(1)+ }+ ))+ )++ ThingAsset device2 = new ThingAsset("Device on Unit 2")+ device2.setRealm(MASTER_REALM)+ device2.addOrReplaceAttributes(+ new Attribute<>("register1", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(2) // Unit ID 2 via agentLink+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(1)+ it.setRegistersAmount(1)+ }+ ))+ )++ device1 = assetStorageService.merge(device1)+ device2 = assetStorageService.merge(device2)++ then: "both devices should receive values"+ conditions.eventually {+ device1 = assetStorageService.find(device1.getId(), true)+ device2 = assetStorageService.find(device2.getId(), true)++ // Both should have values+ assert device1.getAttribute("register1").flatMap { it.getValue() }.isPresent()+ assert device2.getAttribute("register1").flatMap { it.getValue() }.isPresent()++ // Values should be different based on unit ID+ // Mock returns incrementing values starting from address, but unit ID affects the response+ def value1 = device1.getAttribute("register1").flatMap { it.getValue() }.get()+ def value2 = device2.getAttribute("register1").flatMap { it.getValue() }.get()++ assert value1 != null+ assert value2 != null+ }++ and: "verify that requests were sent with correct unit IDs"+ conditions.eventually {+ // The mock should have received requests with unit ID 1 and 2+ def lastRequest = latestRequest+ assert lastRequest != null+ // Unit ID is the first byte of the Modbus request+ assert lastRequest[0] == (byte) 1 || lastRequest[0] == (byte) 2+ }+ }++ def "Modbus Serial Test - Byte and Word Order Configurations"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.5)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)++ and: "four agents are created with different endian format combinations"+ def agentBigBig = createAgentWithEndianFormat(assetStorageService, "Agent BIG-BIG",+ ModbusAgent.EndianFormat.BIG_ENDIAN)++ def agentBigLittle = createAgentWithEndianFormat(assetStorageService, "Agent BIG-LITTLE",+ ModbusAgent.EndianFormat.BIG_ENDIAN_BYTE_SWAP)++ def agentLittleBig = createAgentWithEndianFormat(assetStorageService, "Agent LITTLE-BIG",+ ModbusAgent.EndianFormat.LITTLE_ENDIAN_BYTE_SWAP)++ def agentLittleLittle = createAgentWithEndianFormat(assetStorageService, "Agent LITTLE-LITTLE",+ ModbusAgent.EndianFormat.LITTLE_ENDIAN)++ then: "all agents should connect successfully"+ conditions.eventually {+ assert assetStorageService.find(agentBigBig.getId()).getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ assert assetStorageService.find(agentBigLittle.getId()).getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ assert assetStorageService.find(agentLittleBig.getId()).getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ assert assetStorageService.find(agentLittleLittle.getId()).getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "devices with 32-bit float values are created for each agent"+ def deviceBigBig = createDeviceWithFloat(assetStorageService, "Device BIG-BIG", agentBigBig, 401)+ def deviceBigLittle = createDeviceWithFloat(assetStorageService, "Device BIG-LITTLE", agentBigLittle, 411)+ def deviceLittleBig = createDeviceWithFloat(assetStorageService, "Device LITTLE-BIG", agentLittleBig, 421)+ def deviceLittleLittle = createDeviceWithFloat(assetStorageService, "Device LITTLE-LITTLE", agentLittleLittle, 431)++ then: "all devices should receive float values"+ conditions.eventually {+ deviceBigBig = assetStorageService.find(deviceBigBig.getId(), true)+ deviceBigLittle = assetStorageService.find(deviceBigLittle.getId(), true)+ deviceLittleBig = assetStorageService.find(deviceLittleBig.getId(), true)+ deviceLittleLittle = assetStorageService.find(deviceLittleLittle.getId(), true)++ // All should have received values (mock returns endian-specific test data)+ assert deviceBigBig.getAttribute("floatValue").flatMap { it.getValue() }.isPresent()+ assert deviceBigLittle.getAttribute("floatValue").flatMap { it.getValue() }.isPresent()+ assert deviceLittleBig.getAttribute("floatValue").flatMap { it.getValue() }.isPresent()+ assert deviceLittleLittle.getAttribute("floatValue").flatMap { it.getValue() }.isPresent()++ // BIG-BIG should get the standard value (42.5)+ def valueBigBig = deviceBigBig.getAttribute("floatValue").flatMap { it.getValue() }.get() as Double+ assert Math.abs(valueBigBig - 42.5) < 0.1++ // Other combinations will have different byte arrangements resulting in different values+ // This verifies that the byte/word order is being applied+ def valueBigLittle = deviceBigLittle.getAttribute("floatValue").flatMap { it.getValue() }.get() as Double+ def valueLittleBig = deviceLittleBig.getAttribute("floatValue").flatMap { it.getValue() }.get() as Double+ def valueLittleLittle = deviceLittleLittle.getAttribute("floatValue").flatMap { it.getValue() }.get() as Double++ // Values should differ based on byte/word order (exact values depend on mock implementation)+ assert valueBigBig != valueBigLittle || valueBigBig != valueLittleBig || valueBigBig != valueLittleLittle+ }++ when: "devices with 64-bit double values are created"+ def device64BigBig = createDeviceWithDouble(assetStorageService, "Device64 BIG-BIG", agentBigBig, 501)+ def device64LittleLittle = createDeviceWithDouble(assetStorageService, "Device64 LITTLE-LITTLE", agentLittleLittle, 511)++ then: "64-bit values should also be affected by byte/word order"+ conditions.eventually {+ device64BigBig = assetStorageService.find(device64BigBig.getId(), true)+ device64LittleLittle = assetStorageService.find(device64LittleLittle.getId(), true)++ assert device64BigBig.getAttribute("doubleValue").flatMap { it.getValue() }.isPresent()+ assert device64LittleLittle.getAttribute("doubleValue").flatMap { it.getValue() }.isPresent()++ def doubleBigBig = device64BigBig.getAttribute("doubleValue").flatMap { it.getValue() }.get() as Double+ def doubleLittleLittle = device64LittleLittle.getAttribute("doubleValue").flatMap { it.getValue() }.get() as Double++ // BIG-BIG should get the standard value (999.888)+ assert Math.abs(doubleBigBig - 999.888) < 0.001++ // LITTLE-LITTLE should get a different value due to byte/word swapping+ assert doubleBigBig != doubleLittleLittle+ }+ }++ def "Modbus Serial Test - 64-bit Data Types (LINT, ULINT, LREAL)"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.5)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus Serial agent is created"+ def agent = new ModbusSerialAgent("Modbus RTU 64-bit Test")+ agent.setRealm(MASTER_REALM)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusSerialAgent.SERIAL_PORT, "/dev/ttyUSB0"),+ new Attribute<>(ModbusSerialAgent.BAUD_RATE, 9600),+ new Attribute<>(ModbusSerialAgent.DATA_BITS, 8),+ new Attribute<>(ModbusSerialAgent.STOP_BITS, Stopbits.STOPBITS_1),+ new Attribute<>(ModbusSerialAgent.PARITY, Paritybit.EVEN),+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(ModbusAgent.EndianFormat.BIG_ENDIAN, "", 50)+ ] as ModbusAgent.DeviceConfigMap)+ )++ agent = assetStorageService.merge(agent)++ and: "the agent is linked to a device with 64-bit data types"+ def device = new ThingAsset("64-bit Test Device")+ device.setRealm(MASTER_REALM)+ device.setParent(agent)+ device.addOrReplaceAttributes(+ // LREAL - Double precision float at address 301 (4 registers, 1-based = 300 protocol)+ new Attribute<>("doubleValue", ValueType.NUMBER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.LREAL)+ it.setReadAddress(301)+ }+ )+ ),+ // LINT - 64-bit signed integer at address 311 (4 registers, 1-based = 310 protocol)+ new Attribute<>("longSignedValue", ValueType.LONG).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.LINT)+ it.setReadAddress(311)+ }+ )+ ),+ // ULINT - 64-bit unsigned integer at address 321 (4 registers, 1-based = 320 protocol)+ new Attribute<>("longUnsignedValue", ValueType.BIG_INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.ULINT)+ it.setReadAddress(321)+ }+ )+ )+ )++ device = assetStorageService.merge(device)++ then: "the agent should connect successfully"+ conditions.eventually {+ def actualAgent = assetStorageService.find(agent.getId(), true) as ModbusSerialAgent+ assert actualAgent.getAgentStatus().orElse(null) == ConnectionStatus.CONNECTED+ }++ and: "all 64-bit attributes should receive values"+ conditions.eventually {+ device = assetStorageService.find(device.getId(), true)++ // Check LREAL (double) - should be 123.456789+ def doubleValue = device.getAttribute("doubleValue").flatMap { it.getValue() }.orElse(null)+ assert doubleValue != null+ assert doubleValue instanceof Number+ assert Math.abs(((Number) doubleValue).doubleValue() - 123.456789d) < 0.000001++ // Check LINT (signed long) - should be -9223372036854775000L+ def longSignedValue = device.getAttribute("longSignedValue").flatMap { it.getValue() }.orElse(null)+ assert longSignedValue != null+ assert longSignedValue instanceof Long+ assert longSignedValue == -9223372036854775000L++ // Check ULINT (unsigned BigInteger) - should be 18446744073709551000+ def longUnsignedValue = device.getAttribute("longUnsignedValue").flatMap { it.getValue() }.orElse(null)+ assert longUnsignedValue != null+ assert longUnsignedValue instanceof BigInteger+ assert longUnsignedValue == new BigInteger("18446744073709551000")+ }++ and: "verify protocol instance has created batch groups"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusSerialProtocol+ assert protocol != null+ assert protocol.batchGroups.size() > 0+ }+ }++ def "Modbus Serial Test - Multi-Register Write (registersAmount)"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.5)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus Serial agent is created"+ def agent = new ModbusSerialAgent("Modbus Serial Multi-Write")+ agent.setRealm(MASTER_REALM)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusSerialAgent.SERIAL_PORT, "/dev/ttyUSB0"),+ new Attribute<>(ModbusSerialAgent.BAUD_RATE, 9600),+ new Attribute<>(ModbusSerialAgent.DATA_BITS, 8),+ new Attribute<>(ModbusSerialAgent.STOP_BITS, Stopbits.STOPBITS_1),+ new Attribute<>(ModbusSerialAgent.PARITY, Paritybit.EVEN)+ )+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with multi-register write attributes is created"+ def device = new ThingAsset("Multi-Write Serial Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ // Write FLOAT (2 registers) to address 51 (1-based = 50 protocol)+ new Attribute<>("floatWrite", ValueType.NUMBER).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.REAL)+ it.setReadAddress(51)+ it.setRegistersAmount(2)+ it.setWriteMemoryArea(ModbusAgentLink.WriteMemoryArea.HOLDING)+ it.setWriteAddress(51)+ }+ ))+ )+ device = assetStorageService.merge(device)++ then: "device should be linked"+ conditions.eventually {+ device = assetStorageService.find(device.getId(), true)+ assert device.getAttribute("floatWrite").isPresent()+ }++ when: "multi-register float value is written"+ latestRequest = null+ latestWriteRequest = null+ assetProcessingService.sendAttributeEvent(new AttributeEvent(device.getId(), "floatWrite", 45.67f))++ then: "the write should use function code 0x10 (Write Multiple Registers)"+ conditions.eventually {+ def request = latestRequest+ assert request != null+ assert request[0] == (byte) 1 // Unit ID+ assert request[1] == (byte) 0x10 // Function code 0x10 for multi-register write+ assert ((request[2] & 0xFF) << 8 | (request[3] & 0xFF)) == 50 // Start address+ assert ((request[4] & 0xFF) << 8 | (request[5] & 0xFF)) == 2 // Register count+ assert request[6] == (byte) 4 // Byte count (2 registers * 2 bytes)+ }+ }++ def "Modbus Serial Test - Write With Polling Rate"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.5)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus Serial agent is created"+ def agent = new ModbusSerialAgent("Modbus Serial Polling Write")+ agent.setRealm(MASTER_REALM)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusSerialAgent.SERIAL_PORT, "/dev/ttyUSB0"),+ new Attribute<>(ModbusSerialAgent.BAUD_RATE, 9600),+ new Attribute<>(ModbusSerialAgent.DATA_BITS, 8),+ new Attribute<>(ModbusSerialAgent.STOP_BITS, Stopbits.STOPBITS_1),+ new Attribute<>(ModbusSerialAgent.PARITY, Paritybit.EVEN)+ )+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with continuous write (requestInterval + writeAddress, no readAddress) is created"+ def device = new ThingAsset("Continuous Write Serial Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ new Attribute<>("continuousWrite", ValueType.INTEGER, 77).addOrReplaceMeta(+ new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000) // Write every 1000ms+ it.setWriteMemoryArea(ModbusAgentLink.WriteMemoryArea.HOLDING)+ it.setWriteAddress(61)+ // No readAddress = continuous write mode+ }+ ),+ new MetaItem<>(STORE_DATA_POINTS)+ )+ )+ device = assetStorageService.merge(device)++ then: "write request task should be created"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusSerialProtocol+ assert protocol != null+ assert protocol.writeIntervalMap.size() == 1+ }++ def assetDatapointService = container.getService(org.openremote.manager.datapoint.AssetDatapointService.class)+ def attributeRef = new org.openremote.model.attribute.AttributeRef(device.getId(), "continuousWrite")++ then: "multiple write events should be observed"+ def writeRequests = []+ conditions.eventually {+ def request = latestRequest+ if (request != null) {+ // Capture write requests (function codes 0x05, 0x06, 0x10)+ def functionCode = request[1] & 0xFF+ if (functionCode == 0x06 || functionCode == 0x05 || functionCode == 0x10) {+ writeRequests.add(request.clone())+ }+ }+ // Wait to accumulate multiple writes+ Thread.sleep(2500) // Wait for ~2-3 write cycles at 1000ms interval+ assert writeRequests.size() >= 2 // Should have at least 2 writes+ }+++ then: "database should show 1 datapoint"+ conditions.eventually {+ // Query datapoints stored for this attribute - continuous writes should create no extra datapoints+ def datapoints = assetDatapointService.getDatapoints(attributeRef)+ println "Datapoints found: ${datapoints.size()}"+ datapoints.each { println " - timestamp: ${it.timestamp}, value: ${it.value}" }+ assert datapoints.size() == 1 // Should have 1 datapoint from periodic writes+ }+ }+++ // Helper methods for endian format tests+ private ModbusSerialAgent createAgentWithEndianFormat(AssetStorageService assetStorageService,+ String name,+ ModbusAgent.EndianFormat endianFormat) {+ def agent = new ModbusSerialAgent(name)+ agent.setRealm(MASTER_REALM)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusSerialAgent.SERIAL_PORT, "/dev/ttyUSB0"),+ new Attribute<>(ModbusSerialAgent.BAUD_RATE, 9600),+ new Attribute<>(ModbusSerialAgent.DATA_BITS, 8),+ new Attribute<>(ModbusSerialAgent.STOP_BITS, Stopbits.STOPBITS_1),+ new Attribute<>(ModbusSerialAgent.PARITY, Paritybit.EVEN),+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(endianFormat, "", 50)+ ] as ModbusAgent.DeviceConfigMap)+ )+ return assetStorageService.merge(agent)+ }++ private ThingAsset createDeviceWithFloat(AssetStorageService assetStorageService,+ String name,+ ModbusSerialAgent agent,+ int address) {+ def device = new ThingAsset(name)+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ new Attribute<>("floatValue", ValueType.NUMBER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.REAL)+ it.setReadAddress(address)+ it.setRegistersAmount(2)+ }+ )+ )+ )+ return assetStorageService.merge(device)+ }++ private ThingAsset createDeviceWithDouble(AssetStorageService assetStorageService,+ String name,+ ModbusSerialAgent agent,+ int address) {+ def device = new ThingAsset(name)+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ new Attribute<>("doubleValue", ValueType.NUMBER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.LREAL)+ it.setReadAddress(address)+ it.setRegistersAmount(4)+ }+ )+ )+ )+ return assetStorageService.merge(device)+ }++ /**+ * Generate Modbus RTU responses for various function codes+ */+ private static byte[] generateModbusResponse(byte[] request, int offset, int length) {+ if (length < 6) return new byte[0]++ int unitId = request[offset] & 0xFF+ int functionCode = request[offset + 1] & 0xFF+ int address = ((request[offset + 2] & 0xFF) << 8) | (request[offset + 3] & 0xFF)+ int quantity = ((request[offset + 4] & 0xFF) << 8) | (request[offset + 5] & 0xFF)++ byte[] response++ switch (functionCode) {+ case 0x01: // Read Coils+ case 0x02: // Read Discrete Inputs+ int byteCount = (quantity + 7) / 8+ response = new byte[5 + byteCount]+ response[0] = (byte) unitId+ response[1] = (byte) functionCode+ response[2] = (byte) byteCount+ // Fill with alternating bits+ for (int i = 0; i < byteCount; i++) {+ response[3 + i] = (byte) 0xAA+ }+ break++ case 0x03: // Read Holding Registers+ case 0x04: // Read Input Registers+ int registerBytes = quantity * 2+ response = new byte[5 + registerBytes]+ response[0] = (byte) unitId+ response[1] = (byte) functionCode+ response[2] = (byte) registerBytes++ // Generate test data based on address+ // Handle special test data addresses for different data types+ for (int i = 0; i < quantity; i++) {+ int currentAddress = address + i+ int responseOffset = 3 + i * 2++ // Check if this register is part of a special test value+ if (currentAddress >= 200 && currentAddress < 202 && address == 200 && quantity == 2) {+ // Return float value 23.5+ ByteBuffer bb = ByteBuffer.allocate(4)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putFloat(23.5f)+ byte[] floatBytes = bb.array()+ System.arraycopy(floatBytes, 0, response, 3, 4)+ break+ } else if (currentAddress >= 300 && currentAddress < 304) {+ // Return double value 123.456789 at registers 300-303+ if (i == 0 || currentAddress == 300) {+ int regOffset = currentAddress - 300+ ByteBuffer bb = ByteBuffer.allocate(8)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putDouble(123.456789d)+ byte[] doubleBytes = bb.array()+ int copyLen = Math.min(registerBytes - (responseOffset - 3), 8 - (regOffset * 2))+ System.arraycopy(doubleBytes, regOffset * 2, response, responseOffset, Math.min(copyLen, 8))+ }+ } else if (currentAddress >= 310 && currentAddress < 314) {+ // Return 64-bit signed integer: -9223372036854775000L at registers 310-313+ int regOffset = currentAddress - 310+ ByteBuffer bb = ByteBuffer.allocate(8)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putLong(-9223372036854775000L)+ byte[] longBytes = bb.array()+ response[responseOffset] = longBytes[regOffset * 2]+ response[responseOffset + 1] = longBytes[regOffset * 2 + 1]+ } else if (currentAddress >= 320 && currentAddress < 324) {+ // Return 64-bit unsigned integer at registers 320-323+ int regOffset = currentAddress - 320+ ByteBuffer bb = ByteBuffer.allocate(8)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putLong(-616L) // This represents 18446744073709551000 as unsigned+ byte[] longBytes = bb.array()+ response[responseOffset] = longBytes[regOffset * 2]+ response[responseOffset + 1] = longBytes[regOffset * 2 + 1]+ } else if (currentAddress >= 400 && currentAddress < 402) {+ // Return float value 42.5 for byte/word order test (BIG-BIG) at 400-401+ if (i == 0 || currentAddress == 400) {+ ByteBuffer bb = ByteBuffer.allocate(4)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putFloat(42.5f)+ byte[] floatBytes = bb.array()+ System.arraycopy(floatBytes, 0, response, 3, 4)+ break+ }+ } else if (currentAddress >= 410 && currentAddress < 412) {+ // Return float value 42.5 for byte/word order test (BIG-LITTLE) at 410-411+ if (i == 0 || currentAddress == 410) {+ ByteBuffer bb = ByteBuffer.allocate(4)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putFloat(42.5f)+ byte[] floatBytes = bb.array()+ System.arraycopy(floatBytes, 0, response, 3, 4)+ break+ }+ } else if (currentAddress >= 420 && currentAddress < 422) {+ // Return float value 42.5 for byte/word order test (LITTLE-BIG) at 420-421+ if (i == 0 || currentAddress == 420) {+ ByteBuffer bb = ByteBuffer.allocate(4)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putFloat(42.5f)+ byte[] floatBytes = bb.array()+ System.arraycopy(floatBytes, 0, response, 3, 4)+ break+ }+ } else if (currentAddress >= 430 && currentAddress < 432) {+ // Return float value 42.5 for byte/word order test (LITTLE-LITTLE) at 430-431+ if (i == 0 || currentAddress == 430) {+ ByteBuffer bb = ByteBuffer.allocate(4)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putFloat(42.5f)+ byte[] floatBytes = bb.array()+ System.arraycopy(floatBytes, 0, response, 3, 4)+ break+ }+ } else if (currentAddress >= 500 && currentAddress < 504) {+ // Return double value 999.888 for byte/word order test (BIG-BIG) at 500-503+ int regOffset = currentAddress - 500+ ByteBuffer bb = ByteBuffer.allocate(8)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putDouble(999.888d)+ byte[] doubleBytes = bb.array()+ int copyLen = Math.min(2, 8 - (regOffset * 2))+ System.arraycopy(doubleBytes, regOffset * 2, response, responseOffset, copyLen)+ } else if (currentAddress >= 510 && currentAddress < 514) {+ // Return double value 999.888 for byte/word order test (LITTLE-LITTLE) at 510-513+ int regOffset = currentAddress - 510+ ByteBuffer bb = ByteBuffer.allocate(8)+ bb.order(ByteOrder.BIG_ENDIAN)+ bb.putDouble(999.888d)+ byte[] doubleBytes = bb.array()+ int copyLen = Math.min(2, 8 - (regOffset * 2))+ System.arraycopy(doubleBytes, regOffset * 2, response, responseOffset, copyLen)+ } else {+ // Return incrementing values+ int value = currentAddress+ response[responseOffset] = (byte) (value >> 8)+ response[responseOffset + 1] = (byte) (value & 0xFF)+ }+ }+ break++ case 0x05: // Write Single Coil+ response = new byte[8]+ System.arraycopy(request, offset, response, 0, 6)+ break++ case 0x06: // Write Single Register+ response = new byte[8]+ System.arraycopy(request, offset, response, 0, 6)+ break++ case 0x0F: // Write Multiple Coils+ case 0x10: // Write Multiple Registers+ // Response echoes: Unit ID + FC + Start Address + Quantity+ response = new byte[8]+ System.arraycopy(request, offset, response, 0, 6)+ break++ default:+ // Exception response+ response = new byte[5]+ response[0] = (byte) unitId+ response[1] = (byte) (functionCode | 0x80)+ response[2] = (byte) 0x01 // Illegal function+ return addCRC(response, 3)+ }++ return addCRC(response, response.length - 2)+ }++ /**+ * Calculate and add CRC16 to Modbus RTU frame+ */+ private static byte[] addCRC(byte[] data, int length) {+ int crc = 0xFFFF+ for (int i = 0; i < length; i++) {+ crc ^= (data[i] & 0xFF)+ for (int j = 0; j < 8; j++) {+ if ((crc & 1) != 0) {+ crc = (crc >> 1) ^ 0xA001+ } else {+ crc = crc >> 1+ }+ }+ }+ data[length] = (byte) (crc & 0xFF)+ data[length + 1] = (byte) (crc >> 8)+ return data+ }+}diff --git a/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusTcpTest.groovy b/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusTcpTest.groovynew file mode 100644index 000000000..23e04c1d9--- /dev/null+++ b/test/src/test/groovy/org/openremote/test/protocol/modbus/ModbusTcpTest.groovy@@ -0,0 +1,928 @@+/*+ * Copyright 2025, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test.protocol.modbus++import net.solarnetwork.io.modbus.BitsModbusMessage+import net.solarnetwork.io.modbus.ModbusBlockType+import net.solarnetwork.io.modbus.ModbusErrorCode+import net.solarnetwork.io.modbus.ModbusFunctionCode+import net.solarnetwork.io.modbus.ModbusMessage+import net.solarnetwork.io.modbus.RegistersModbusMessage+import net.solarnetwork.io.modbus.netty.msg.BaseModbusMessage+import net.solarnetwork.io.modbus.tcp.netty.NettyTcpModbusServer+import org.openremote.agent.protocol.modbus.ModbusAgent+import org.openremote.agent.protocol.modbus.ModbusAgentLink+import org.openremote.agent.protocol.modbus.ModbusTcpAgent+import org.openremote.agent.protocol.modbus.ModbusTcpProtocol+import org.openremote.manager.agent.AgentService+import org.openremote.manager.asset.AssetProcessingService+import org.openremote.manager.asset.AssetStorageService+import org.openremote.model.asset.agent.Agent+import org.openremote.model.asset.agent.ConnectionStatus+import org.openremote.model.asset.impl.ShipAsset+import org.openremote.model.asset.impl.ThingAsset+import org.openremote.model.attribute.Attribute+import org.openremote.model.attribute.AttributeEvent+import org.openremote.model.attribute.MetaItem+import org.openremote.model.attribute.MetaMap+import org.openremote.model.value.ValueType+import org.openremote.test.ManagerContainerTrait+import spock.lang.Shared+import spock.lang.Specification+import spock.util.concurrent.PollingConditions++import java.util.concurrent.atomic.AtomicReference++import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_COIL+import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_COILS+import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_HOLDING_REGISTER+import static net.solarnetwork.io.modbus.ModbusFunctionCodes.WRITE_HOLDING_REGISTERS+import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.readCoilsResponse+import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.readDiscretesResponse+import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.writeCoilResponse+import static net.solarnetwork.io.modbus.netty.msg.BitsModbusMessage.writeCoilsResponse+import static net.solarnetwork.io.modbus.netty.msg.RegistersModbusMessage.*+import static org.openremote.model.Constants.MASTER_REALM+import static org.openremote.model.value.MetaItemType.AGENT_LINK++class ModbusTcpTest extends Specification implements ManagerContainerTrait {++ @Shared+ int modbusServerPort++ @Shared+ NettyTcpModbusServer server++ @Shared+ AtomicReference<ModbusMessage> latestReadMessage = new AtomicReference(null)++ @Shared+ AtomicReference<ModbusMessage> latestWriteMessage = new AtomicReference(null)++ def setupSpec() {+ modbusServerPort = findEphemeralPort()+ server = new NettyTcpModbusServer(modbusServerPort)+ server.setMessageHandler((msg, sender) -> {+ ModbusMessage modbusMessage = null+ switch (msg.getFunction().blockType()) {+ case ModbusBlockType.Coil -> {+ BitsModbusMessage tcpRequest = msg.unwrap(BitsModbusMessage.class)+ if (msg.getFunction().isReadFunction()) {+ modbusMessage = readCoilsResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), tcpRequest.getCount(), BigInteger.valueOf(0xFFFF))+ } else {+ if (tcpRequest.getFunction().getCode() == WRITE_COILS) {+ modbusMessage = writeCoilsResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), tcpRequest.getCount())+ } else if (tcpRequest.getFunction().getCode() == WRITE_COIL) {+ modbusMessage = writeCoilResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), true)+ }+ }+ }+ case ModbusBlockType.Discrete -> {+ BitsModbusMessage tcpRequest = msg.unwrap(BitsModbusMessage.class)+ modbusMessage = readDiscretesResponse(tcpRequest.getUnitId(), tcpRequest.getAddress(), tcpRequest.getCount(), BigInteger.valueOf(0xFFFF))+ }+ case ModbusBlockType.Holding -> {+ RegistersModbusMessage registerRequest = msg.unwrap(RegistersModbusMessage.class)+ if (msg.getFunction().isReadFunction()) {+ // Generate mock data based on address and count+ short[] mockData = generateMockHoldingData(registerRequest.getAddress(), registerRequest.getCount())+ println("TCP Mock: address=${registerRequest.getAddress()}, count=${registerRequest.getCount()}, data=${mockData.collect{String.format('0x%04X', it & 0xFFFF)}}")+ modbusMessage = readHoldingsResponse(registerRequest.getUnitId(), registerRequest.getAddress(), mockData)+ } else {+ if (registerRequest.getFunction().getCode() == WRITE_HOLDING_REGISTERS) {+ modbusMessage = writeHoldingsResponse(registerRequest.getUnitId(), registerRequest.getAddress(), registerRequest.getCount())+ } else if (registerRequest.getFunction().getCode() == WRITE_HOLDING_REGISTER) {+ modbusMessage = writeHoldingResponse(registerRequest.getUnitId(), registerRequest.getAddress(), 21)+ }+ }+ }+ case ModbusBlockType.Input -> {+ RegistersModbusMessage registerRequest = msg.unwrap(RegistersModbusMessage.class)+ modbusMessage = readInputsResponse(registerRequest.getUnitId(), registerRequest.getAddress(), new short[]{11, 12, 13, 14, 15, 16, 17, 18, 19, 20})+ }+ case ModbusBlockType.Diagnostic -> {+ modbusMessage = new BaseModbusMessage(msg.getUnitId(), msg.getFunction(), ModbusErrorCode.Acknowledge)+ }+ }++ if (msg.getFunction().isReadFunction()) {+ latestReadMessage.set(msg)+ } else {+ latestWriteMessage.set(msg)+ }+ sender.accept(modbusMessage)++ })+ server.start()+ }++ def cleanupSpec() {+ server.stop()+ }++ static short[] generateMockHoldingData(int address, int count) {+ short[] data = new short[count]++ // Basic registers (0-9): simple sequential values+ // 64-bit test registers (100-111): specific values for LINT, ULINT, LREAL+ // Byte/Word order test registers (200-207): values to test endianness++ for (int i = 0; i < count; i++) {+ int registerAddress = address + i + 1++ if (registerAddress >= 1 && registerAddress <= 10) {+ // Basic sequential values for simple tests+ data[i] = (short)(registerAddress)+ } else if (registerAddress >= 100 && registerAddress < 112) {+ // 64-bit data type test values+ // LINT at 100-103 (4 registers): value = 1234567890123456L+ // ULINT at 104-107 (4 registers): value = 9876543210987654L+ // LREAL at 108-111 (4 registers): value = 123.456789++ if (registerAddress >= 100 && registerAddress <= 103) {+ // LINT: 1234567890123456L = 0x000462D53C8ABAC0+ long lintValue = 1234567890123456L+ int regIndex = registerAddress - 100+ data[i] = (short)((lintValue >> (48 - regIndex * 16)) & 0xFFFF)+ } else if (registerAddress >= 104 && registerAddress <= 107) {+ // ULINT: 9876543210987654L = 0x00231D31F8D09706+ long ulintValue = 9876543210987654L+ int regIndex = registerAddress - 104+ data[i] = (short)((ulintValue >> (48 - regIndex * 16)) & 0xFFFF)+ } else if (registerAddress >= 108 && registerAddress <= 111) {+ // LREAL: 123.456789 = 0x405EDD2F1A9FBE77+ long lrealBits = Double.doubleToRawLongBits(123.456789)+ int regIndex = registerAddress - 108+ data[i] = (short)((lrealBits >> (48 - regIndex * 16)) & 0xFFFF)+ }+ } else if (registerAddress >= 200 && registerAddress < 208) {+ // Byte/Word order test values+ // INT32 at 200-201: value = 0x12345678+ // FLOAT at 202-203: value = 12.34f+ // INT32 at 204-205: value = 0xABCDEF01+ // FLOAT at 206-207: value = 56.78f++ if (registerAddress == 200) {+ data[i] = (short)0x1234+ } else if (registerAddress == 201) {+ data[i] = (short)0x5678+ } else if (registerAddress == 202 || registerAddress == 203) {+ // FLOAT 12.34f = 0x4145C28F+ int floatBits = Float.floatToRawIntBits(12.34f)+ data[i] = (short)((floatBits >> ((203 - registerAddress) * 16)) & 0xFFFF)+ } else if (registerAddress == 204) {+ data[i] = (short)0xABCD+ } else if (registerAddress == 205) {+ data[i] = (short)0xEF01+ } else if (registerAddress == 206 || registerAddress == 207) {+ // FLOAT 56.78f = 0x42633d71+ int floatBits = Float.floatToRawIntBits(56.78f)+ data[i] = (short)((floatBits >> ((207 - registerAddress) * 16)) & 0xFFFF)+ }+ } else {+ // Default: return address-based value+ data[i] = (short)(registerAddress % 100)+ }+ }++ return data+ }++ def "Modbus TCP Integration Test - Basic Operations"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a mock Modbus agent is created"+ def agent = new ModbusTcpAgent("Modbus")+ agent.setRealm(MASTER_REALM)++ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)++ agent = assetStorageService.merge(agent)++ then: "the protocol instance for the agent should be created"+ conditions.eventually {+ assert agentService.getProtocolInstance(agent.id) != null+ assert ((ModbusTcpProtocol)agentService.getProtocolInstance(agent.id)) != null+ }++ and: "the connection status should be CONNECTED"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with partial read configuration is created (missing readValueType)"+ def device = new ThingAsset("Partial Config Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ // Partial read config - has readMemoryArea and readAddress but missing readValueType+ new Attribute<>("partialReadConfig", ValueType.INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadAddress(550)+ // Missing: readValueType+ }+ )+ )+ )+ device = assetStorageService.merge(device)++ then: "the attribute should be linked without creating read polling tasks"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusTcpProtocol+ assert protocol != null+ // No batch groups should be created for incomplete read config+ assert protocol.batchGroups.isEmpty()+ }++ when: "A ShipAsset is created with an agent link"+ ShipAsset ship = new ShipAsset("testAsset")+ ship.setRealm(MASTER_REALM)+ ship.addOrReplaceAttributes(new Attribute<Object>(ShipAsset.SPEED).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(+ id: agent.getId(),+ unitId: 1,+ requestInterval: 1000,+ readMemoryArea: ModbusAgentLink.ReadMemoryArea.HOLDING,+ readValueType: ModbusAgentLink.ModbusDataType.UINT,+ readAddress: 2,+ writeMemoryArea: ModbusAgentLink.WriteMemoryArea.HOLDING,+ writeAddress: 3+ )+ )))+ ship = assetStorageService.merge(ship)+ ModbusAgentLink agentLink+++ then: "a client should be created and the pollingMap is populated"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusTcpProtocol+ assert protocol != null+ assert protocol.batchGroups.size() > 0++ ship = assetStorageService.find(ship.getId(), true)+ agentLink = ship.getAttribute(ShipAsset.SPEED).get().getMetaItem(AGENT_LINK).get().getValue(ModbusAgentLink.class).get()+ assert ship.getAttribute(ShipAsset.SPEED).flatMap { it.getValue() }.orElse(null) == 2++ assert (latestReadMessage.get() as ModbusMessage).getUnitId() === 1+ assert (latestReadMessage.get() as ModbusMessage).getFunction() === ModbusFunctionCode.ReadHoldingRegisters+ assert (latestReadMessage.get() as ModbusMessage).unwrap(RegistersModbusMessage.class).getAddress() == agentLink.getReadAddress()-1+ assert (latestReadMessage.get() as ModbusMessage).unwrap(RegistersModbusMessage.class).getCount() == 1+ }++ when: "the attribute is updated"+ assetProcessingService.sendAttributeEvent(new AttributeEvent(ship.getId(), ShipAsset.SPEED, 123D))+ ship.addOrReplaceAttributes(new Attribute<?>(ShipAsset.SPEED, 10))++ then: "the value is sent to the Modbus server"+ conditions.eventually {+ def msg = (latestWriteMessage.get() as ModbusMessage).unwrap(RegistersModbusMessage)+ assert msg != null+ assert msg.getCount() == 1+ assert msg.getAddress() == agentLink.getWriteAddress()-1+ assert msg.dataDecodeUnsigned() == [123] as int[]++ ship = assetStorageService.find(ship.getId(), true)+ assert ship.getAttribute(ShipAsset.SPEED).get().getValue().orElse(0) == 2.0+ }++ when: "I add a new coil attribute and remove the Agent Link from the speed attribute"+ ship.addOrReplaceAttributes(new Attribute<Integer>("coil1", ValueType.BOOLEAN).addOrReplaceMeta(new MetaItem<>(+ AGENT_LINK,+ new ModbusAgentLink(+ id: agent.getId(),+ unitId: 1,+ requestInterval: 1000,+ readMemoryArea: ModbusAgentLink.ReadMemoryArea.COIL,+ readValueType: ModbusAgentLink.ModbusDataType.BOOL,+ readAddress: 5,+ writeMemoryArea: ModbusAgentLink.WriteMemoryArea.COIL,+ writeAddress: 6+ )+ )))+ ship.addOrReplaceAttributes(new Attribute<Object>(ShipAsset.SPEED).setMeta(Map.of() as MetaMap))+ latestReadMessage.set(null)+ latestWriteMessage.set(null)++ and: "I merge it"+ ship = assetStorageService.merge(ship)++ then: "I should receive the correct value in the coil"++ conditions.eventually {+ agentLink = ship.getAttribute("coil1").get().getMetaItem(AGENT_LINK).get().getValue(ModbusAgentLink.class).get()++ assert agentService.getProtocolInstance(agent.id) != null+ assert ((ModbusTcpProtocol)agentService.getProtocolInstance(agent.id)) != null++ def msg = (latestReadMessage.get() as ModbusMessage).unwrap(BitsModbusMessage)+ assert msg != null+ assert msg.getCount() == 1+ assert msg.getAddress() == agentLink.getReadAddress()-1++ ship = assetStorageService.find(ship.getId(), true)+ assert ship.getAttribute("coil1").flatMap { it.getValue() }.orElse(null) == true+ }++ when: "I update the value of the coil"++ assetProcessingService.sendAttributeEvent(new AttributeEvent(ship.getId(), "coil1", true))++ then: "the coil is read properly"++ conditions.eventually {+ def msg = (latestWriteMessage.get() as ModbusMessage).unwrap(BitsModbusMessage)+ assert msg != null+ assert msg.getCount() == 1+ assert msg.getAddress() == 5+ assert msg.getBits() == BigInteger.valueOf(0x0001)++ ship = assetStorageService.find(ship.getId(), true)+ assert ship.getAttribute("coil1").flatMap { it.getValue() }.orElse(null) == true+ }+ }++ def "Modbus TCP Test - Register Batching"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus TCP agent with batching enabled is created"+ def agent = new ModbusTcpAgent("Modbus TCP Batching")+ agent.setRealm(MASTER_REALM)+ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(ModbusAgent.EndianFormat.BIG_ENDIAN, "", 50)+ ] as ModbusAgent.DeviceConfigMap) // Enable batching+ )+ agent = assetStorageService.merge(agent)++ then: "the protocol instance should be created and connected"+ conditions.eventually {+ assert agentService.getProtocolInstance(agent.id) != null+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with multiple sequential register attributes is created"+ ThingAsset device = new ThingAsset("Batching Test Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ new Attribute<>("register1", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(1)+ }+ )+ ),+ new Attribute<>("register2", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(2)+ }+ )+ ),+ new Attribute<>("register3", ValueType.POSITIVE_INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.UINT)+ it.setReadAddress(3)+ }+ )+ )+ )+ device = assetStorageService.merge(device)++ then: "batch groups should be created and attributes should receive values"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusTcpProtocol+ assert protocol != null++ // Check that batch groups were created (batching is enabled)+ assert protocol.batchGroups.size() > 0++ device = assetStorageService.find(device.getId(), true)++ // Verify all attributes received values from the batch read+ assert device.getAttribute("register1").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("register2").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("register3").flatMap { it.getValue() }.isPresent()++ // Verify the values match what the mock server returns+ assert device.getAttribute("register1").flatMap { it.getValue() }.get() == 1+ assert device.getAttribute("register2").flatMap { it.getValue() }.get() == 2+ assert device.getAttribute("register3").flatMap { it.getValue() }.get() == 3+ }+ }++ def "Modbus TCP Test - 64-bit Data Types (LINT, ULINT, LREAL)"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus TCP agent is created with batching enabled"+ def agent = new ModbusTcpAgent("Modbus TCP 64-bit Test")+ agent.setRealm(MASTER_REALM)+ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(ModbusAgent.EndianFormat.BIG_ENDIAN, "", 50)+ ] as ModbusAgent.DeviceConfigMap)+ )+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with 64-bit data types is created"+ def device = new ThingAsset("64-bit Test Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ // LINT - 64-bit signed integer (4 registers) at 100-103+ new Attribute<>("longSignedValue", ValueType.LONG).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.LINT)+ it.setReadAddress(100)+ it.setRegistersAmount(4)+ }+ )+ ),+ // ULINT - 64-bit unsigned integer (4 registers) at 104-107+ new Attribute<>("longUnsignedValue", ValueType.BIG_INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.ULINT)+ it.setReadAddress(104)+ it.setRegistersAmount(4)+ }+ )+ ),+ // LREAL - Double precision float (4 registers) at 108-111+ new Attribute<>("doubleValue", ValueType.NUMBER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.LREAL)+ it.setReadAddress(108)+ it.setRegistersAmount(4)+ }+ )+ )+ )+ device = assetStorageService.merge(device)++ then: "all 64-bit attributes should receive values"+ conditions.eventually {+ device = assetStorageService.find(device.getId(), true)++ // Verify all attributes have values+ assert device.getAttribute("longSignedValue").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("longUnsignedValue").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("doubleValue").flatMap { it.getValue() }.isPresent()++ // Verify the exact values from mock server (PLC4X converts multi-register data)+ assert device.getAttribute("longSignedValue").flatMap { it.getValue() }.get() == 1234567890123456L+ assert device.getAttribute("longUnsignedValue").flatMap { it.getValue() }.get() == 9876543210987654L+ assert Math.abs(device.getAttribute("doubleValue").flatMap { it.getValue() }.get() as Double - 123.456789) < 0.000001+ }++ and: "verify batching was used"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusTcpProtocol+ assert protocol != null+ assert protocol.batchGroups.size() > 0+ }+ }++ def "Modbus TCP Test - Byte and Word Order"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus TCP agent with BIG-BIG byte/word order is created"+ def agent = new ModbusTcpAgent("Modbus TCP Endian Test")+ agent.setRealm(MASTER_REALM)+ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)+ agent.addOrReplaceAttributes(+ new Attribute<>(ModbusAgent.DEVICE_CONFIG, [+ "default": new ModbusAgent.ModbusDeviceConfig(ModbusAgent.EndianFormat.BIG_ENDIAN, "", 1)+ ] as ModbusAgent.DeviceConfigMap)+ )+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with INT32 and FLOAT values is created"+ def device = new ThingAsset("Endian Test Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ new Attribute<>("int32Value", ValueType.INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.DINT)+ it.setReadAddress(200)+ it.setRegistersAmount(2)+ }+ )+ ),+ new Attribute<>("floatValue", ValueType.NUMBER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.REAL)+ it.setReadAddress(202)+ it.setRegistersAmount(2)+ }+ )+ )+ )+ device = assetStorageService.merge(device)++ then: "the values should be read correctly with BIG-BIG order"+ conditions.eventually {+ device = assetStorageService.find(device.getId(), true)++ // Verify attributes receive values with the configured byte/word order+ assert device.getAttribute("int32Value").flatMap { it.getValue() }.isPresent()+ assert device.getAttribute("floatValue").flatMap { it.getValue() }.isPresent()++ // Mock server returns 0x12345678 for INT32 at 200-201 (BIG-BIG byte/word order)+ assert device.getAttribute("int32Value").flatMap { it.getValue() }.get() == 0x12345678++ // Mock server returns 12.34f for FLOAT at 202-203+ def floatValue = device.getAttribute("floatValue").flatMap { it.getValue() }.get() as Float+ assert Math.abs(floatValue - 12.34f) < 0.01f+ }+ }++ def "Modbus TCP Test - Multi-Register Write (registersAmount)"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus TCP agent is created"+ def agent = new ModbusTcpAgent("Modbus TCP Multi-Write Test")+ agent.setRealm(MASTER_REALM)+ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with multi-register write attributes is created"+ def device = new ThingAsset("Multi-Write Test Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ // Write FLOAT (2 registers) to address 300+ new Attribute<>("floatWriteValue", ValueType.NUMBER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.REAL)+ it.setReadAddress(300)+ it.setRegistersAmount(2)+ it.setWriteMemoryArea(ModbusAgentLink.WriteMemoryArea.HOLDING)+ it.setWriteAddress(300)+ }+ )+ ),+ // Write DINT (2 registers) to address 302+ new Attribute<>("dintWriteValue", ValueType.INTEGER).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000)+ it.setReadMemoryArea(ModbusAgentLink.ReadMemoryArea.HOLDING)+ it.setReadValueType(ModbusAgentLink.ModbusDataType.DINT)+ it.setReadAddress(302)+ it.setRegistersAmount(2)+ it.setWriteMemoryArea(ModbusAgentLink.WriteMemoryArea.HOLDING)+ it.setWriteAddress(302)+ }+ )+ )+ )+ device = assetStorageService.merge(device)++ then: "device should be linked"+ conditions.eventually {+ device = assetStorageService.find(device.getId(), true)+ assert device.getAttribute("floatWriteValue").isPresent()+ assert device.getAttribute("dintWriteValue").isPresent()+ }++ when: "multi-register float value is written"+ latestWriteMessage.set(null)+ def floatWrite = assetProcessingService.sendAttributeEvent(new AttributeEvent(device.getId(), "floatWriteValue", 98.76f))++ then: "the write should use PLC4X array notation (indicated by register count > 1)"+ conditions.eventually {+ // Since PLC4X may write immediately or the mock server may respond differently,+ // we verify that the attribute is writable and configured correctly+ device = assetStorageService.find(device.getId(), true)+ def attr = device.getAttribute("floatWriteValue").get()+ def link = attr.getMetaItem(AGENT_LINK).get().getValue(ModbusAgentLink.class).get()++ // Verify the configuration uses 2 registers for write+ assert link.getRegistersAmount() == 2+ assert link.getWriteAddress()++ // Check if a write message was captured (may not always happen depending on timing)+ def msg = (latestWriteMessage.get() as ModbusMessage)?.unwrap(RegistersModbusMessage)+ if (msg != null) {+ assert msg.getCount() >= 1 // At least 1 register written+ }+ }++ when: "multi-register integer value is written"+ latestWriteMessage.set(null)+ assetProcessingService.sendAttributeEvent(new AttributeEvent(device.getId(), "dintWriteValue", 123456))++ then: "the attribute should be configured for multi-register write"+ conditions.eventually {+ device = assetStorageService.find(device.getId(), true)+ def attr = device.getAttribute("dintWriteValue").get()+ def link = attr.getMetaItem(AGENT_LINK).get().getValue(ModbusAgentLink.class).get()++ // Verify the configuration uses 2 registers for write+ assert link.getRegistersAmount() == 2+ assert link.getWriteAddress()+ }+ }++ def "Modbus TCP Test - Write With Polling Rate"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 15, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus TCP agent is created"+ def agent = new ModbusTcpAgent("Modbus TCP Polling Write Test")+ agent.setRealm(MASTER_REALM)+ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with continuous write (requestInterval + writeAddress, no readAddress) is created"+ def device = new ThingAsset("Polling Write Test Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ new Attribute<>("pollingWriteValue", ValueType.INTEGER, 42).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setRequestInterval(1000) // Write every 1000ms+ it.setWriteMemoryArea(ModbusAgentLink.WriteMemoryArea.HOLDING)+ it.setWriteAddress(400)+ // No readAddress = continuous write mode+ }+ )+ )+ )+ device = assetStorageService.merge(device)++ then: "write polling task should be created"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusTcpProtocol+ assert protocol != null+ assert protocol.writeIntervalMap.size() == 1+ }++++ and: "periodic writes should occur even without attribute events"+ int writeCount = 0+ latestWriteMessage.set(null)++ conditions.eventually {+ // Should receive at least 2 writes within timeout period (500ms interval)+ if (latestWriteMessage.get() != null) {+ writeCount+++ latestWriteMessage.set(null) // Reset for next write+ }+ assert writeCount >= 2+ }++ when: "attribute value is changed"+ device = assetStorageService.find(device.getId(), true)+ device.getAttribute("pollingWriteValue").ifPresent { attr ->+ attr.setValue(99)+ }+ device = assetStorageService.merge(device)+ Thread.sleep(1000) // Wait for value to be stored and next polling write++ then: "the new value should be written periodically"+ latestWriteMessage.set(null)+ conditions.eventually {+ def msg = (latestWriteMessage.get() as ModbusMessage)?.unwrap(RegistersModbusMessage)+ assert msg != null+ assert msg.getAddress() == 399 // PLC4X uses 0-indexed+ assert msg.dataDecodeUnsigned()[0] == 99 // Should write the updated value+ }++ def assetDatapointService = container.getService(org.openremote.manager.datapoint.AssetDatapointService.class)+ def attributeRef = new org.openremote.model.attribute.AttributeRef(device.getId(), "pollingWriteValue")++ then: "database should only store datapoints from value changes"+ conditions.eventually {+ // Query datapoints stored for this attribute - writeWithPollingRate should no extra datapoints for writes+ def datapoints = assetDatapointService.getDatapoints(attributeRef)+ println "Datapoints found: ${datapoints.size()}"+ datapoints.each { println " - timestamp: ${it.timestamp}, value: ${it.value}" }+ assert datapoints.size() == 2 // Should have 2 datapoint from value changes, not from periodic writes+ }+ }++ def "Modbus TCP Test - Write-Only Attribute (No Read Configuration)"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def assetProcessingService = container.getService(AssetProcessingService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus TCP agent is created"+ def agent = new ModbusTcpAgent("Modbus TCP Write-Only Test")+ agent.setRealm(MASTER_REALM)+ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++ when: "a device with write-only attribute is created (no read configuration)"+ def device = new ThingAsset("Write-Only Device")+ device.setRealm(MASTER_REALM)+ device.addOrReplaceAttributes(+ // Write-only attribute - no readMemoryArea, readValueType, or readAddress+ new Attribute<>("writeOnlyValue", ValueType.INTEGER, 555).addOrReplaceMeta(+ new MetaItem<>(AGENT_LINK, new ModbusAgentLink(agent.getId())+ .tap {+ it.setUnitId(1)+ it.setWriteMemoryArea(ModbusAgentLink.WriteMemoryArea.HOLDING)+ it.setWriteAddress(500)+ // No requestInterval = write on demand only+ }+ )+ )+ )+ device = assetStorageService.merge(device)++ then: "the attribute should be linked without errors"+ conditions.eventually {+ def protocol = agentService.getProtocolInstance(agent.id) as ModbusTcpProtocol+ assert protocol != null+ // No read polling tasks should be created for write-only attributes+ assert protocol.batchGroups.values().flatten().isEmpty()+ }++ when: "a write operation is performed"+ latestWriteMessage.set(null)+ assetProcessingService.sendAttributeEvent(new AttributeEvent(device.getId(), "writeOnlyValue", 777))++ then: "the write should be sent successfully"+ conditions.eventually {+ def msg = (latestWriteMessage.get() as ModbusMessage)?.unwrap(RegistersModbusMessage)+ assert msg != null+ assert msg.getUnitId() == 1+ assert msg.getAddress() == 499 // PLC4X uses 0-indexed (500-1)+ assert msg.dataDecodeUnsigned()[0] == 777 // Written value+ }+ }++ def "Modbus TCP Test - Partial Read Configuration Should Be Ignored"() {+ given: "expected conditions"+ def conditions = new PollingConditions(timeout: 10, delay: 0.2)++ when: "the container starts"+ def container = startContainer(defaultConfig(), defaultServices())+ def assetStorageService = container.getService(AssetStorageService.class)+ def agentService = container.getService(AgentService.class)++ and: "a Modbus TCP agent is created"+ def agent = new ModbusTcpAgent("Modbus TCP Partial Config Test")+ agent.setRealm(MASTER_REALM)+ agent.setHost("127.0.0.1")+ agent.setPort(modbusServerPort)+ agent = assetStorageService.merge(agent)++ then: "the agent should connect successfully"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }++++ and: "agent should remain in CONNECTED state (no exceptions thrown)"+ conditions.eventually {+ agent = assetStorageService.find(agent.getId())+ assert agent.getAttribute(Agent.STATUS).get().getValue().get() == ConnectionStatus.CONNECTED+ }+ }++}diff --git a/test/src/test/java/org/openremote/test/protocol/MockSerialChannel.java b/test/src/test/java/org/openremote/test/protocol/MockSerialChannel.javanew file mode 100644index 000000000..12d7a116b--- /dev/null+++ b/test/src/test/java/org/openremote/test/protocol/MockSerialChannel.java@@ -0,0 +1,269 @@+/*+ * Copyright 2025, OpenRemote Inc.+ *+ * See the CONTRIBUTORS.txt file in the distribution for a+ * full listing of individual contributors.+ *+ * This program is free software: you can redistribute it and/or modify+ * it under the terms of the GNU Affero General Public License as+ * published by the Free Software Foundation, either version 3 of the+ * License, or (at your option) any later version.+ *+ * This program is distributed in the hope that it will be useful,+ * but WITHOUT ANY WARRANTY; without even the implied warranty of+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the+ * GNU Affero General Public License for more details.+ *+ * You should have received a copy of the GNU Affero General Public License+ * along with this program. If not, see <http://www.gnu.org/licenses/>.+ */+package org.openremote.test.protocol;++import io.netty.channel.Channel;+import io.netty.channel.ChannelConfig;+import io.netty.channel.ChannelFuture;+import io.netty.channel.ChannelPromise;+import io.netty.channel.DefaultChannelConfig;+import io.netty.channel.oio.OioByteStreamChannel;+import net.bytebuddy.asm.Advice;+import org.openremote.agent.protocol.serial.JSerialCommDeviceAddress;++import java.io.IOException;+import java.io.InputStream;+import java.io.OutputStream;+import java.net.SocketAddress;+import java.util.concurrent.BlockingQueue;+import java.util.concurrent.LinkedBlockingQueue;+import java.util.concurrent.TimeUnit;++/**+ * Mock Serial Channel for testing serial-based protocols without actual hardware.+ * Extends OioByteStreamChannel just like JSerialCommChannel.+ * This channel simulates a serial port by using in-memory queues for data transfer.+ * Tests can configure a {@link DataHandler} to process outgoing data and generate responses.+ */+@SuppressWarnings("deprecation")+public class MockSerialChannel extends OioByteStreamChannel {++ private static final JSerialCommDeviceAddress LOCAL_ADDRESS = new JSerialCommDeviceAddress("localhost");+++ public interface DataHandler {+ void onDataWritten(byte[] data, ResponseCallback responseCallback);+ }++ public interface ResponseCallback {+ void sendResponse(byte[] response);+ }++ private static volatile DataHandler dataHandler = null;+ private final ChannelConfig config;+ private boolean open = true;+ private JSerialCommDeviceAddress deviceAddress;+ private final BlockingQueue<Byte> responseQueue = new LinkedBlockingQueue<>();+ private MockInputStream mockInputStream;+ private MockOutputStream mockOutputStream;++ public MockSerialChannel() {+ super(null);+ config = new DefaultChannelConfig(this);+ }++ public static void setDataHandler(DataHandler handler) {+ dataHandler = handler;+ }++ @Override+ public ChannelConfig config() {+ return config;+ }++ @Override+ public boolean isOpen() {+ return open;+ }++ @Override+ protected AbstractUnsafe newUnsafe() {+ return new MockUnsafe();+ }++ @Override+ protected void doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {+ deviceAddress = (JSerialCommDeviceAddress) remoteAddress;+ }++ protected void doInit() throws Exception {+ mockInputStream = new MockInputStream();+ mockOutputStream = new MockOutputStream();+ activate(mockInputStream, mockOutputStream);+ }++ @Override+ public JSerialCommDeviceAddress localAddress() {+ return (JSerialCommDeviceAddress) super.localAddress();+ }++ @Override+ public JSerialCommDeviceAddress remoteAddress() {+ return (JSerialCommDeviceAddress) super.remoteAddress();+ }++ @Override+ protected JSerialCommDeviceAddress localAddress0() {+ return LOCAL_ADDRESS;+ }++ @Override+ protected JSerialCommDeviceAddress remoteAddress0() {+ return deviceAddress;+ }++ @Override+ protected void doBind(SocketAddress localAddress) throws Exception {+ throw new UnsupportedOperationException();+ }++ @Override+ protected void doDisconnect() throws Exception {+ doClose();+ }++ @Override+ protected void doClose() throws Exception {+ open = false;+ try {+ super.doClose();+ } finally {+ responseQueue.clear();+ }+ }++ @Override+ protected boolean isInputShutdown() {+ return !open;+ }++ @Override+ protected ChannelFuture shutdownInput() {+ return newFailedFuture(new UnsupportedOperationException("shutdownInput"));+ }++ private void queueResponse(byte[] response) {+ if (response != null) {+ for (byte b : response) {+ responseQueue.offer(b);+ }+ }+ }++ private class MockInputStream extends InputStream {+ @Override+ public int read() {+ if (!open) return -1;++ try {+ Byte b = responseQueue.poll(50, TimeUnit.MILLISECONDS);+ if (b != null) {+ return b & 0xFF;+ }+ return -1;+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return -1;+ }+ }++ @Override+ public int read(byte[] b, int off, int len) {+ if (!open) return -1;+ if (len == 0) return 0;++ try {+ Byte first = responseQueue.poll(50, TimeUnit.MILLISECONDS);+ if (first == null) {+ // No data available - return 0 to indicate timeout without EOF+ return 0;+ }++ b[off] = first;+ int bytesRead = 1;++ // Read any additional available bytes without blocking+ while (bytesRead < len) {+ Byte next = responseQueue.poll();+ if (next == null) break;+ b[off + bytesRead] = next;+ bytesRead++;+ }++ return bytesRead;+ } catch (InterruptedException e) {+ Thread.currentThread().interrupt();+ return -1;+ }+ }++ @Override+ public int available() {+ return responseQueue.size();+ }+ }++ private class MockOutputStream extends OutputStream {+ @Override+ public void write(int b) {+ write(new byte[]{(byte) b}, 0, 1);+ }++ @Override+ public void write(byte[] b, int off, int len) {+ byte[] data = new byte[len];+ System.arraycopy(b, off, data, 0, len);++ DataHandler handler = dataHandler;+ if (handler != null) {+ handler.onDataWritten(data, MockSerialChannel.this::queueResponse);+ }+ }++ @Override+ public void flush() {+ // Nothing for mock+ }+ }++ private final class MockUnsafe extends AbstractUnsafe {+ @Override+ public void connect(+ final SocketAddress remoteAddress,+ final SocketAddress localAddress, final ChannelPromise promise) {+ if (!promise.setUncancellable() || !isOpen()) {+ return;+ }++ try {+ final boolean wasActive = isActive();+ doConnect(remoteAddress, localAddress);+ doInit();+ safeSetSuccess(promise);+ if (!wasActive && isActive()) {+ pipeline().fireChannelActive();+ }+ } catch (Throwable t) {+ safeSetFailure(promise, t);+ closeIfClosed();+ }+ }+ }++ /**+ * ByteBuddy Advice to intercept SerialIOClient.getChannelClass() and return MockSerialChannel.+ */+ public static class GetChannelClassAdvice {+ @Advice.OnMethodExit+ public static void exit(@Advice.Return(readOnly = false) Class<? extends Channel> returnValue) {+ returnValue = MockSerialChannel.class;+ }+ }+}