Giter VIP home page Giter VIP logo

node-opcua / node-opcua Goto Github PK

View Code? Open in Web Editor NEW
1.4K 84.0 477.0 41.77 MB

Unlocking the Full Potential of OPC UA with Typescript and NodeJS - http://node-opcua.github.io/

License: MIT License

JavaScript 17.00% Makefile 0.01% Batchfile 0.02% XSLT 0.04% Shell 0.04% TypeScript 82.88% Dockerfile 0.01%
iot-platform opc-ua node-opcua nodejs javascript iiot m2m iec-62541 industrial-automation industry-4

node-opcua's Introduction

node-opcua

node-opcua is a full OPC UA stack for NodeJS and the Browser written in Typescript.

NPM version Node.js CI lerna Coverage Status Gitter chat The Book

NPM download - server NPM download - server -total

NPM download - client NPM download - client -total

Financial contributors

Become a sponsor

Node-opcua is the OPC-UA stack running on NodeJS.

Why NodeJS ?

Because NodeJs is a great framework for designing high-performing asynchronous applications.

Getting started

installing node-opcua as a node package

$ mkdir mytest
$ cd mytest
$ npm init 
$ npm install node-opcua --unsafe-perms
$ # Create your first app.js file!

installing node-opcua samples as a node package

$ mkdir myserver
$ cd myserver
$ npm init
$ npm install node-opcua-samples --unsafe-perms
$ ./node_modules/.bin/simple_server

or

$ ./node_modules/.bin/simple_client  -e "opc.tcp://opcserver.mAutomation.net:4841" -n="ns=1;s=EVR2.system.RTC_SEC"

or

$ ./node_modules/.bin/simple_client  -e "opc.tcp://opcuademo.sterfive.com:26543" 

Minimum Nodejs requirement

  • Nodejs version 18 or above

tutorials and guided examples

The Book. This book provides a large number of practical and ready-to-use and fully documented examples. It's the best starting point to learn about node-opcua.

Sponsors & Backers

The funding of node-opcua entirely relies on its users.
We appreciate that, once you have evaluated the software and you have decided to use it in one of your applications, you consider supporting our effort by either financially contributing to one of our sponsor programs:

Grants ensure the following:

  • πŸ”¨ Long-term maintenance of the project
  • βš™οΈ maintain the website and continuous integration platform
  • πŸ›£ Progress on the road map
  • πŸ› Quick responses to bug reports
  • πŸš€ New features & enhancements
  • βš–οΈ representing the node-opcua user community at the OPC Foundation

Sponsors

Backers

Thank you to all our backers! Become a backer

Contributors

This project exists thanks to all the people who contribute.

Getting professional support

To get professional support, consider subscribing to the node-opcua membership community:

Professional Support

Registered members have access to an extended set of online documentation.

Registered members can post and query Sterfive for any question related to NodeOPCUA in a private chat room.

or contact sterfive for dedicated consulting and more advanced support or for a certified version of node-opcua. ([email protected]).

Road-map

If your company would like to participate and influence the development of future versions of node-opcua please contact sterfive.

Those are the items we would like to achieve in the next version of the API.

  • improved documentation
  • Compliance testing and certification (CTT)
  • Pub-sub support
  • support for redundancy
  • session-less transactions
  • WebSocket transport
  • JTokens and OAuth
  • reversed connection
  • more tutorials

Advanced topics

installing node-opcua from source

running the demo server from source

 $ git clone https://github.com/node-opcua/node-opcua.git
 $ cd node-opcua
 $ npm install -g pnpm 
 $ pnpm recursive install
 $ pnpm build
 $ node packages/node-opcua-samples/bin/simple_server

running the demo client from source

 $ git clone https://github.com/node-opcua/node-opcua.git
 $ cd node-opcua
 $ npm install -g pnpm 
 $ pnpm recursive install
 $ pnpm build
 $ node packages/node-opcua-samples/bin/simple_client.js -e "opc.tcp://opcserver.mAutomation.net:4841" -n="ns=1;s=EVR2.system.RTC_SEC"

Tutorials

API reference

Contributing

$ git clone git://github.com/node-opcua/node-opcua.git
$ cd node-opcua
$ npm install -g pnpm 
$ pnpm install
$ pnpm recursive install
$ pnpm build

NPM

Project Stats

Supported Features

