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);