plcpeople / nodeS7

Node.JS library for communication to Siemens S7 PLCs
MIT License
363 stars 122 forks source link

How to use read values #71

Closed socramone closed 5 years ago

socramone commented 5 years ago

Hi! First of all I want to thank you for your proyect and for sharing it!

I am using writing funtion and it works perfectly.

My doubt is about reading values, I can read values from PLC but I dont know how I can use them to make some conditions in my program.

My problem is I can't compare "values" value with anything.

if (values === "TEST5: 1") {

Can you help me?

Thanks ni advance.

I post my code:

var nodes7 = require('nodes7');  // This is the package name, if the repository is cloned you may need to require 'nodeS7' with uppercase S
var conn = new nodes7;
var doneReading = false;
var doneWriting = false;

var variables = { 
            TEST1: 'MR4',           // Memory real at MD4
            TEST4: 'DB4,REAL0',     // Array of 20 values in DB1
            TEST5: 'DB6,REAL0',     // Single real value
                };

conn.initiateConnection({port: 102, host: '192.168.0.150', rack: 0, slot: 1}, connected); // slot 2 for 300/400, slot 1 for 1200/1500
//conn.initiateConnection({port: 102, host: '192.168.0.2', localTSAP: 0x0100, remoteTSAP: 0x0200, timeout: 8000}, connected); // local and remote TSAP can also be directly specified instead.  The timeout option specifies the TCP timeout.

function connected(err) {
    if (typeof(err) !== "undefined") {
        // We have an error.  Maybe the PLC is not reachable.
        console.log(err);
        process.exit();
    }
    conn.setTranslationCB(function(tag) {return variables[tag]; });     // This sets the "translation" to allow us to work with object names
    conn.addItems(['TEST5']);
    conn.writeItems('TEST4', [ 30 ], valuesWritten);  // You can write a single array item too.
    conn.readAllItems(valuesReady);
}

function valuesReady(anythingBad, values) {
        if (anythingBad) { console.log("SOMETHING WENT WRONG READING VALUES!!!!"); }
        console.log(values);

    if (values === "TEST5: 1") {

        console.log("Escribiendo en PLC DB4: 20")
        conn.writeItems('TEST4', [ 20 ], valuesWritten); 
        }

    doneReading = true;
    if (doneWriting) { process.exit(); }
}

function valuesWritten(anythingBad) {
    if (anythingBad) { console.log("SOMETHING WENT WRONG WRITING VALUES!!!!"); }
    console.log("Done writing.");
    doneWriting = true;
    if (doneReading) { process.exit(); }
}

![Uploading Captura de pantalla 2018-11-04 a las 20.32.16.png…]()

gfcittolin commented 5 years ago

Hi, values is a Javascript object, so if you want to access the value of TEST5, you could do either

if (values.TEST5 == 1) {
  //do sth
}

or

if (values["TEST5"] == 1) {
  //do sth
}
socramone commented 5 years ago

It works! Thank you so much!