Service
Discovery Service Set
FindServers() βœ…
GetEndpoints() βœ…
RegisterServer() βœ…
RegisterServer2() βœ…
FindServersOnNetwork() βœ…
Secure Channel Service Set
OpenSecureChannel() βœ…
CloseSecureChannel() βœ…
Session Service Set
CreateSession() βœ…
CloseSession() βœ…
ActivateSession() βœ…
Cancel()
View Service Set
Browse() βœ…
BrowseNext() βœ…
TranslateBrowsePathsToNodeIds() βœ…
RegisterNodes() βœ…
UnregisterNodes() βœ…
Attribute Service Set
Read() βœ…
Write() βœ…
HistoryRead() πŸŒ’
HistoryUpdate() πŸŒ’
MonitoredItems Service Set
CreateMonitoredItems() βœ…
ModifyMonitoredItems() βœ…
SetMonitoringMode() βœ…
SetTriggering() πŸŒ‘
DeleteMonitoredItems() βœ…
Subscription Service Set
CreateSubscription() βœ…
ModifySubscription() βœ…
DeleteSubscriptions() βœ…
Publish() βœ…
Republish() βœ…
TransferSubscriptions() βœ…
Node Management Service Set
AddNodes() πŸŒ‘
AddReferences() πŸŒ‘
DeleteNodes() πŸŒ‘
DeleteReferences() πŸŒ‘
Query Service Set
QueryFirst() πŸŒ‘
QueryNext() πŸŒ‘
PubSUB as a commercial module βœ…
GDS as a commercial module βœ…
Transport Protocol
Transport Status Comment
UA-TCP UA-SC UA Binary βœ… OPC.TCP - Binary
SOAP-HTTP WS-SC UA Binary πŸŒ‘ HTTP/HTTPS - Binary
SOAP-HTTP WS-SC UA XML πŸŒ‘
SOAP-HTTP WS-SC UA XML-UA Binary πŸŒ‘
Security Policies
Policy Status Comment
None βœ…
Basic128Rsa15 βœ… deprecated in 1.04
Basic256 βœ… deprecated in 1.04
Basic256Sha256 βœ…
Authentication Status Comment
Anonymous βœ…
User Name Password βœ…
X509 Certificate βœ…
client facets
Base Client Behaviour βœ…
AddressSpace Lookup βœ…
Attribute Read βœ…
DataChange Subscription βœ…
DataAccess βœ…
Discovery βœ…
Event Subscription βœ…
Method call βœ…
Historical Access πŸŒ“
Advanced Type βœ…
Programming πŸŒ‘
Auditing πŸŒ“
Redundancy πŸŒ‘ Sponsors wanted
server profiles
Core Server βœ…
Data Access Server βœ…
Embedded Server βœ…
Nano Embedded Device Server βœ…
Micro Embedded Device Server βœ…
Standard DataChange Subscription Server βœ…
Standard Event Subscription Server βœ…
Standard UA Server βœ…
Redundancy Transparent Server πŸŒ‘ Sponsors wanted
Redundancy Visible Server πŸŒ‘ Sponsors wanted
Node Management Server πŸŒ‘ Sponsors wanted
Auditing Server πŸŒ“
Complex Type Server βœ… (sponsored)
Session Diagnostics βœ… (sponsored)
Subscription Diagnostics βœ… (sponsored)
Alarms & Conditions βœ… (sponsored)
Pub & Sub πŸŒ‘ Sponsors wanted

Feedback

  • if you're using node-opcua in one of your project, please feel free to leave a comment and a quick description in the wiki

  • if you have a particular wish or found a issue, let us known and create an issue

About licensing

The node-opcua core module is copyrighted and licencsd under the term of the "The MIT License".

This means that :

  • node-opcua comes without any warranty of any kind.
  • you can freely re-use in an open-source application or a commercial application
  • you have to include the software copyright notice in all copies or substantial portions of the software.

You are strongly encouraged to apply to our NodeOPCUA Membership to get additional benefits and support.

Copyright

