yaacov / node-modbus-serial

A pure JavaScript implemetation of MODBUS-RTU (and TCP) for NodeJS
ISC License
620 stars 238 forks source link

Global Variable #406

Closed lekhoi99 closed 3 years ago

lekhoi99 commented 3 years ago

How can I set Data from Client.readHoldingRegisters as Global Variable ?

yaacov commented 3 years ago

Hi, thank you for the question, I setup the "help wanted" label in case someone can help.

yaacov commented 3 years ago

can you post a little example code, explaining what you want to do ?

lekhoi99 commented 3 years ago

I want to get Data from Modbus RTU and then put it to OPC UA Protocol My code :

const getMeterValue = async (id) => {
    try {
        // set ID of slave
        await client.setID(id);
        // read the 1 registers starting at address 0 (first register)
        let val = await client.readHoldingRegisters(23, 37);
        // return the value
    } catch (e) {
        // if error return -1
        return -1
    }
}

const sleep = (ms) => new Promise(resolve => setTimeout(resolve, ms));

// start get value
getMetersValue(metersIdList);

// node OPC UA
const { OPCUAServer, Variant, DataType, StatusCodes } = require("node-opcua");
(async () => {

    // Let's create an instance of OPCUAServer
    const server = new OPCUAServer({
        port: 4880, // the port of the listening socket of the server
        buildInfo: {
            productName: "MySampleServer1",
            buildNumber: "7658",
            buildDate: new Date(2014, 5, 2)
        }
    });
    await server.initialize();
    console.log("initialized");

    const addressSpace = server.engine.addressSpace;
    const namespace = addressSpace.getOwnNamespace();

    // declare a new object
    const device1 = namespace.addObject({
        organizedBy: addressSpace.rootFolder.objects,
        browseName: "Inverter 1"
    });

    namespace.addVariable({
        componentOf: device1,
        browseName: "Frequency Output",
        dataType: "Double",
        value: {
            get: () => new Variant({ dataType: DataType.Double, value: val.data[0] })
        }
    });
})();

But val isn't Defined

can you post a little example code, explaining what you want to do ?

yaacov commented 3 years ago

did you try defining val as a global var ?

let var = ...
...
   var = await client.readHoldingRegisters(23, 37);
...
lekhoi99 commented 3 years ago

did you try defining val as a global var ?

let var = ...
...
   var = await client.readHoldingRegisters(23, 37);
...

I tried. But it doesn't work