Skip to content

Commit

Permalink
fix: refactor_convert fn to handle both single and multiple args cases
Browse files Browse the repository at this point in the history
  • Loading branch information
Graziano Grespan committed Aug 18, 2024
1 parent 7db5698 commit b66cf3b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 33 deletions.
39 changes: 26 additions & 13 deletions apis/promise.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,20 +23,28 @@
* @private
*/
const _convert = function(f) {
const converted = function(address, arg, next) {
const converted = function(...args) {
const client = this;
const id = this._unitID;

/* the function check for a callback
* if we have a callback, use it
* o/w build a promise.
*/
if (next) {
// if we have a callback, use the callback
f.bind(client)(id, address, arg, next);
// The last argument might be the callback (next)
const next = args[args.length - 1];

// Determine if the last argument is actually a callback
const hasCallback = typeof next === "function";

if (hasCallback) {
// If there is a callback, call the function with the appropriate arguments
if (args.length === 1) {
// This case is used for client close method
f.bind(client)(next);
} else {
// This case is used for client writeFC methods
f.bind(client)(id, ...args);
}
} else {
// o/w use a promise
const promise = new Promise(function(resolve, reject) {
// Otherwise, use a promise
return new Promise(function(resolve, reject) {
function cb(err, data) {
if (err) {
reject(err);
Expand All @@ -45,10 +53,14 @@ const _convert = function(f) {
}
}

f.bind(client)(id, address, arg, cb);
if (args.length === 0) {
// This case is used for client close method
f.bind(client)(cb);
} else {
// This case is used for client writeFC methods
f.bind(client)(id, ...args, cb);
}
});

return promise;
}
};

Expand All @@ -73,6 +85,7 @@ const addPromiseAPI = function(Modbus) {
cl.getTimeout = function() {return this._timeout;};

// convert functions to return promises
cl.close = _convert(cl.close);
cl.readCoils = _convert(cl.writeFC1);
cl.readDiscreteInputs = _convert(cl.writeFC2);
cl.readHoldingRegisters = _convert(cl.writeFC3);
Expand Down
29 changes: 9 additions & 20 deletions index.js
Original file line number Diff line number Diff line change
Expand Up @@ -669,27 +669,16 @@ class ModbusRTU extends EventEmitter {
*
* @param {Function} callback the function to call next on close success
* or failure.
*/
*/
close(callback) {
return new Promise((resolve, reject) => {
const cb = (err) => {
if (callback) {
callback(err);
}
if (err) {
reject(err);
} else {
resolve();
}
};

if (this._port) {
this._port.removeAllListeners("data");
this._port.close(cb);
} else {
cb();
}
});
// close the serial port if exist
if (this._port) {
this._port.removeAllListeners("data");
this._port.close(callback);
} else {
// nothing needed to be done
callback();
}
}

/**
Expand Down

0 comments on commit b66cf3b

Please sign in to comment.