Copyright (c) 2022-2024 Sterfive SAS - 833264583 RCS ORLEANS - France (https://www.sterfive.com) Copyright (c) 2014-2022 Etienne Rossignon

node-opcua's People

Contributors

andreasheine avatar enobufs avatar erossignon avatar everhardt avatar gilesbradshaw avatar hanskhe avatar hoancea avatar huazh avatar iliareshetov avatar jacobq avatar janschatz avatar jugglingcats avatar kubat avatar marcelwinh avatar marcoseb avatar martinc-mcn avatar mathias-luedtke avatar mdameda avatar narttmk avatar padraic-padraic avatar patricia-dm avatar perok avatar rashandan avatar shreeramk avatar snyk-bot avatar sphire avatar tetanw avatar tomsoftware avatar treestructure avatar zombinary 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

node-opcua's Issues

connection issue with Prosys OPC UA client

Hello i am using Prosys OPC UA client to test the sample server. However it give us the errors:

"""
buffer.js:582
throw new RangeError('Trying to access beyond buffer length');
^
RangeError: Trying to access beyond buffer length
at checkOffset (buffer.js:582:11)
at Buffer.readUInt32LE (buffer.js:609:5)
"""
Can u give me some advice?
Thank you
Best regard,
Long Tran

function constructBrowsePath(startingNode ,path) ??error

function constructBrowsePath(startingNode ,path)
exports.constructBrowsePath = constructBrowsePath;

can not use require('node-opcua').AddressSpace constructBrowsePath.

please add:
AddressSpace.prototype.constructBrowsePath = constructBrowsePath;

Siemens Simatic NET

node simple_client.js
connected !
{ namespaceIndex: 0, name: 'FolderType' }
{ namespaceIndex: 0, name: 'Views' }
{ namespaceIndex: 0, name: 'Objects' }
{ namespaceIndex: 0, name: 'Types' }
MessageBuilder : ERROR DETECTED IN event handler
[Error: String cannot be coerced to a nodeId : S7:S7_Connection_1.db1.0,x0]
Error: String cannot be coerced to a nodeId : S7:S7_Connection_1.db1.0,x0

response.results[0] not checked for

When CreateMonitoredItemResponse comes with ServiceResult = 0x802b0000, response.results is empty array, and in client_subscription.js at line 229 module checks result[0].StatusCode. Node throw exception:

TypeError: Cannot read property 'statusCode' of undefined  
    at ClientMonitoredItem._monitor (project\node_modules\node-opcua\lib\client\client_subscription.js:229:32)
    at OPCUASession._defaultRequest (project\node_modules\node-opcua\lib\client\opcua_client.js:366:13)
    at Object.OPCUASession.performMessageTransaction (project\node_modules\node-opcua\lib\client\opcua_client.js:552:9)
   ...

at this point err is β€Œβ€ŒError: ServiceResult is BadTimestampsToReturnInvalid (0x802b0000)

capture: https://drive.google.com/file/d/0B98-p8X89-Btakt6Z3JxZUZGVjg/edit?usp=sharing

Error disapear when i added
timestampsToReturn: 2,
on line 216 in client_subscription.js

Source time stamp

There does not seem to be a way to provide the source time stamp for a variable. How would you prefer to do this API wise if I can help?

error when "use strict"

'node --use_strict "sample_client.js"' throw error but 'node "sample_client.js"' is OK:

e:\nodejs\global\node_modules\node-opcua\lib\misc\encode_decode.js:119
isValidBoolean = exports.isValidBoolean = function(value) {
^
ReferenceError: isValidBoolean is not defined
at Object. (e:\nodejs\global\node_modules\node-opcua\lib\misc\encode_decode.js:119:16)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)
at Module.load (module.js:349:32)
at Function.Module._load (module.js:305:12)
at Module.require (module.js:357:17)
at require (module.js:373:17)
at Object. (e:\nodejs\global\node_modules\node-opcua\lib\misc\factories.js:8:10)
at Module._compile (module.js:449:26)
at Object.Module._extensions..js (module.js:467:10)

Null Pointer Exception in CreateSession() - server not defined

Hi, I tried to create a simple client. So I started to write some kind of main-Method. After I did the connect, I want to create a session. Unfortunately I got an error:
... \node-opcua\lib\client\opcua_client.js:638
this.serverUri = endpoint.server.applicationUri;
TypeError: Cannot read property 'server' of undefined at OPCUAClient._createSession (... \node_modules\node-opcua\lib\client\opcua_client.js:639:30)
at OPCUAClient.createSession

Here is the corresponding code snippet:

console.log("BP0");
var client      = new opcua.OPCUAClient();
var endpointUrl = "opc.tcp://" + require("os").hostname() + ":48010";
client.connect(endpointUrl, function(err){
    if (err) {
        console.log(" failure ",err);
    } else {
        console.log("done!")
    }
});
console.log("Connected!");
var userIdentityToken = new s.AnonymousIdentityToken({policyId: "0"});
client.createSession(userIdentityToken, function(err, ses){
    if(!err){
        session = ses;
    } else {
        console.log("ERROR 100");
    }
});
console.log("Session created!");
client.disconnect(function(err){
    if (!err){
        console.log("Disconnected!")
    } else {
        console.log("ERROR 101");
    }
});
console.log("Disconnected!");
console.log("BP1");

Asynchronous value returns on server side

Your code looks great... thanks for all your hard work in developing this module.
We're looking to potentially use it in an upcoming project of ours, however I have a question/request. From your example documentation, it looks like the only way to return a requested value on the server side is through a synchronous getter such as:

server.nodeVariable1 = server.engine.addVariableInFolder("MyDevice",{
browseName: "MyVariable1",
dataType: "Double",
value: {
get: function () {
return new opcua.Variant({dataType: opcua.DataType.Double, value: variable1 });
}
}
});

However, for our needs (due to wireless latencies and other issues), we will need to asynchronously read this value on the server, and return it via a callback of some sort. Is this functionality planned in the near future, or could you give me some guidance on where to look if you would like us to potentially modify and send a pull request?

Cheers--

cannot connect to endpoint?

server:
[root@py myserver]# node sample_server.js
using URSA
FAST: using node-expat
initialized
LISTENING TO PORT 4334
Server is now listening ... ( press CTRL+C to stop)
port 4334
the primary server endpoint url is opc.tcp://py:4334/UA/SampleServer

client:
[root@py sample_client]# node sample_client.js
using URSA
FAST: using node-expat
cannot connect to endpoint : opc.tcp://py:4334/UA/SampleServer
failure { [Error: getaddrinfo EIO] code: 'EIO', errno: 'EIO', syscall: 'getaddrinfo' }

AssertionError: offset === 11644473600000

Great work.

Running simple test:

var http = require('http');
var opcua = require('node-opcua');

http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end('Hello World\n');
}).listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');

