From 6c88392ea9487c9a53caa89804f6215ad960df87 Mon Sep 17 00:00:00 2001 From: Cristiano Aguzzi Date: Wed, 29 Nov 2023 21:22:46 +0100 Subject: [PATCH] fix(binding-modbus): clean up operations when timeout (#1173) If we don't clean up the queue and the application is looping trying to read modbus registers, the queue will grow indefinitely. This cleans up the queue when a timeout occurs (e.g. wrong remote host or not reachable). --- packages/binding-modbus/src/modbus-connection.ts | 12 +++++++----- .../binding-modbus/test/modbus-connection-test.ts | 3 +++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/packages/binding-modbus/src/modbus-connection.ts b/packages/binding-modbus/src/modbus-connection.ts index 86f6cc92b..11509e55f 100644 --- a/packages/binding-modbus/src/modbus-connection.ts +++ b/packages/binding-modbus/src/modbus-connection.ts @@ -282,12 +282,14 @@ export class ModbusConnection { this.trigger(); } catch (error) { warn("Cannot reconnect to modbus server"); - // inform all the operations that the connection cannot be recovered - this.queue.forEach((transaction) => { - transaction.operations.forEach((op) => { - op.failed(error instanceof Error ? error : new Error(JSON.stringify(error))); + // inform and clean up all the operations that the connection cannot be recovered + while (this.queue.length > 0) { + const transaction = this.queue.shift(); + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion -- queue.length > 0 + transaction!.operations.forEach((operation) => { + operation.failed(error instanceof Error ? error : new Error(JSON.stringify(error))); }); - }); + } } } else if (this.client.isOpen && this.currentTransaction == null && this.queue.length > 0) { // take next transaction from queue and execute diff --git a/packages/binding-modbus/test/modbus-connection-test.ts b/packages/binding-modbus/test/modbus-connection-test.ts index b6f54c518..3f0562b7f 100644 --- a/packages/binding-modbus/test/modbus-connection-test.ts +++ b/packages/binding-modbus/test/modbus-connection-test.ts @@ -82,6 +82,8 @@ describe("Modbus connection", () => { connection.enqueue(op); await op.execute().should.eventually.be.rejected; + connection.queue.length.should.equal(0); + connection.close(); }).timeout(5000); @@ -105,6 +107,7 @@ describe("Modbus connection", () => { connection.enqueue(op); await op.execute().should.eventually.be.rejected; + connection.queue.length.should.equal(0); connection.close(); }).timeout(5000);