Skip to content

Commit

Permalink
fix(binding-modbus): clean up operations when timeout (eclipse-thingw…
Browse files Browse the repository at this point in the history
…eb#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).
  • Loading branch information
relu91 authored Nov 29, 2023
1 parent 0a6463b commit 6c88392
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
12 changes: 7 additions & 5 deletions packages/binding-modbus/src/modbus-connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 3 additions & 0 deletions packages/binding-modbus/test/modbus-connection-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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);

Expand All @@ -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);
Expand Down

0 comments on commit 6c88392

Please sign in to comment.