I get out:

../testOPCuaSDK/node-opcua-sample/node_modules/node-opcua/node_modules/better-assert/index.js:37
throw err;
^
AssertionError: offset === 11644473600000
at /home/prjsprod/prjdpsystem/testOPCuaSDK/node-opcua-sample/node_modules/node-opcua/lib/misc/encode_decode.js:231:9
at exports.isValidDateTime (/home/prjsprod/prjdpsystem/testOPCuaSDK/node-opcua-sample/node_modules/node-opcua/lib/misc/encode_decode.js:235:7)
at Object. (/home/prjsprod/prjdpsystem/testOPCuaSDK/node-opcua-sample/node_modules/node-opcua/lib/misc/encode_decode.js:277:2)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object. (/home/prjsprod/prjdpsystem/testOPCuaSDK/node-opcua-sample/node_modules/node-opcua/lib/misc/factories.js:8:10)

If commet line 231 in file 'encode_decode.js'
//assert(offset === 11644473600000);

Out is:
../testOPCuaSDK/node-opcua-sample$ node simple_client.js
FAST: using node-expat
Server running at http://127.0.0.1:3000/

PS: I like help with this project.

Best regards,
AurΓ©lio.

public key generation on windows

I'm having problems generating a public key on windows.

I do ..

openssl req -x509 -days 365 -nodes -newkey rsa:1024 -keyout key.pem -out cert.pem

then ...

openssl rsa -in cert.pem -pubout > public_key.pub

but it gives me..

unable to load Private Key
7876:error:0906D06C:PEM routines:PEM_read_bio:no start line:.\crypto\pem\pem_lib.c:703:Expecting: ANY PRIVATE KEY

any advice/help would be massively appreciated

MonitoredItem on changed not fired

In UAExpert i see the attributes are changed realtime. But using this module the on changed event is not fired. Also console.log("keepalive"); is not printed. Somebody have any suggestions? Thank you in advance...

Code that works (getting variable value 1 time):

    function(callback) {
       the_session.readVariableValue("ns=2;s=WINDSAMP/Variables/fWindspeed1_1s_var", function(err,dataValues) {
           if (!err) {
               console.log(" Winddirection 1 = " , dataValues);
           }
           callback(err);
       });
    }

Code that does not work:

    function(callback) {
       the_subscription=new opcua.ClientSubscription(the_session,{
           requestedPublishingInterval: 500,
           requestedLifetimeCount: 1000,
           requestedMaxKeepAliveCount: 10,
           maxNotificationsPerPublish: 10,
           publishingEnabled: true,
           priority: 0
       });

       the_subscription.on("started",function(){
           console.log("subscription started for 2 seconds - subscriptionId=",the_subscription.subscriptionId);
       }).on("keepalive",function(){
           console.log("keepalive");
       }).on("terminated",function(){
           callback();
       });

       setTimeout(function(){
           the_subscription.terminate();
       },10000);

        var monitoredItem  = the_subscription.monitor({
              nodeId: opcua.resolveNodeId("ns=2;s=WINDSAMP/Variables/fWindspeed1_1s_var"),
              attributeId: 13
          },
          {
              samplingInterval: 100,
              discardOldest: true,
              queueSize: 10
          },
          opcua.read_service.TimestampsToReturn.Both
        );   

        console.log("-------------------------------------");

       monitoredItem.on("changed",function(dataValue){
          console.log(" Windspeed = ",dataValue.value.value);
       });

    },

How to browse nodeId and attributeID for the sample client

Hello. I am new to the opcUA.
I am doing a small change in the sample client which just try to read the "MyVariable1" from the sample server.
I changed "ns=4,s="free_mem" to "ns=1,s="1001".
The change come from reading data from UAExpert application. I guessed that i should change this.

The result is just "keep alive" or there is no variable found.

Could you please tell me how can i read the NodeID and Attribute ?.
Thank you very much for considering my problem.

monitorItem fails from an node-opcua client with the OPC-F standard server

