Have a problem trying to pass an object as context from one module to the next:
this is how my flow should work and i think i'm missing something or just woke up dumb today :D
module.exports = dixell = { // Dixell lib
fns: {
slaveType: async (adr) => {
let type;
try {
client.setID(adr);
type = await client.readHoldingRegisters(1,2);
let mswordMsbyte = String.fromCharCode(parseInt(type.data[0].toString(2).slice(0,-8), 2));
let lswordCode = parseInt(registers.data[1].toString(2).slice(0,-6), 2);
return `${mswordMsbyte}${lswordCode}`;
} catch(err) {
console.log(err)
}
}
}
}
^^ 1st module holds the function. to this function i try to bind an object as this
by invoking it on another module with call()
const ModbusRTU = require('modbus-serial');
const client = new ModbusRTU(); // this creates the object i want to pass
const dixell = require('../../libraries/dixell');
// sleep function
const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));
client.connectRTUBuffered('COM3', { baudRate: 9600 });
module.exports = exports = {}
exports.plcQueueFns = async (adr, fns) => {
let data = {};
for(let fn of fns) {
console.log(typeof(client))
data[fn.key] = await fn.fn(adr);
await sleep(10);
}
return data;
}
exports.getPayload = async (plantid) => {
let adrs = await exports.getPlcs();
let devices = [];
for (let adr of adrs) {
try {
let fnsdata = await exports.plcQueueFns(adr, [
{key: 'type', fn: dixell.fns.slaveType},
]);
}
}
^^ on the 2nd module i have a function called getPayload
that starts a loop and runs other functions in a loop with plcQueueFns
but i can't get to pass context i've tried :
in getPaylod
to send the function like this
{key: 'type', fn: dixell.fns.slaveType.bind(client)}
> not working
i also tried in plcQueueFns
to invoke it with
data[fn.key] = await fn.fn.call(client, adr)
> Still nothing
in slaveType()
i get {}
for this
and this error comes up
ReferenceError: client is not defined
Please advice . what am i doing wrong or missing ?
thanks in advance