TypeScript / JavaScript OPC UA client for the browser.
... work in progress ...
- OPC UA binary data encoding (Part 6: Mappings - 5.2.1)
- WebSockets transport protocol (Part 6: Mappings - 7.5.1)
npm i opcua
import Client from 'opcua'
const client = new Client('ws://localhost:1234')
// open socket connection
await client.open()
// send hello and wait for acknowledge
const ack = await client.hello()
// open secure channel
const openSecureChannelResponse = await client.openSecureChannel()
// create session
const createSessionResponse = await client.createSession()
// activate session
const activateSessionResponse = await client.activateSession()
// browse root folder
const req = new BrowseRequest({
NodesToBrowse: [
new BrowseDescription({
NodeId: NewTwoByteNodeId(IdRootFolder),
BrowseDirection: BrowseDirectionBoth,
IncludeSubtypes: true,
ResultMask: BrowseResultMaskAll
})
]
})
const res = await client.browse(req)
for (const result of res.Results as BrowseResult[]) {
for (const ref of result.References as ReferenceDescription[]) {
console.log(ref.DisplayName.Text)
}
}
... work in progress ... it's pretty complex so we need some diagrams
https://reference.opcfoundation.org/v104/Core/docs/Part4/5.12.1/#5.12.1.5
The source code is written in TypeScript. We use the TypeScript compiler to create the JavaScript files for the browser.
Some source code files are autogenerated.
src/ua/generated.ts
bycmd/service/main.go
src/id/id.ts
bycmd/id/main.go
src/ua/StatusCode.ts
bycmd/status/main.go
Do not edit them by hand. You need Go on your machine to execute those generators. The schema definition files are located at ./schema
.
We rely on reflection and decorators to get types (e.g. uint32
, CreateSessionRequest
or arrays of certain types string[]
) during runtime. In JavaScript a number is always double-precision 64-bit. OPC UA has much more number types like int8
, uint8
, int16
, uint16
and so on. In order to get the binary encoding / decoding right we must know exactly how many bits represent a number.
The client architecture consists of multiple layers. They closely follow the official OPC UA specification. Read the following diagram from bottom to top. On the right side you find the responsibilities for each layer.
The OPC UA handshake is quite complex and several steps are necessary to get an active session. Those steps are
- Hello / Acknowledge
- Open Secure Channel
- Create Session
- Activate Session
The following diagram shows this sequence and highlights response parameters that the client has to store internally (e.g. channel id, token id, authentication token, sequence number, request id).
You need an OPC UA server implementation that supports WebSockets to test the client. Two options exist:
- Use open62541 with WebSockets enabled
- Use websockify for servers that do not support WebSockets (that only support TCP connections)