Hi Etienne,
The following code fails with the OPC-F standard server

   var monitoredItem = subscription.monitor(
    {
        nodeId: resolveNodeId(startnode),
        attributeId: 13
    },
    {
        samplingInterval: 1000,
        discardOldest: true,
        queueSize: 100
    });

The servers fails with a BadTimestampsToReturn. Looks like the timestampToReturn field is not initialized in the monitor request (subscription_client.js) that's why the server rejects the monitor request.

Browse Server

    var browseDescription = {
        nodeId: "RootFolder",
      //  referenceTypeId: "Organizes",
        browseDirection: BrowseDirection.Inverse
    }
   the_session.browse(browseDescription, function (err, results, diagnostics) {
   results[0].references.forEach(ref => { console.log(ref); });
   callback(err);
    });

says ReferenceError: BrowseDirection is not defined.

Browserify node-opcua

Hello,

I am trying to browserify the node-opcua module withouth success. Is it possible in the current stage of developement? I have tried setting transform option with requirish module but still it can't resolve the modules. File sample_client.js contains one line wich basically just requires the node-opcua module.

It works if I run it as 'node sample_client.js'. Browserify command works with other modules (like async). The error I am receiving:

$ browserify -t requirish ./opcua/sample_client.js > bundle.js 
Error: Cannot find module 'lib/datamodel/structures' from '/home/jkochman/Work/MTViewCenter2/node_modules/node-opcua'
    at /usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:51:17
    at process (/usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:159:43)
    at /usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:168:21
    at load (/usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:99:43)
    at /usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:105:22
    at /usr/local/lib/node_modules/browserify/node_modules/browser-resolve/node_modules/resolve/lib/async.js:22:47
    at Object.oncomplete (fs.js:107:15)

Kind regards,
Jakub

Test Client Example

Hi!

