Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cancel pending transactions when calling destroy #521

Merged
merged 10 commits into from
Oct 23, 2023
Merged

Conversation

AndreMaz
Copy link
Contributor

@AndreMaz AndreMaz commented Oct 23, 2023

This PR cancels pending transactions (under the hood calls clearTimeout() ) when the destroy() method is called.

Rationale, after destroy() is called it does not make sense to wait for a response hence we need to cancel all pending requests.

How to test:

  • On modbus-sever, add a delay of 10secs on getHoldingRegister()
  • Set client timeout to 7 secs
  • Call readHoldingRegisters() in the example below
  • after 5 secs try to destroy the client

Repro example

"use strict";

const ModbusRTU = require("../index");
const client = new ModbusRTU();

async function main() {
  try {
    await client.connectTCP("127.0.0.1", { port: 8502 });
    console.log("Connected");
    client.setID(1);
    client.setTimeout(7_000);

    // Disconnect after 5 seconds
    setTimeout(async () => {
      try {
        console.log(`Destroying connection at ${new Date().toISOString()}`);
      await new Promise((resolve, reject) => {
        // Try to close the connection
        client.destroy((err) => {
          if (err) return reject(err);

          console.log(`Destroyed closed at ${new Date().toISOString()}`);
          return resolve();
        });
      });
      } catch (error) {
        console.log(`Failed to destroy connection: ${error.message} at ${new Date().toISOString()}`);
      }
      
    }, 5000);

    await readRegistersOneByOne();
  } catch (error) {
    console.log(error.message);
  } finally {
    client.close();
  }
}

const spec = {
  telemetry: {
    regA: {
      address: 1,
      registerCnt: 1,
    },
  },
};

async function readRegistersOneByOne() {
  for (const [key, { address, registerCnt }] of Object.entries(
    spec.telemetry
  )) {
    try {
      console.log(`Reading registers at ${address} with ${registerCnt} registers`);
      const data = await client.readHoldingRegisters(address, registerCnt);
      console.log(key, data.buffer);
    } catch (error) {
      console.log(error);
    }
  }
}

main();

Without "cleanup"
image

With "cleanup"
image

index.js Outdated Show resolved Hide resolved
@yaacov yaacov merged commit 0b6a7d8 into yaacov:master Oct 23, 2023
2 checks passed
@yaacov
Copy link
Owner

yaacov commented Oct 23, 2023

Thank you for the pull request 💚

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants