Skip to content

Commit b37345e

Browse files
Optimize slave address setting in mbpoll loop
Avoid calling `modbus_set_slave` if the slave address is already set to the desired value. This reduces redundant function calls during polling, improving efficiency. The change introduces a check using `modbus_get_slave` before calling `modbus_set_slave`. The error handling logic is preserved. Verified functionality and performance with a local Modbus TCP server. The behavior remains correct. Co-authored-by: zknpr <96851588+zknpr@users.noreply.github.com>
1 parent 0d5b8ec commit b37345e

1 file changed

Lines changed: 6 additions & 4 deletions

File tree

src/mbpoll.c

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -997,10 +997,12 @@ main (int argc, char **argv) {
997997
// Read -------------------------------------------------------------
998998
for (i = 0; i < ctx.iSlaveCount; i++) {
999999

1000-
iRet = modbus_set_slave (ctx.xBus, ctx.piSlaveAddr[i]);
1001-
if (iRet != 0) {
1002-
vIoErrorExit ("Setting slave address failed: %s",
1003-
modbus_strerror (errno));
1000+
if (modbus_get_slave (ctx.xBus) != ctx.piSlaveAddr[i]) {
1001+
iRet = modbus_set_slave (ctx.xBus, ctx.piSlaveAddr[i]);
1002+
if (iRet != 0) {
1003+
vIoErrorExit ("Setting slave address failed: %s",
1004+
modbus_strerror (errno));
1005+
}
10041006
}
10051007
ctx.iTxCount++;
10061008

0 commit comments

Comments
 (0)