I' m testing your client example with Kepware product but i got error when i try to read a variable. my code is:
the_session.readVariableValue("ns=3;s=MOYNOSFNE12.SFNE12.pippo", function(err,dataValues,diagnostics) {

Where MOYNOSFNE12 is Channel and SFNE12 is device.... Have you tested with Kepware? Can you help me?

Creating methods in objects

generated files

Hi, in the released version, the add method to the objects is lacking. However, in the codes that are in development, I notice addMethod() function has been implemented in the server-engine. I tried implementing it but to no avail.

Currently, I have this error:
Cannot find module 'generated/_auto_generated_CallMethodRequest'

How do I generate this file and the others that are not included in the released version?

Open connection by using username ,password and encryption

How can i connect to an opc server by using an username, password and encryption? I'm not able to write any value. I just got error messages. Using a testing tool i have to type a username and password to connect and it works fine. Is there anything i have to take care by writing values an setting up the connection?

How to get timestamp when call readVariableValue

readVariableValue doesn't return serverTimestamp & sourceTimestamp.

OPCUASession.prototype.readVariableValue = function (nodes, callback) {
...

var request = new read_service.ReadRequest({
    nodesToRead: nodesToRead,
    timestampsToReturn: read_service.TimestampsToReturn.Neither
});

Monitored Item do not have SourceTimestamp and ServerTimestamp

I used your simple_client (https://github.com/node-opcua/node-opcua/blob/master/documentation/creating_a_client.md with a minor modification: dataValue.value.value --> dataValue in line 92) to read items in a OPC Server. Then I got

% free mem = { value:
{ dataType: [Getter/Setter],
arrayType: [Getter/Setter],
value: 67 },
statusCode: undefined,
sourceTimestamp: null,
sourcePicoseconds: 0,
serverTimestamp: null,
serverPicoseconds: 0 }

Why it could not read SourceTimestamp and serverTimestamp? I tried it with other OPC UA client (e.g Kepware Quick Client) and their items have these properties.

Date decoding/encoding

Decoding dates seem to be offset incorrectly, possibly encoding too?

I had a look at test_date_to_64bits_conversion.js and the test "should decode 92c253d3 0cf7ce01 DateTime as Dec 12, 2013 08:36:09.747317000" lacks asserts. If I correct the assert it fails because the decoding doesn't match the expected output.

Bug v 0.0.36

Works:

"dependencies": {
    "async": "^0.9.0",
    "node-expat": "^2.3.3",
    "node-opcua": "0.0.35",
    "ursa": "^0.8.0"

doesnt:

"dependencies": {
    "async": "^0.9.0",
    "node-expat": "^2.3.3",
    "node-opcua": "0.0.36",
    "ursa": "^0.8.0"

stacktrace:

using URSA
FAST: using node-expat

buffer.js:582
    throw new RangeError('Trying to access beyond buffer length');
          ^
RangeError: Trying to access beyond buffer length
    at checkOffset (buffer.js:582:11)
    at Buffer.readUInt32LE (buffer.js:609:5)
    at BinaryStream.readUInt32 (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/misc/binaryStream.js:201:31)
    at exports.decodeUInt32 (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/misc/encode_decode.js:136:19)
    at SequenceHeader.decode (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/_generated_/_auto_generated_SequenceHeader.js:77:27)
    at MessageBuilder._read_headers (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/misc/message_builder.js:329:29)
    at MessageBuilderBase._append (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/misc/message_builder_base.js:107:15)
    at MessageBuilderBase._feed_messageChunk (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/misc/message_builder_base.js:167:14)
    at null.<anonymous> (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/misc/message_builder_base.js:44:14)
    at emit (events.js:95:17)
    at PacketAssembler.feed (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/transport/packet_assembler.js:73:14)
    at MessageBuilderBase.feed (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/misc/message_builder_base.js:147:30)
    at ClientSecureChannelLayer._on_receive_message_chunk (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/client/client_secure_channel_layer.js:505:25)
    at null.<anonymous> (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/client/client_secure_channel_layer.js:258:18)
    at emit (events.js:95:17)
    at null.<anonymous> (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/transport/tcp_transport.js:288:14)
    at emit (events.js:95:17)
    at PacketAssembler.feed (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/transport/packet_assembler.js:73:14)
    at on_data_received_for_packet_assembler [as _on_data_received] (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/transport/tcp_transport.js:294:30)
    at Socket.<anonymous> (/home/vincent/Documents/MesDashboard/Mes/test/node_modules/node-opcua/lib/transport/tcp_transport.js:163:18)
    at Socket.emit (events.js:95:17)
    at Socket.<anonymous> (_stream_readable.js:764:14)
    at Socket.emit (events.js:92:17)
    at emitReadable_ (_stream_readable.js:426:10)
    at emitReadable (_stream_readable.js:422:5)
    at readableAddChunk (_stream_readable.js:165:9)
    at Socket.Readable.push (_stream_readable.js:127:10)
    at TCP.onread (net.js:528:21)

The code:

var opcua = require("node-opcua");
var async = require("async");

var client = new opcua.OPCUAClient();
var endpointUrl = "opc.tcp://10.24.24.112:49321/"
var the_session, the_subscription;

var tags = [  "ns=2;s=Simulation Examples.Functions.Sine1", 
              'ns=2;s=Channel1.Device1.Tag1',
              "ns=2;s=Simulation Examples.Functions.Ramp1",
              "ns=2;s=Simulation Examples.Functions.Ramp2"];


async.series([
    // step 1 : connect to
    function(callback)  {
        client.connect(endpointUrl,function (err) {
            if(err) {
                console.log(" cannot connect to endpoint :" , endpointUrl );
            } else {
                console.log("connected !");
            }
            callback(err);
        });
    },
    // step 2 : createSession
    function(callback) {
        client.createSession( function(err,session) {
            if(!err) {
                the_session = session;
            }
            callback(err);
        });
    },

    // step 3 : browse
    function(callback) {
       the_session.browse("RootFolder", function(err,browse_result){
           if(!err) {
               browse_result[0].references.forEach(function(reference) {
                   console.log("browseName: ", reference.browseName);
               });
           }
           callback(err);
       });
    },

    // step 4' : read a variable with read
    function(callback) {
      tags.forEach(function(tag){
         var max_age = 0;
         var nodes_to_read = [
            { nodeId: tag, attributeId: 13} 
         ];
         the_session.read(nodes_to_read, max_age, function(err,nodes_to_read,dataValues) {
             if (!err) {
                 console.log("Tag: " + tag + " :" , dataValues[0]);
             }else
              callback(err);
         });
     });
      //no error has occurred
      callback(null);
    },

    // step 5: install a subscription and install a monitored item for 10 seconds
    function(callback) {
       the_subscription=new opcua.ClientSubscription(the_session,{
           requestedPublishingInterval: 1000,
           requestedLifetimeCount: 10,
           requestedMaxKeepAliveCount: 2,
           maxNotificationsPerPublish: 10,
           publishingEnabled: true,
           priority: 10
       });

       the_subscription.on("started",function(){
           console.log("subscription started for 2 seconds - subscriptionId=",the_subscription.subscriptionId);
       }).on("keepalive",function(){
           console.log("keepalive");
       }).on("terminated",function(){
           callback();
       });

       // install monitored item
       tags.forEach(function(tag){
        (function(subscriptor, tag){
        var monitoredItem  = subscriptor.monitor({
          nodeId: opcua.resolveNodeId(tag),attributeId: 13
          },
          {
            samplingInterval: 100,
            discardOldest: true,
            queueSize: 10
          },
            opcua.read_service.TimestampsToReturn.Both
          );
          console.log("-------------------------------------");

          monitoredItem.on("changed",function(dataValue){
          console.log("Tag: " + tag + ' :' ,dataValue.value.value);
          });

       })(the_subscription, tag);
      });

    },

    // close session
    function(callback) {
        the_session.close(function(err){
            if(err) {
                console.log("session closed failed ?");
            }
            callback();
        });
    }

],
function(err) {
    if (err) {
        console.log(" failure ",err);
    } else {
        console.log("done!");
    }
    client.disconnect(function(){});
}) ;


I connecting with a kepserver 5.15

Enable browsing with upper and lower case nodeIds

In UA-Expert, GUID identiers are shown in lower case. node-opcua-client is accepting only uppercase browse strings. See my code example below.

var browseDescription = { // TODO use uppercase-function
nodeId : new opcua.NodeId(datamodelNodeId.NodeIdType.GUID,"360273AA-F2B9-4A7F-A5E3-37B7074E2529",3)
}
the_session.browse(browseDescription, function(err, browse_result, diagnostics){

Recursive browse all server items

Hi erossignon,

How could I recursive browse all items of a OPC UA server?

I tried browse function with many type of browseDescription. However, it returns only one level up/down from the browsed node.

I also try crawler (as you used in /bin/simple_client.js) but I got following error message with KepWareEX Server or your sample server (https://github.com/node-opcua/node-opcua/blob/master/documentation/sample_server.js). It is ok with your server in /bin/simple_server.js!

Error message:
`[31mMessageBuilder : ERROR DETECTED IN event handler
[TypeError: Cannot call method 'substring' of undefined]
TypeError: Cannot call method 'substring' of undefined
at lowerize (D:\WorkSpace\Node.js\testopcua\node_modules\node-opcua\lib\client\node_crawler.js:351:20)
at D:\WorkSpace\Node.js\testopcua\node_modules\node-opcua\lib\client\node_crawler.js:393:27
at Array.map (native)
at _reconstruct_manageable_object (D:\WorkSpace\Node.js\testopcua\node_modules\node-opcua\lib\client\node_crawler.js:387:27)
at done (D:\WorkSpace\Node.js\testopcua\node_modules\node-opcua\lib\client\node_crawler.js:423:17)
at Object.self.q.drain (D:\WorkSpace\Node.js\testopcua\node_modules\node-opcua\lib\client\node_crawler.js:296:13)
at next (D:\WorkSpace\Node.js\testopcua\node_modules\node-opcua\node_modules\async\lib\async.js:804:31)
[...]

Returning bad quality from sample server

Hi,

I tried modifying the sample server to talk to a real PLC as a test. It worked well, but I wasn't sure how to return a bad status code to the client. Possibly:

return new opcua.Variant({dataType: opcua.DataType.Double, value: pump_speed, statusCode: opcua.StatusCodes.BadCommunicationError });

But that obviously isn't the right way. What is the best way to do this? Or will the status code always be "Good"?

Thanks...
Dana

monitored item samplingInterval shall be clamped

The monitored item samplingInterval may be set to 0 by a client.
(for instance UaExpert may specify a value of 0 for a publish interval)
In this case the server will emit a timer with a 0ms interval causing high CPU demand.
The samplingInterval interval shall be clamped to prevent server to be overwhelmed.

Performance on AM3358 / BBB / Raspberry Pi

I'm running a simple OPC UA server on my BeagleBoneBlack and get the data via a OPC UA client (on another computer) from the server. Both, client und server are written with the node-opcua tool. I read every second some variables with the client and the CPU load of the BBB (the server) is about 100%!
Obviously needs the software much more hardware performance to run the node-opcua module on a Raspberry Pi or BBB.
Any experience with BBB and this module or any idea to reduce the cpu load?

Examples

Hey, just stumpled on your repo and I'm really interested in it, I've been working with OPC in languages like C# and Java and it also occured to me that Node.js would be perfect for handling asynchronous OPC polling.

I tried getting started with your code, but was unsure how to get started. Any chance you could make an example where it discovers OPC applications installed on the machine and allows connecting to them?

And is there a way I can help out with anything? :)

Bug for VariantArrayType in index.js?

Hi,
The path in index.js file for VariantArrayType shows:
module.exports.VariantArrayType = require("lib/datamodel/datavalue").VariantArrayType;

But, I could not find any VariantArrayType declaration in datavalue.

Should it be lib/datamodel/variant instead?

Failed to renew security token

I tried testing the nodejs server using Prosys java sdk 2.0.2 evaluation version. I used the SampleConsoleClient to connect to the server. After awhile, I received a recurring error on the client:

Client console output:
02/05/2015 15:15:01.560 ERROR 66 Failed to renew security token.
org.opcfoundation.ua.common.ServiceResultException: Bad_UnexpectedError (code=0x80010000, description="Sequence number mismatch")
at org.opcfoundation.ua.transport.tcp.io.TcpConnection$ReadThread.run(Unknown Source)
ServerState changed from Running to CommunicationFault

Test server console output:
test server console output

Which side would be causing the problem?

got error when run sample_client.js on version "0.0.29"

with node flag --use_strict

subscription started for 2 seconds - subscriptionId= 17
οΏ½[31mMessageBuilder : ERROR DETECTED IN event handlerοΏ½[39m
[TypeError: 'caller', 'callee', and 'arguments' properties may not be accessed on strict mode functions or the arguments objects for calls to them]
[ {},
{},
...

without --use_strict

subscription started for 2 seconds - subscriptionId= 18
οΏ½[31mMessageBuilder : ERROR DETECTED IN event handlerοΏ½[39m
{ [AssertionError: response instanceof subscription_service.CreateMonitoredItemsResponse]
name: 'AssertionError',
actual: undefined,
expected: undefined,
operator: undefined,
message: 'response instanceof subscription_service.CreateMonitoredItemsResponse',
generatedMessage: false }
AssertionError: response instanceof subscription_service.CreateMonitoredItemsResponse

Node OPC Client constructor not found for expandedId ( StatusChangeNotification)

While running the subscription, it sometimes throw out the following error, and it will cause the subscription suspended, would you please suggest what happend ?
I'm using the opc foundation's Com Opc Server Wrapper with Kepeware 4 to monitor a simulator tag configured in kepware 4. If I tried to reboot the nodejs process for several times, then the error will disappear, but I don't know how to make it more stable.
Thanks a lot !

cannot find constructor for expandedId
{ identifierType: { key: 'NUMERIC', value: 1 },
  value: 820,
  namespace: 0 }

browseRequest fails on .NET server

looks like the browseRequest always fails from the interactive_client..

b ObjectsFolder
StatusCode = Bad_NodeNotInView

the reason is that there is a piece of code in the C# which enforces to be sure we are in the default view.

if (NodeId.IsNull(view.m_viewId) && view.m_viewVersion == 0 && view.m_timestamp == DateTime.MinValue)
{
return true;
}

so you must not fill the m_timestamp attribute of the view parameter with the current date if you want a successful browse request

Writing data with node-opcua

Hi,
I didn't found any example somewhere on how to use node-opcua to write data to an opc server.
I tried to use both writeSingleNode and write.
I did somethin like:

  function(callback) {
         var nodesToWrite = [
             { nodeId: "ns=4;s=S7-1500 station_1.PLC System.CAN_message_DB.CAN_CMD",
               attributeId: 1,
               indexRange: 0,
               value: 0
               }
         ];
       var value = 0;
       the_session.write(nodesToWrite, function(err,statusCode,diagnosticInfo) {
           if (!err) {
               console.log(" write ok" );
               console.log(diagnosticInfo);
               console.log(statusCode);
           }
           callback(err);
       });
    },

But I always get BadNotWritable or BadTypeMismatch, while trying different options.
There is a very useful sample code for reading data, is there something similar for writing data around there?
Thanks in advance for your help

Running test cases

Hi, I am trying to run some existing tests. How do I get this done?
I forked this project, imported it to Eclipse Enide and started Windows Power Shell, cd to node-opcua folder and ran 'nodeunit ./test/test_nodeopcua.js'.

I got this error message:

Cannot find module '_generated_/_auto_generated_DiagnosticInfo'

In fact my auto_generated folder of my project is empty.

UPDATE: ok the first step is to identify the correct testing framework. I found out that you are able to run all tests by calling 'npm test' after running 'npm install' - people on stackoverflow told me that probably 'mocha' is the name of the testing framework.

OPC DA

Hi Etienne,

Not sure where to ask this but, I'm just wondering if node-opcua supports reading/writing values from/to OPC DA Servers?

Thank you.

passing a String NodeId on the command line

Hi Etienne,

I wanted to test your command line interface mentioned in line 10 of simple_client.js. I was not able to set an accepted NodeId name, i.e. if I call

    node bin/simple_client.js --endpoint opc.tcp://ehome09:48010 --node "ns=3,s={360273AA-F2B9-4A7F-A5E3-37B7074E2529}.MechanicalDomain"

I will get an error:

throw new Error("String cannot be coerced to a nodeId : " + value)
                  ^
Error: String cannot be coerced to a nodeId : ns=3,s={360273AA-F2B9-4A7F-A5E3-37B7074E2529}.MechanicalDomain
    at TypeSchema.coerceNodeId ...

Can you verify that your example in your code is still working or are you able to add one more example call?

This is the corresponding file in node-opcua-project:
https://github.com/node-opcua/node-opcua/blob/master/bin/simple_client.js

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.