Giter Club home page Giter Club logo

node-ads's Introduction

node-ads NPM Version node JavaScript Style Guide

A NodeJS implementation for the Twincat ADS protocol. (Twincat and ADS is from Beckhoff ©. I'm not affiliated.)

Changelog

  • debug module.
  • Added aliases: TOD -> TIME_OF_DAY and DT -> DATE_AND_TIME.
  • Code standardized.
  • Using safe-buffer.
  • When we use notification, the notification will blocked to fire if too many notifications are defined
  • multiRead method and read bug fix (timeout).
  • multiRead and getHandels method improved, multiWrite added.
  • working string length
  • array added

Requirements

  • Beckhoff PLC that has an ethernet connection and is connected to your LAN
    • Make your you give the PLC a fixed IP address
    • Make sure you can ping the PLC from another computer

Configuration

  1. Enable ADS on your PLC project. To do this click on your task and then enable the checkbox before Create symbols (if he is not disabled). In addition, you can still, under I/O Devices click on Image and go to the ADS tab. Check the Enable ADS Server and also Create symbols. Download the new configuration and make sure you reboot your PLC. The reboot is only needed when you are using TwinCat 2.

  2. Now add a static route to our Beckhoff PLC. The route should point to your server that will run the proxy application. It's also a good idea to add an extra static route that points to your local development device. This way you can test out the proxy from your development device too.

Attention

  1. TwinCAT AMS Router doesn't allow multiple TCP connections from the same host. So when you use two AdsLib instances on the same host to connect to the same TwinCAT router, you will see that TwinCAT will close the first TCP connection and only respond to the newest. If you start the TwinCat System Manager and Node-Red ADS on the same PC at the same time, Node-Red will not run anymore. You can set up a second IPv4 on the PC and assign to this a ADS NET ID under Twincat

  2. As ADS is transmitted over a TCP connection, there is no real time guarantee.

Examples

Hello machine

var ads = require('node-ads')

var options = {
    //The IP or hostname of the target machine
    host: "10.0.0.2",
    //The NetId of the target machine
    amsNetIdTarget: "5.1.204.160.1.1",
    //The NetId of the source machine.
    //You can choose anything in the form of x.x.x.x.x.x,
    //but on the target machine this must be added as a route.
    amsNetIdSource: "192.168.137.50.1.1",

    //OPTIONAL: (These are set by default)
    //The tcp destination port
    //port: 48898
    //The ams source port
    //amsPortSource: 32905
    //The ams target port for TwinCat 2 Runtime 1 
    //amsPortTarget: 801 
    //The ams target port for TwinCat 3 Runtime 1
    //amsPortTarget: 851 
    //The timeout for PLC requests
    //timeout: 500
    //The Local address the socket should connect from
    //localAddress: "192.168.137.50"
    //The Local port the socket should connect from
    //localPort: 50000
    //Version of IP stack. Must be 4, 6, or 0. The value 0 indicates that both IPv4 and IPv6 addresses are allowed. Default: 0
    //family: 4
}

var client = ads.connect(options, function() {
    this.readDeviceInfo(function(err, result) {
        if (err) console.log(err)
        console.log(result)
        this.end()
    })
})

client.on('error', function(error) {
    console.log(error)
})

Read something

var myHandle = {
    //Handle name in twincat
    symname: '.TESTINT',  
    //An ads type object or an array of type objects.
    //You can also specify a number or an array of numbers,
    //the result will then be a buffer object.
    //If not defined, the default will be BOOL.
    bytelength: ads.INT,  
    //The propery name where the value should be written.
    //This can be an array with the same length as the array length of byteLength.
    //If not defined, the default will be 'value'.     
    propname: 'value'      
}

var client = ads.connect(options, function() {
    this.read(myHandle, function(err, handle) {
        if (err) console.log(err)
        //result is the myHandle object with the new properties filled in
        console.log(handle.value)
        //All handles will be released automaticly here
        this.end()
    })
})

Write something

var client = ads.connect(options, function() {
    myHandle.value = 5
    this.write(myHandle, function(err) {
        if (err) console.log(err)
        this.read(myHandle, function(err, handle) {
            if (err) console.log(err)
            console.log(handle.value)
            this.end()
        })
    })
})

Get notifications

var myHandle = {
    symname: '.CounterTest',       
    bytelength: ads.WORD,  

    //OPTIONAL: (These are set by default)       
    //transmissionMode: ads.NOTIFY.ONCHANGE, (other option is ads.NOTIFY.CYCLIC)
    //maxDelay: 0,  -> Latest time (in ms) after which the event has finished
    //cycleTime: 10 -> Time (in ms) after which the PLC server checks whether the variable has changed
}

var client = ads.connect(options, function() {
    this.notify(myHandle)
})

client.on('notification', function(handle){
    console.log(handle.value)
})

process.on('exit', function () {
    console.log("exit")
})

process.on('SIGINT', function() {
    client.end(function() {
        process.exit()
    })
})

MultiRead something

var client = ads.connect(options, function() {
    this.multiRead(
        [{
            symname: '.TESTBOOL',
            bytelength: ads.BOOL,
        }, {
            symname: '.TESTINT',
            bytelength: ads.UINT,
        }],
        function (error, handles) {
            if (error) {
                console.log(error)
            } else {
                handles.forEach(function(handle){
                    if (handle.err) {
                        console.error(handle.err)
                    } else {
                        console.log(handle.value)
                    }
                }
            }
            this.end()
        })
    )
})

MultiWrite something

var client = ads.connect(options, function() {
    this.multiRead(
        [{
            symname: '.TESTBOOL',
            bytelength: ads.BOOL,
            value: false
       }, {
            symname: '.TESTINT',
            bytelength: ads.UINT,
            value: 5
        }],
        function (error, handles) {
            if (error) {
                console.log(error)
            } else {
                handles.forEach(function(handle){
                    if (handle.err) {
                        console.error(handle.err)
                    } else {
                        console.log(handle.value)
                    }
                }
            }
            this.end()
        })
    )
})

Get handles

var client = ads.connect(options, function() {
    this.getHandles(
        [{
            symname: '.TESTBOOL',
        }, {
            symname: '.TESTINT',
        }],
        function (error, handles) {
            if (error) {
                console.log(error)
            } else if (handles.err) {
                console.error(handles.err)
            } else {
                console.log(handles)
            }
            this.end()
        })
})

Get symbol list

var client = ads.connect(options, function() {
    this.getSymbols(function(err, symbols, false) {
        if (err) console.log(err)
        console.log(JSON.stringify(symbols, null, 2))
        this.end()
    })
})

Get datatyp list

var client = ads.connect(options, function() {
    this.getDatatyps(function(err, datatyps) {
        if (err) console.log(err)
        else console.log(JSON.stringify(datatyps, null, 2))
        this.end()
    })
})

Read device state

var client = ads.connect(options, function() {
    this.readState(function(error,result) {
      if (error) {
        consiole.log(error)
      } else {
        if (result.adsState == ads.ADSSTATE.RUN) {
          console.log('The PLC is lucky!')
        }
        console.log('The state is '+ads.ADSSTATE.fromId(result.adsState))
      }
      this.end()
    });
})

The following states are possible:

  ads.ADSSTATE.INVALID
  ads.ADSSTATE.IDLE
  ads.ADSSTATE.RESET
  ads.ADSSTATE.INIT
  ads.ADSSTATE.START
  ads.ADSSTATE.RUN
  ads.ADSSTATE.STOP
  ads.ADSSTATE.SAVECFG
  ads.ADSSTATE.LOADCFG
  ads.ADSSTATE.POWERFAILURE
  ads.ADSSTATE.POWERGOOD
  ads.ADSSTATE.ERROR
  ads.ADSSTATE.SHUTDOWN
  ads.ADSSTATE.SUSPEND
  ads.ADSSTATE.RESUME
  ads.ADSSTATE.CONFIG
  ads.ADSSTATE.RECONFIG
  ads.ADSSTATE.STOPPING

Event-Driven Detection of Changes to the Symbol Table

If the symbol table changes because, for instance, a new PLC program is written into the controller, the handles must be ascertained once again. The example below illustrates how changes to the symbol table can be detected.

var start = true;

var myHandle = {
    indexGroup: ads.ADSIGRP.SYM_VERSION,
    indexOffset: 0,
    bytelength: ads.BYTE,  
}

var client = ads.connect(options, function() {
    start = true;
    this.notify(myHandle);
})

client.on('notification', function(handle){
    if (start) {
      console.log('symbol table version '+handle.value)
    } else {
      console.log('symbol table changed '+handle.value)
    }
    
    start = false;
})

process.on('SIGINT', function() {
    client.end(function() {
        process.exit()
    })
})

client.on('error', function(error) {
    console.log(error)
})

Something about the handle

If the handle remains persistent (eg as a global object), when the end() function is called the symhandle must be deleted from the handle. Otherwise, the old non-existing syshandle is used in a new connection and triggers an error.

symname

Global variables must start with a dot: .engine Program variables must start with the programname: MAIN.UpTyp.timerUp.PT

Something about the bytelength

All possibilities of bytelength described here work with read, write, notificaton, multiread and multiwrite.

If you simply enter a number, reading a value returns a buffer object of length or expecting to write. This can be further processed with the standard functions of buffer.

This mehtode is called RAW read and write.

var myHandle = {
    symname: '.TestDoubleIntStruct',  
    bytelength: 2,  
    propname: 'value'      
}
var client = ads.connect(options, function() {
    myHandle.value = new Buffer(4)
    myHandle.value.writeInt16LE(5, 0)
    myHandle.value.writeInt16LE(5, 2)
    this.write(myHandle, function(err) {
        if (err) console.log(err)
        this.read(myHandle, function(err, handle) {
            if (err) console.log(err)
            console.log(handle.value)
            this.end()
        })
    })
})

There are also ready-made objects for reading and writing numeric variables:

  ads.BOOL
  ads.BYTE
  ads.WORD
  ads.DWORD
  ads.SINT
  ads.USINT
  ads.INT
  ads.UINT
  ads.DINT
  ads.UDINT
  ads.LINT
  ads.ULINT
  ads.REAL
  ads.LREAL

There are also ready-made objects for reading and writing date and time variables:

With this type it is possible to convert the time zone. There are two ways to control this feature. You can add the variable useLocalTimezone to the handle. This is true for defauld. Or you use the function ads.useLocalTimezone().

  ads.TIME
  ads.TIME_OF_DAY
  ads.TOD // TIME_OF_DAY alias
  ads.DATE
  ads.DATE_AND_TIME
  ads.DT // DATE_AND_TIME alias
var myHandle = {
    symname: '.TESTTIME',  
    bytelength: ads.useLocalTimezone(ads.TIME,false),  
    propname: 'value'      
}
var myHandle = {
    symname: '.TESTTIME',
    useLocalTimezone: false,
    bytelength: ads.TIME,  
    propname: 'value'      
}

The type ads.STRING is fix for 80 characters. Therefore you can use the ads.string(length) function.

var myHandle = {
    symname: '.SOMETEXT80',  
    bytelength: ads.STRING,  
    propname: 'value'      
}
var myHandle = {
    symname: '.SOMETEXT10',  
    bytelength: ads.string(10),  
    propname: 'value'      
}

There is also a possibility to read and write arrays. This is done via the function ads.array(type, lowIndex, hiIndex). The low index and the hi index must be the same as in the twincat definition On reading the Value is an array, on writing the Value must be an array. The array under node always starts with 0, independently as loIndex and hiIndex are given.

var myHandle = {
    symname: '.SOMEINTARREY',  
    bytelength: ads.array(ads.INT,0,9),  
    propname: 'value'      
}

You can also read and write structures. An array is passed for bytelength. Then an array with the same number of parameters is expected in propname. The structur is mapped binary, so it must be described exactly how it exists in the PLC.

var myHandle = {
    symname: '.SOMESTRUCTURE',  
    bytelength: [ ads.BOOL, 
                  ads.array(ads.INT,0,9),
                  ads.array(ads.string(10),0,9),
                  ads.array(ads.useLocalTimezone(ads.TIME,false),0,9)
                 ],  
    propname: ['value_a.bool',
               'value_a.arrayofint',
               'value_a.arrayofstring',
               'value_a.arrayoftime']
}

License (MIT)

Copyright (c) 2012 Inando

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

node-ads's People

Contributors

auspexeu avatar dkleber89 avatar herrjones avatar jozo132 avatar ortmann64 avatar plchome avatar roccomuso avatar sanderd17 avatar suizi11 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-ads's Issues

Socket closes after 10 seconds - Error: This socket has been ended by the other party

Hi there,

I am using the notify method this to read position feedback from axes, however i am finding that the socket connection closes after approx 10 seconds.

 const options = {
    host: '10.4.4.1',
    amsNetIdTarget: '10.4.4.1.1.1',
    amsNetIdSource: '10.4.4.2.1.1',
  };

// Reading this...
  var myHandle = {
    symname: 'GVL.fbRevolve.rPosition',
    bytelength: ads.LREAL,
  };

    var client = ads.connect(options, function() {
      this.notify(myHandle);
    });

  client.on('notification', function(handle) {
    console.log(handle.value);
  });

  client.on('close', function(data) {
    console.log('CLOSE', data);
  });

 client.on('error', function(err) {
    console.log('Error: ', err);
  });

This works correctly for about 10 seconds before the socket is closed.

I thought it may have been a timeout somewhere, maybe the client not sending data frequently enough(?), so have added the following:

var client = ads.connect(options, function() {
      this.notify(myHandle);

setInterval(() => {
        this.readDeviceInfo(function(err, result) {
          if (err) console.log('Error: ', err);
          console.log('\nreadDeviceInfo: ', result);
          // this.end();
        });
      }, 1000);
    });

however after about 10 seconds the following gets thrown:

Error: Error: This socket has been ended by the other party
at Socket.writeAfterFIN [as write] (net.js:407)
at Object.runCommand (ads.js:1014)
at Object.readDeviceInfo (ads.js:295)
at EventEmitter.ads.adsClient.readDeviceInfo (ads.js:60)
at renderer.js:153

Any Ideas how to keep the connect open?

Thanks,
Jon

Couldn't write array to beckhoff machines.

Hi @PLCHome ,
I was trying to use the the write array handle to pass the array to the beckhoff machine.
But when I pass the array I got an exception of 'Property value not available on handle!'
Here is the handle that I pass through:
var myHandle = {
symname: 'LLC.arrayOperationToolId',
bytelength: ads.array(ads.INT,0,9),
value: [0,1,2,3,4,5,6,7,8],
propname: 'value'
}
The low index and high index is the same register in the twincat and the name is the same as well.
Other than array everything works fine.
Did I do something wrong?

Notifications don't work

When I tried notifications, I could read the value with a handle, but I was never notified of changes.

Apparently, at line 198, there's a condition that never gets satisfied for notifications:

if (ads.pending[invokeId]) {

It isn't invoked from the library, so there's no pending object and no callback.

Adding these two lines made the notifications work.

  if (commandId == ID_NOTIFICATION) {
	getNotificationResult.call(this, data)
  } else if (ads.pending[invokeId]) //...

Some additional cleanup (like the removing the case and check referencing ID_NOTIFICATION) might be needed.

getSymbols bug fix is not available on npm

Hello Mister Musolino
When I do an update with npm I do receive version 1.4.3 of node-ads but unfortunately the getSymbols bugfix you did at 25 Sep 2018 is not contained. Could you please have a look at this.
Thanks for your help and another thanks for your library. It looks much better to me than the TcAdsWebService stuff from Beckhoff. Good job!
Best regards
Markus Hardardt

Read / Write / Notify on Index Group / Offset

It would be nice to be able to create a handle using an index group and offset.

For example:
When connecting to port 100 (logger), you can do an Add Device Notification on 0x1 / 0xffff to get notifications of the ADSLOGSTR(), the ones that are normally logged to the event viewer.

Notifications don't work

The pull request from sanders17 seems to be ok...
when does it come on the master branch and npm install?

multiWrite: Error: parameter size not correct

Hi @PLCHome ,

I was trying to use multiWrite to pass the array to the beckhoff machine.
But when I pass the array I got an exception of 'parameter size not correct'
Here is the handle that I pass through:

var myHandle = [{
symname: 'Main.b',
bytelength: ads.INT,
value: 200
}, {
symname: 'Main.c',
bytelength: ads.BOOL,
value: true
}]

Did I do something wrong?

multiRead - Error: parameter size not correct

Hi, i have a problem by using the multiRead method, i tried different things and also only one value, but it's returning every time only the error message Error: parameter size not correct. What i'm doing wrong?
The communication itself is working well so far. Single values are working as expected.

I'm using a Beckhoff TwinCAT v2.11.

var ads = require('node-ads')

var options = {
    host: "192.168.1.174",
    amsNetIdTarget: "10.0.0.105.1.1",
    amsNetIdSource: "192.168.137.50.1.1",
}

var client = ads.connect(options, function() {
    this.notify({
        symname: '.AI_Light_Sensor',       
        bytelength: ads.INT
    });

    this.notify({
        symname: '.PT_Temp_Sensor',       
        bytelength: ads.INT
    });

    this.read({
        symname: '.AI_Light_Sensor',       
        bytelength: ads.INT,  
    }, function(err, handle) {
        if (err) console.log(err)
        	console.log(handle.value)
    });

    this.read({
        symname: '.PT_Temp_Sensor',       
        bytelength: ads.INT,  
    }, function(err, handle) {
        if (err) console.log(err)
        	console.log(handle.value)
    });

    this.multiRead([
		{
	        symname: '.DO_Lamp_1',       
	        bytelength: ads.BOOL,  
	    }, {
	        symname: 'MAIN.test',       
	        bytelength: ads.BOOL,  
	    }, {
	        symname: '.DI_Button',       
	        bytelength: ads.BOOL,  
	    }, {
	        symname: '.AI_Light_Sensor',       
	        bytelength: ads.INT,  
	    }, {
	        symname: '.PT_Temp_Sensor',       
	        bytelength: ads.INT,  
	    }, {
	        symname: '.DIM_Lamp_2',       
	        bytelength: ads.INT,  
	    }, {
	        symname: '.GLOBAL_Dimmer_1',       
	        bytelength: ads.INT,  
	    }
	], 
    function(err, handle) {
        if (err) console.log(err)
        	console.log(handle)
    });
});

client.on('notification', function(handle){
    console.log(handle)
})

process.on('exit', function () {
    console.log("exit")
})

process.on('SIGINT', function() {
    client.end(function() {
        process.exit()
    })
})

client.on('error', function(error) {
    console.log(error)
})

This is the error message on the console:

{ options:
   { host: '192.168.1.174',
     amsNetIdTarget: '10.0.0.105.1.1',
     amsNetIdSource: '192.168.137.50.1.1',
     port: 48898,
     amsPortSource: 32905,
     amsPortTarget: 801,
     verbose: 0 },
  invokeId: 9,
  pending:
   { '6': { cb: [Function], timeout: [Object] },
     '7': { cb: [Function], timeout: [Object] },
     '8': { cb: [Function], timeout: [Object] },
     '9': { cb: [Function], timeout: [Object] } },
  symHandlesToRelease:
   [ <Buffer 44 00 00 f7>,
     <Buffer 44 00 00 f7>,
     <Buffer 63 02 00 f7>,
     <Buffer a3 00 00 f7> ],
  notificationsToRelease: [],
  notifications: {},
  dataStream: null,
  tcpHeaderSize: 6,
  amsHeaderSize: 32,
  adsClient:
   EventEmitter {
     connect: [Function],
     end: [Function],
     readDeviceInfo: [Function],
     read: [Function],
     write: [Function],
     notify: [Function],
     writeRead: [Function],
     getSymbols: [Function],
     multiRead: [Function],
     _eventsCount: 2 },
  tcpClient:
   Socket {
     connecting: false,
     _hadError: false,
     _handle:
      TCP {
        reading: true,
        owner: [Circular],
        onread: [Function: onread],
        onconnection: null,
        writeQueueSize: 0 },
     _parent: null,
     _host: null,
     _readableState:
      ReadableState {
        objectMode: false,
        highWaterMark: 16384,
        buffer: [Object],
        length: 0,
        pipes: null,
        pipesCount: 0,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: false,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        resumeScheduled: false,
        destroyed: false,
        defaultEncoding: 'utf8',
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null },
     readable: true,
     domain: null,
     _events:
      { end: [Object],
        finish: [Function: onSocketFinish],
        _socketEnd: [Function: onSocketEnd],
        data: [Function],
        timeout: [Function],
        error: [Function] },
     _eventsCount: 6,
     _maxListeners: undefined,
     _writableState:
      WritableState {
        objectMode: false,
        highWaterMark: 16384,
        finalCalled: false,
        needDrain: false,
        ending: false,
        ended: false,
        finished: false,
        destroyed: false,
        decodeStrings: false,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function: bound onwrite],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 3,
        prefinished: false,
        errorEmitted: false,
        bufferedRequestCount: 0,
        corkedRequestsFree: [Object] },
     writable: true,
     allowHalfOpen: false,
     _bytesDispatched: 595,
     _sockname: null,
     _pendingData: null,
     _pendingEncoding: '',
     server: null,
     _server: null,
     read: [Function],
     _consuming: true,
     [Symbol(asyncId)]: 6,
     [Symbol(bytesRead)]: 0 },
  dataCallback: [Function] }
Error: parameter size not correct
    at getError (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:1245:13)
    at Object.getWriteReadResult (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:760:13)
    at Object.analyseResponse (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:235:28)
    at Object.checkResponseStream (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:173:25)
    at Object.analyseResponse (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:241:23)
    at Object.checkResponseStream (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:173:25)
    at Object.analyseResponse (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:241:23)
    at Object.checkResponseStream (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:173:25)
    at Object.analyseResponse (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:241:23)
    at Object.checkResponseStream (/Users/oVi/dev/src-one/homecontrol/node_modules/node-ads/lib/ads.js:173:25)

Error: "Ads Register Notification timeout

Hi there

I have following problem:

i have set up a Project, that have around 350 ads nodes. (ADS Notification and ADS Outputs). -->i mean, thats under the Limit of the readme..

When i restart the PLC, everything is ok. But from the 1st or 2nd Deploy in Node-RED i have following Errors: (@every Deploy and peridically)

"Ads Register Notification timeout".
Sometimes followed by:
"Ads write timeout" and / or "This socket has been ended by the other party"
I have tried to set the timeout in the ads config node to 2000ms with the same result.

Node-RED: v1.0.3
Nodejs: 11.9.0
ADS: 1.1.22

My Node-RED is Running in a Docker Container on a Raspberry Pi and the PLC is Running on a CX5120 in the same Network.

It seems as the connection doesn't close correctly or something like that. Do you have an idea what can be wrong?

--> You can see here the start discussion: PLCHome/node-red-contrib-ads#25 (comment)

maybe, you can fix that problem in the api..?

Reliability Question and Connection Problem

Hi @roccomuso,

I am thinking about using your module to talk to a Beckhoff PLC. Do you use this module yourself and is it considered to be stable?

I tried to connect to TwinCAT3 on my Virtual Machine but wasn't very successfull. Wireshark said the connection was established successfully. I also added a project route and set the amsPortTarget to 851 (due to TwinCAT3) but no luck. I always experience a timeout in the error handler.

use multi read

Hi
How can I use the multi read function? Tried to pass the handle as array, but didn't work.
Thank's for your advice.
Regards Heleon

How to access local ads server?

I have successfully accessed remote ads target. But if I want to access target on the same machine(node app and target are same PC), then I get timeout.

var options = {
    host: "10.10.2.100",
    amsNetIdTarget: "10.10.2.100.1.1",
    amsNetIdSource: "10.10.2.100.1.1",
    amsPortTarget: 801
}

var myHandle = {
    symname: '.NoBeam',
    bytelength: ads.BOOL,  
    propname: 'value'      
}
var client = ads.connect(options, function() {
    this.read(myHandle, function(err, handle) {
        if (err) console.log(err)
        else console.log(handle.value)
        this.end()
    })
})

yields to timeout message printed only.
10.10.2.100 (and I also tried 127.0.0.1) added into static routing table.

Using TC2.

Typescript, Testing, Linting

Typescript is mentioned in another issues here #14 (comment) and it's suggested that it would take a complete rewrite.

Not necessarily. The non-typing syntax of TypeScript is JavaScript. I've changed many projects (mostly non-OSS) over from JS to TS and it's relatively painless (especially if they are smaller, e.g. <10kLOC). I find that the only things I end up changing, other than adding types, are things that should have changed anyway, but weren't apparent without the types.

I think there is a significant benefit to both provide typing for end users as well as maintaining types in the project for future maintenance.

TypeScript can also address older node compliance (also mentioned in other issues/PR) by have TS compile to an earlier version of JS for publishing on NPM while allowing the source code to be maintained with the latest syntax.

I'd also like to see the addition of unit testing and linting to the project.

Would any or all of these changes (typing, testing, linting) be entertained?

ECONNRESET or timeout when trying to access remote TwinCAT

I have my laptop(192.168.0.120) connected over local network to a Win10 PC (192.168.0.208) running TwinCAT 3.

I am trying to do a readDeviceInfo as described in the documentation ("Hello Machine") with options set like this:

 var options = {
    host: "192.168.0.208",
    amsNetIdTarget: "192.168.0.208.1.1",
    amsNetIdSource: "10.0.75.1.1.1",
    amsPortTarget: 801,
    timeout: 10000
}

I tried to add the route on the target PC via the Router UI, but it would silently fail (TwinCAT beginner here). So I ended up adding a static route to the StaticRoutes.xml file and it looks like this:

<Route>
	<Name>RemoteClient</Name>
	<Address>192.168.0.120</Address>
	<NetId>10.0.75.1.1.1</NetId>
	<Type>TCP_IP</Type>
	<Flags>32</Flags>
</Route>

When I run the simple js to execute read the device info, I get
{ Error: read ECONNRESET
at TCP.onread (net.js:622:25) errno: 'ECONNRESET', code: 'ECONNRESET', syscall: 'read' }
or timeout

Wireshark shows that the laptop (RemoteClient) sends the DeviceInfoRequest, but the target PC promptly closes the connection.
image

From what I understand, add the route on the target PC essentially authorizes the client to connect. I am guessing that's where my problem lies, but I am unable to solve it.

Any ideas?
Thanks!

I use a CX5020 for my trials and also have problems to connect

Hello @roccomuso ,
I use a CX5020 for my trials and also have problems to connect. I tried a several times different combinations of Adresses NetIds and ports but no success. Here are the error messages I face:
"Error ADS: Error: connect ECONNREFUSED 192.168.137.235:48898"
"Error readDeviceInfo: timeout"
"Ads Register Notification live tick timeout"
"Ads Register Notification Sym Tab timeout"

the ECONNREFUSED message sometimes dissappears suddenly but also suddenly comes back without having made any config changes.

Originally posted by @Wolfskammer04 in #1 (comment)

Occasional "Symbol not found"

I have an app which is periodically writing few variables in PLC. The period is every 5 minute.

var options = {
    host: "127.0.0.1",
    amsNetIdTarget: "10.10.2.100.1.1",
    amsNetIdSource: "10.10.2.100.1.15",
    amsPortTarget: 801
}

var client = ads.connect(options, function() {
                    WriteAds(client, values[0]).
                    then(() => WriteAds(client, values[1])).
                    then(() => WriteAds(client, values[2])).
                    then(() => WriteAds(client, values[3])).
                    then(() => WriteAds(client, values[4])).
                    then(() => WriteAds(client, values[5])).
                    then(() => WriteAds(client, values[6])).
                    then(() => WriteAds(client, validityHandle)).
                    catch((err) => { 
                        log.error("Error writing to ADS: ", err);
                    }).
                    finally(() => ReleaseAndDisconnect(client))
                })

function ReleaseAndDisconnect(client)
{
    return new Promise(function(resolve, reject){
        client.end(function (){ resolve() })
        resolve()
    })
}

function WriteAds(client, h)
{
    return new Promise(function(resolve, reject){
        client.write(h, function(err) {
            if (err) 
            {
                reject(err)
            }
            else
            {
                resolve()
            }
        })
    })
}


As you can see, there are 6 handles in array and 1 standalone handle. This is the exception

Error writing to ADS: symbol not found
Error: symbol not found
    at getError (C:\pkg\node_modules\node-ads\lib\ads.js:1290:13)
    at Object.getWriteResult (C:\pkg\node_modules\node-ads\lib\ads.js:792:13)
    at Object.analyseResponse (C:\pkg\node_modules\node-ads\lib\ads.js:224:24)
    at Object.checkResponseStream (C:\pkg\node_modules\node-ads\lib\ads.js:177:25)
    at Socket.<anonymous> (C:\pkg\node_modules\node-ads\lib\ads.js:116:25)
    at emitOne (events.js:116:13)
    at Socket.emit (events.js:211:7)
    at addChunk (_stream_readable.js:263:12)
    at readableAddChunk (_stream_readable.js:250:11)
    at Socket.Readable.push (_stream_readable.js:208:10)

It happens on standalone variable. Variables before are written just fine.

I captured ADS traffic and can see that ADSIGRP_SYM_HNDBYNAME is called for all variables following ADSIGRP_SYM_VALBYHND, except last one. The last one only received ADSIGRP_SYM_VALBYHND without prior ADSIGRP_SYM_HNDBYNAME. Not sure where index/offset was discovered, but there is some value. Is it cached somewhere?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.