ads-client 2.0.0-beta.4 → 2.0.0-beta.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -4,30 +4,117 @@
4
4
  [![npm version](https://img.shields.io/npm/v/ads-client)](https://www.npmjs.org/package/ads-client)
5
5
  [![GitHub](https://img.shields.io/badge/View%20on-GitHub-brightgreen)](https://github.com/jisotalo/ads-client)
6
6
  [![License](https://img.shields.io/github/license/jisotalo/ads-client)](https://choosealicense.com/licenses/mit/)
7
- [![Support](https://img.shields.io/badge/Donate-PayPal-yellow)](https://www.paypal.com/donate/?business=KUWBXXCVGZZME&no_recurring=0&currency_code=EUR)
7
+
8
8
 
9
9
  Beckhoff TwinCAT ADS client library for Node.js (unofficial).
10
10
 
11
11
  Connect to a Beckhoff TwinCAT automation system using the ADS protocol from a Node.js app.
12
12
 
13
- ## v2 project status
13
+ If you are using Node-RED, check out the [node-red-contrib-ads-client](https://www.npmjs.com/package/node-red-contrib-ads-client).
14
+
15
+ # Project status
16
+
17
+ <u><b>NOTE: DOCUMENTATION LINKS ARE NOT WORKING UNTIL RELEASED - CLONE REPOSITORY FOR DOCS</b></u>
18
+
19
+ Version 2 is almost ready!
20
+
21
+ - Rewritten in Typescript
22
+ - See [CHANGELOG.md](https://github.com/jisotalo/ads-client/blob/v2-dev/CHANGELOG.md) for details.
23
+ - See [MIGRATION.md](https://github.com/jisotalo/ads-client/blob/v2-dev/MIGRATION.md) for guide of migrating v1 -> v2 (breaking changes!)
24
+ - See the new [documentation](TODO-DOC-URL-HERE/classes/Client.html)
25
+
26
+ # Features
27
+ - Supports TwinCAT 2 and 3
28
+ - Supports any kind of target systems with ADS protocol (local runtime, PLC, EtherCAT I/O...)
29
+ - Supports multiple connections from the same host
30
+ - Reading and writing any kind of variables
31
+ - Subscribing to variable value changes (ADS notifications)
32
+ - Automatic conversion between PLC and Javascript objects
33
+ - Calling function block methods (RPC)
34
+ - Automatic 32/64 bit variable support (PVOID, XINT, etc.)
35
+ - Automatic byte alignment support (all pack-modes automatically supported)
36
+
37
+ # Table of contents
38
+ - [Support](#support)
39
+ - [Installing](#installing)
40
+ - [Connection setup](#connection-setup)
41
+ - [Setup 1 - Connect from Windows](#setup-1---connect-from-windows)
42
+ - [Setup 2 - Connect from Linux/Windows](#setup-2---connect-from-linuxwindows)
43
+ - [Setup 3 - Connect from any Node.js system](#setup-3---connect-from-any-nodejs-system)
44
+ - [Setup 4 - Connect from local system](#setup-4---connect-from-local-system)
45
+ - [Setup 5 - Docker container](#setup-5---docker-container)
46
+ - [Important](#important)
47
+ - [Enabling localhost support on TwinCAT 3](#enabling-localhost-support-on-twincat-3)
48
+ - [Structured variables](#structured-variables)
49
+ - [Connecting to targets without a PLC runtime](#connecting-to-targets-without-a-plc-runtime)
50
+ - [Differences when using with TwinCAT 2](#differences-when-using-with-twincat-2)
51
+ - [Getting started](#getting-started)
52
+ - [Documentation](#documentation)
53
+ - [Available methods](#available-methods)
54
+ - [Creating a client](#creating-a-client)
55
+ - [Connecting](#connecting)
56
+ - [Reading values](#reading-values)
57
+ - [Reading any value](#reading-any-value)
58
+ - [Reading raw data](#reading-raw-data)
59
+ - [Reading reference/pointer](#reading-referencepointer)
60
+ - [Writing values](#writing-values)
61
+ - [Writing any value](#writing-any-value)
62
+ - [Writing raw data](#writing-raw-data)
63
+ - [Writing reference/pointer](#writing-referencepointer)
64
+ - [Subscribing to value changes](#subscribing-to-value-changes)
65
+ - [Any value](#any-value)
66
+ - [Raw data](#raw-data)
67
+ - [Unsubscribing](#unsubscribing)
68
+ - [Using variable handles](#using-variable-handles)
69
+ - [Calling function block RPC methods](#calling-function-block-rpc-methods)
70
+ - [Converting from/to raw data](#converting-fromto-raw-data)
71
+ - [Other features](#other-features)
72
+ - [Disconnecting](#disconnecting)
73
+ - [FAQ](#faq)
74
+ - [Lot's of connection issues and timeouts](#lots-of-connection-issues-and-timeouts)
75
+ - [Getting `TypeError: Do not know how to serialize a BigInt`](#getting-typeerror-do-not-know-how-to-serialize-a-bigint)
76
+ - [Can I connect from Raspberry Pi to TwinCAT?](#can-i-connect-from-raspberry-pi-to-twincat)
77
+ - [Receiving ADS error 1808 `Symbol not found` even when it should be found](#receiving-ads-error-1808-symbol-not-found-even-when-it-should-be-found)
78
+ - [Having timeouts or 'mailbox is full' errors](#having-timeouts-or-mailbox-is-full-errors)
79
+ - [Having problems to connect from OSX or Raspberry Pi to target PLC](#having-problems-to-connect-from-osx-or-raspberry-pi-to-target-plc)
80
+ - [A data type is not found even when it should be](#a-data-type-is-not-found-even-when-it-should-be)
81
+ - [ClientException: Connection failed: Device system manager state read failed](#clientexception-connection-failed-device-system-manager-state-read-failed)
82
+ - [Connection failed (error EADDRNOTAVAIL)](#connection-failed-error-eaddrnotavail)
83
+ - [Problems running ads-client with docker](#problems-running-ads-client-with-docker)
84
+ - [How to connect to PLC that is in CONFIG mode?](#how-to-connect-to-plc-that-is-in-config-mode)
85
+ - [Issues with TwinCAT 2 low-end devices (BK9050, BC9050 etc.)](#issues-with-twincat-2-low-end-devices-bk9050-bc9050-etc)
86
+ - [External links](#external-links)
87
+ - [Library testing](#library-testing)
88
+ - [TwinCAT 3 tests](#twincat-3-tests)
89
+ - [TwinCAT 2 tests](#twincat-2-tests)
90
+ - [License](#license)
91
+
92
+
93
+ # Support
94
+
95
+ * Bugs and feature requests:
96
+ * [Github Issues](https://github.com/jisotalo/ads-client/issues)
97
+ * Help, support and discussion:
98
+ * [Github Discussions](https://github.com/jisotalo/ads-client/discussions)
99
+
100
+ If you want to support my work, you can buy me a coffee! Contact for more options.
14
101
 
15
- **02.10.2024:** Beta 4 released! See [CHANGELOG.md](https://github.com/jisotalo/ads-client/blob/v2-dev/CHANGELOG.md) for details.
102
+ <a href="https://www.buymeacoffee.com/jisotalo" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/v2/default-blue.png" alt="Buy Me A Coffee" style="height: 60px !important;width: 217px !important;" ></a>
16
103
 
17
- All breaking changes are (hopefully) done.
104
+ [![Donate](https://img.shields.io/badge/Donate-PayPal-yellow)](https://www.paypal.com/donate/?business=KUWBXXCVGZZME&no_recurring=0&currency_code=EUR)
18
105
 
19
- * See [milestone #2](https://github.com/jisotalo/ads-client/milestone/2) for tasks to be done.
20
- * See [MIGRATION.md](https://github.com/jisotalo/ads-client/blob/v2-dev/MIGRATION.md) for guide of migrating v1->v2
21
- * Clone repository and open `docs/index.html` in browser for documentation
106
+ If you need help with integrating the ads-client, I'm available for coding work with invoicing. Contact for further details.
22
107
 
23
- ## Getting started
108
+ # Installing
24
109
 
25
- README is under construction.
110
+ Install the [npm package](https://www.npmjs.com/package/ads-client):
26
111
 
27
- ### Install
28
- `npm install ads-client@beta`
112
+ ```
113
+ npm install ads-client@beta
114
+ ```
115
+
116
+ Include the module in your code:
29
117
 
30
- ### Import the client
31
118
  ```js
32
119
  //Javascript:
33
120
  const { Client } = require('ads-client');
@@ -36,87 +123,986 @@ const { Client } = require('ads-client');
36
123
  import { Client } from 'ads-client';
37
124
  ```
38
125
 
39
- ### Create a client and connect
126
+ You can also clone the repository and run `npm run build`. After that, the library is available at `./dist/`
127
+
128
+ # Connection setup
129
+
130
+ The ads-client can be used with multiple system configurations.
131
+
132
+ [![ads-client-setups](https://user-images.githubusercontent.com/13457157/82724547-8dde0800-9cdf-11ea-8dd1-0a1f06f8559f.PNG)](https://user-images.githubusercontent.com/13457157/82724547-8dde0800-9cdf-11ea-8dd1-0a1f06f8559f.PNG)
133
+
134
+
135
+ ## Setup 1 - Connect from Windows
136
+
137
+ This is the most common scenario. The client is running on a Windows PC that has TwinCAT Router installed (such as development laptop, Beckhoff IPC/PC, Beckhoff PLC).
138
+
139
+ **Requirements:**
140
+ - Client has one of the following installed
141
+ - TwinCAT XAE (dev. environment)
142
+ - TwinCAT XAR (runtime)
143
+ - [TwinCAT ADS](https://www.beckhoff.com/en-en/products/automation/twincat/tc1xxx-twincat-3-base/tc1000.html)
144
+ - An ADS route is created between the client and the PLC using TwinCAT router
145
+
146
+ **Client settings:**
147
+
148
+ ```js
149
+ const client = new Client({
150
+ targetAmsNetId: '192.168.1.120.1.1', //AmsNetId of the target PLC
151
+ targetAdsPort: 851,
152
+ });
153
+ ```
154
+
155
+ ## Setup 2 - Connect from Linux/Windows
156
+
157
+ In this scenario, the client is running on Linux or Windows without TwinCAT Router. The .NET based router can be run separately on the same machine.
158
+
159
+ **Requirements:**
160
+ - Client has .NET runtime installed
161
+ - Client has [AdsRouterConsoleApp](https://github.com/Beckhoff/TF6000_ADS_DOTNET_V5_Samples/tree/main/Sources/RouterSamples/AdsRouterConsoleApp) or similar running
162
+ - An ADS route is created between the client and the PLC (see [AdsRouterConsoleApp](https://github.com/Beckhoff/TF6000_ADS_DOTNET_V5_Samples/tree/main/Sources/RouterSamples/AdsRouterConsoleApp) docs)
163
+
164
+ **Client settings:**
165
+
166
+ ```js
167
+ const client = new Client({
168
+ targetAmsNetId: '192.168.1.120.1.1', //AmsNetId of the target PLC
169
+ targetAdsPort: 851,
170
+ });
171
+ ```
172
+
173
+ ## Setup 3 - Connect from any Node.js system
174
+
175
+ In this scenario, the client is running on a machine that has no router running (no TwinCAT router and no 3rd party router). For example, Raspberry Pi without any additional installations.
176
+
177
+ In this setup, the client directly connects to the PLC and uses its TwinCAT router for communication. Only one simultaneous connection from the client is possible.
178
+
179
+ **Requirements:**
180
+ - Target system (PLC) firewall has TCP port 48898 open
181
+ - Windows Firewall might block, make sure Ethernet connection is handled as "private"
182
+ - Local AmsNetId and ADS port are set manually
183
+ - Used `localAmsNetId` is not already in use
184
+ - Used `localAdsPort` is not already in use
185
+ - An ADS route is configured to the PLC (see blow)
186
+
187
+ **Setting up the route:**
188
+
189
+ 1. At the PLC, open `C:\TwinCAT\3.1\Target\StaticRoutes.xml`
190
+ 2. Copy paste the following under `<RemoteConnections>`
191
+
192
+ ```xml
193
+ <Route>
194
+ <Name>UI</Name>
195
+ <Address>192.168.1.10</Address>
196
+ <NetId>192.168.1.10.1.1</NetId>
197
+ <Type>TCP_IP</Type>
198
+ <Flags>64</Flags>
199
+ </Route>
200
+ ```
201
+
202
+ 3. Edit `Address` to IP address of the client (which runs the Node.js app), such as `192.168.1.10`
203
+ 4. Edit `NetId` to any unused AmsNetId address, such as `192.168.1.10.1.1`
204
+ 5. Restart PLC
205
+
206
+ **Client settings:**
207
+
208
+ ```js
209
+ const client = new Client({
210
+ localAmsNetId: '192.168.1.10.1.1', //Same as Address in PLC's StaticRoutes.xml (see above)
211
+ localAdsPort: 32750, //Can be anything that is not used
212
+ targetAmsNetId: '192.168.1.120.1.1',//AmsNetId of the target PLC
213
+ targetAdsPort: 851,
214
+ routerAddress: '192.168.1.120', //PLC IP address
215
+ routerTcpPort: 48898
216
+ });
217
+ ```
218
+
219
+ **See also:**
220
+ * [Issue #51](https://github.com/jisotalo/ads-client/issues/51#issuecomment-758016428)
221
+
222
+ ## Setup 4 - Connect from local system
223
+
224
+ In this scenario, the PLC is running Node.js app locally. For example, the development PC or Beckhoff PLC with a screen for HMI.
225
+
226
+ **Requirements:**
227
+ - AMS router TCP loopback enabled (see [Enabling localhost support](#enabling-localhost-support))
228
+ - Should be already enabled in TwinCAT versions >= 4024.5.
229
+
230
+ **Client settings:**
231
+
232
+ ```js
233
+ const client = new Client({
234
+ targetAmsNetId: '127.0.0.1.1.1', //or 'localhost'
235
+ targetAdsPort: 851,
236
+ });
237
+ ```
238
+
239
+ ## Setup 5 - Docker container
240
+
241
+ It's also possible to run the client in a docker containers, also with a separate router (Linux systems).
242
+
243
+ I'm available for coding work if you need help with this. See [Supporting](#supporting)
244
+
245
+ # Important
246
+
247
+ ## Enabling localhost support on TwinCAT 3
248
+
249
+ If connecting to the local TwinCAT runtime (Node.js and PLC on the same machine), the ADS router TCP loopback feature has to be enabled.
250
+
251
+ TwinCAT 4024.5 and newer already have this enabled as default.
252
+
253
+ 1. Open registery edition (`regedit`)
254
+ 2. Navigate to
255
+
256
+ ```
257
+ 32 bit operating system:
258
+ HKEY_LOCAL_MACHINE\SOFTWARE\Beckhoff\TwinCAT3\System\
259
+
260
+ 64 bit it operating system:
261
+ HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Beckhoff\TwinCAT3\System\
262
+ ```
263
+
264
+ 3. Create new DWORD registery named `EnableAmsTcpLoopback` with value of `1`
265
+ 4. Restart
266
+
267
+ ![ads-client-tcp-loopback](https://user-images.githubusercontent.com/13457157/82748398-2640bf00-9daa-11ea-98e5-0032b3537969.png)
268
+
269
+ Now you can connect to the localhost using `targetAmsNetId` address of `127.0.0.1.1.1` or `localhost`.
270
+
271
+ ## Structured variables
272
+
273
+ When writing structured variables, the object properties are handled case-insensitively. This is because the TwinCAT is case-insensitive.
274
+
275
+ In practice, it means that the following objects are equal when passed to `writevalue()` or `convertToRaw()`:
276
+
277
+ ```js
278
+ {
279
+ sometext: 'hello',
280
+ somereal: 3.14
281
+ }
282
+ ```
283
+
284
+ ```js
285
+ {
286
+ SOmeTEXT: 'hello',
287
+ SOMEreal: 3.14
288
+ }
289
+ ```
290
+
291
+ If there are multiple properties with the same name (in case-insensitive manner), the client selects probably the first one (the selection is done by `Object.find()`):
292
+
293
+ ```js
294
+ //In this case, probably the first one (sometext) is selected and the SOMEtext is skipped.
295
+ {
296
+ sometext: 'hello',
297
+ SOMEtext: 'good day'
298
+ }
299
+ ```
300
+
301
+ ## Connecting to targets without a PLC runtime
302
+
303
+ Usually the `ads-client` is used to connect to a PLC runtime. Howevever, it's also possible to connect to any device supporting ADS protocol, such as
304
+
305
+ * TwinCAT system service
306
+ * I/O devices (EtherCAT, K-bus etc.)
307
+ * [ads-server](https://github.com/jisotalo/ads-server) instances
308
+
309
+ As default, the client assumes that there should be a PLC runtime. This causes errors with non-PLC systems, as different PLC related things are initialized.
310
+ ```
311
+ Connection failed - failed to set PLC connection. If target is not PLC runtime, use setting "rawClient". If system is in config mode or there is no PLC software yet, you might want to use setting "allowHalfOpen".
312
+ ```
313
+
314
+ By using the `rawClient` setting, the client allows raw connections to any ADS supported system.
315
+
316
+ ```js
317
+ const client = new Client({
318
+ targetAmsNetId: '192.168.5.131.3.1',
319
+ targetAdsPort: 1002,
320
+ rawClient: true // <-- NOTE
321
+ })
322
+ ```
323
+
324
+ Note that when the `rawclient` setting is set, the client only connects to the target. All other background features, such as monitoring system state, PLC symbol version or connection issues, are not available.
325
+
326
+
327
+ ## Differences when using with TwinCAT 2
328
+
329
+ * ADS port for first the PLC runtime is 801 instead of 851
330
+
331
+ ```js
332
+ const client = new ads.Client({
333
+ targetAmsNetId: '...',
334
+ targetAdsPort: 801 //<-- NOTE
335
+ });
336
+ ```
337
+
338
+ * All variable and data type names are in UPPERCASE
339
+
340
+ This might cause problems if your app is used with both TC2 & TC3 systems.
341
+
342
+ ![image](https://user-images.githubusercontent.com/13457157/86540055-96df0d80-bf0a-11ea-8f94-7e04515213c2.png)
343
+
344
+
345
+ * Global variables are accessed with dot (`.`) prefix (without the GVL name)
346
+
347
+ ```js
348
+ await client.readSymbol('GVL_Test.ExampleSTRUCT') //TwinCAT 3
349
+ await client.readSymbol('.ExampleSTRUCT') //TwinCAT 2
350
+ ```
351
+
352
+ * ENUMs are always numeric values only
353
+
354
+ * Empty structs and function blocks (without members) can't be read
355
+
356
+ # Getting started
357
+
358
+ ## Documentation
359
+
360
+ The documentation is available at [https://jisotalo.fi/ads-client](TODO-DOC-URL-HERE/classes/Client.html) and `./docs` folder.
361
+
362
+ Examples in the getting started are based on a PLC project from [https://github.com/jisotalo/ads-client-test-plc-project](https://github.com/jisotalo/ads-client-test-plc-project).
363
+
364
+ You can use the test PLC project as reference together with the [ads-client.test.js](https://github.com/jisotalo/ads-client/blob/master/test/TC3/ads-client.test.js) to see and try out all available features.
365
+
366
+ ## Available methods
367
+
368
+ Click a method to open it's documentation.
369
+
370
+ | Method | Description |
371
+ | ------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
372
+ | [`cacheDataTypes()`](TODO-DOC-URL-HERE/classes/Client.html#cacheDataTypes) | Caches all data types from the target PLC runtime. |
373
+ | [`cacheSymbols()`](TODO-DOC-URL-HERE/classes/Client.html#cacheSymbols) | Caches all symbols from the target PLC runtime. |
374
+ | [`connect()`](TODO-DOC-URL-HERE/classes/Client.html#connect) | Connects to the target. |
375
+ | [`convertFromRaw()`](TODO-DOC-URL-HERE/classes/Client.html#convertFromRaw) | Converts raw data to a Javascript object by using the provided data type. |
376
+ | [`convertToRaw()`](TODO-DOC-URL-HERE/classes/Client.html#convertToRaw) | Converts a Javascript object to raw data by using the provided data type. |
377
+ | [`createVariableHandle()`](TODO-DOC-URL-HERE/classes/Client.html#createVariableHandle) | Creates a handle to a variable at the target system by variable path (such as `GVL_Test.ExampleStruct`). |
378
+ | [`createVariableHandleMulti()`](TODO-DOC-URL-HERE/classes/Client.html#createVariableHandleMulti) | Sends multiple `createVariableHandle()` commands in one ADS packet (ADS sum command). |
379
+ | [`deleteVariableHandle()`](TODO-DOC-URL-HERE/classes/Client.html#deleteVariableHandle) | Deletes a variable handle that was previously created using `createVariableHandle()`. |
380
+ | [`deleteVariableHandleMulti()`](TODO-DOC-URL-HERE/classes/Client.html#deleteVariableHandleMulti) | Sends multiple `deleteVariableHandle()` commands in one ADS packet (ADS sum command). |
381
+ | [`disconnect()`](TODO-DOC-URL-HERE/classes/Client.html#disconnect) | Disconnects from the target and closes active connection. |
382
+ | [`getDataType()`](TODO-DOC-URL-HERE/classes/Client.html#getDataType) | Returns full data type declaration for requested data type (such as `ST_Struct`). |
383
+ | [`getDataTypes()`](TODO-DOC-URL-HERE/classes/Client.html#getDataTypes) | Returns all target PLC runtime data types. |
384
+ | [`getDefaultPlcObject()`](TODO-DOC-URL-HERE/classes/Client.html#getDefaultPlcObject) | Returns a default (empty) Javascript object representing provided PLC data type. |
385
+ | [`getSymbol()`](TODO-DOC-URL-HERE/classes/Client.html#getSymbol) | Returns a symbol object for given variable path (such as `GVL_Test.ExampleStruct`). |
386
+ | [`getSymbols()`](TODO-DOC-URL-HERE/classes/Client.html#getSymbols) | Returns all symbols from the target PLC runtime. |
387
+ | [`invokeRpcMethod()`](TODO-DOC-URL-HERE/classes/Client.html#invokeRpcMethod) | Invokes a function block RPC method on the target system. |
388
+ | [`readDeviceInfo()`](TODO-DOC-URL-HERE/classes/Client.html#readDeviceInfo) | Reads target device information. |
389
+ | [`readPlcRuntimeState()`](TODO-DOC-URL-HERE/classes/Client.html#readPlcRuntimeState) | Reads target PLC runtime state (`Run`, `Stop` etc.) |
390
+ | [`readPlcSymbolVersion()`](TODO-DOC-URL-HERE/classes/Client.html#readPlcSymbolVersion) | Reads target PLC runtime symbol version. |
391
+ | [`readPlcUploadInfo()`](TODO-DOC-URL-HERE/classes/Client.html#readPlcUploadInfo) | Reads target PLC runtime upload information. |
392
+ | [`readRaw()`](TODO-DOC-URL-HERE/classes/Client.html#readRaw) | Reads raw data from the target system by a raw ADS address (index group, index offset and data length). |
393
+ | [`readRawByHandle()`](TODO-DOC-URL-HERE/classes/Client.html#readRawByHandle) | Reads raw data from the target system by a previously created variable handle (acquired using `createVariableHandle()`). |
394
+ | [`readRawByPath()`](TODO-DOC-URL-HERE/classes/Client.html#readRawByPath) | Reads raw data from the target system by variable path (such as `GVL_Test.ExampleStruct`). |
395
+ | [`readRawBySymbol()`](TODO-DOC-URL-HERE/classes/Client.html#readRawBySymbol) | Reads raw data from the target system by a symbol object (acquired using `getSymbol()`). |
396
+ | [`readRawMulti()`](TODO-DOC-URL-HERE/classes/Client.html#readRawMulti) | Sends multiple `readRaw()` commands in one ADS packet (ADS sum command). |
397
+ | [`readState()`](TODO-DOC-URL-HERE/classes/Client.html#readState) | Reads target ADS state. |
398
+ | [`readTcSystemState()`](TODO-DOC-URL-HERE/classes/Client.html#readTcSystemState) | Reads target TwinCAT system state from ADS port 10000 (usually `Run` or `Config`). |
399
+ | [`readValue()`](TODO-DOC-URL-HERE/classes/Client.html#readValue) | Reads variable's value from the target system by a variable path (such as `GVL_Test.ExampleStruct`) and returns the value as a Javascript object. |
400
+ | [`readValueBySymbol()`](TODO-DOC-URL-HERE/classes/Client.html#readValueBySymbol) | Reads variable's value from the target system by a symbol object (acquired using `getSymbol()`) and returns the value as a Javascript object. |
401
+ | [`readWriteRaw()`](TODO-DOC-URL-HERE/classes/Client.html#readWriteRaw) | Writes raw data to the target system by a raw ADS address (index group, index offset) and reads the result as raw data. |
402
+ | [`readWriteRawMulti()`](TODO-DOC-URL-HERE/classes/Client.html#readWriteRawMulti) | Sends multiple `readWriteRaw()` commands in one ADS packet (ADS sum command). |
403
+ | [`reconnect()`](TODO-DOC-URL-HERE/classes/Client.html#reconnect) | Reconnects to the target (disconnects and then connects again). |
404
+ | [`resetPlc()`](TODO-DOC-URL-HERE/classes/Client.html#resetPlc) | Resets the target PLC runtime. Same as reset cold in TwinCAT XAE. |
405
+ | [`restartPlc()`](TODO-DOC-URL-HERE/classes/Client.html#restartPlc) | Restarts the PLC runtime. Same as calling `resetPlc()` and then `startPlc()`. |
406
+ | [`restartTcSystem()`](TODO-DOC-URL-HERE/classes/Client.html#restartTcSystem) | Restarts the target TwinCAT system. |
407
+ | [`sendAdsCommand()`](TODO-DOC-URL-HERE/classes/Client.html#sendAdsCommand) | Sends a raw ADS command to the target. |
408
+ | [`setDebugLevel()`](TODO-DOC-URL-HERE/classes/Client.html#setDebugLevel) | Sets active debug level. |
409
+ | [`setTcSystemToConfig()`](TODO-DOC-URL-HERE/classes/Client.html#setTcSystemToConfig) | Sets the target TwinCAT system to config mode. Same as `Restart TwinCAT (Config mode)` in TwinCAT XAE. |
410
+ | [`setTcSystemToRun()`](TODO-DOC-URL-HERE/classes/Client.html#setTcSystemToRun) | Sets the target TwinCAT system to run mode. Same as `Restart TwinCAT system` in TwinCAT XAE. |
411
+ | [`startPlc()`](TODO-DOC-URL-HERE/classes/Client.html#startPlc) | Starts the target PLC runtime. Same as pressing the green play button in TwinCAT XAE. |
412
+ | [`stopPlc()`](TODO-DOC-URL-HERE/classes/Client.html#stopPlc) | Stops the target PLC runtime. Same as pressing the red stop button in TwinCAT XAE. |
413
+ | [`subscribe()`](TODO-DOC-URL-HERE/classes/Client.html#subscribe) | Subscribes to value change notifications (ADS notifications) by variable path (such as `GVL_Test.ExampleStruct`) or raw ADS address (index group, index offset and data length). |
414
+ | [`subscribeRaw()`](TODO-DOC-URL-HERE/classes/Client.html#subscribeRaw) | Subscribes to raw value change notifications (ADS notifications) by a raw ADS address (index group, index offset and data length). |
415
+ | [`subscribeValue()`](TODO-DOC-URL-HERE/classes/Client.html#subscribeValue) | Subscribes to value change notifications (ADS notifications) by a variable path, such as `GVL_Test.ExampleStruct`. |
416
+ | [`unsubscribe()`](TODO-DOC-URL-HERE/classes/Client.html#unsubscribe) | Unsubscribes a subscription (deletes ADS notification). |
417
+ | [`unsubscribeAll()`](TODO-DOC-URL-HERE/classes/Client.html#unsubscribeAll) | Unsubscribes all active subscription (deletes all ADS notifications). |
418
+ | [`writeControl()`](TODO-DOC-URL-HERE/classes/Client.html#writeControl) | Sends an ADS `WriteControl` command to the target. |
419
+ | [`writeRaw()`](TODO-DOC-URL-HERE/classes/Client.html#writeRaw) | Writes raw data to the target system by a raw ADS address (index group, index offset and data length). |
420
+ | [`writeRawByHandle()`](TODO-DOC-URL-HERE/classes/Client.html#writeRawByHandle) | Writes raw data to the target system by a previously created variable handle (acquired using `createVariableHandle()`). |
421
+ | [`writeRawByPath()`](TODO-DOC-URL-HERE/classes/Client.html#writeRawByPath) | Writes raw data to the target system by variable path (such as `GVL_Test.ExampleStruct`). |
422
+ | [`writeRawBySymbol()`](TODO-DOC-URL-HERE/classes/Client.html#writeRawBySymbol) | Writes raw data to the target system by a symbol object (acquired using `getSymbol()`). |
423
+ | [`writeRawMulti()`](TODO-DOC-URL-HERE/classes/Client.html#writeRawMulti) | Sends multiple `writeRaw()` commands in one ADS packet (ADS sum command). |
424
+ | [`writeValue()`](TODO-DOC-URL-HERE/classes/Client.html#writeValue) | Writes variable's value to the target system by a variable path (such as `GVL_Test.ExampleStruct`). Converts the value from a Javascript object to a raw value. |
425
+ | [`writeValueBySymbol()`](TODO-DOC-URL-HERE/classes/Client.html#writeValueBySymbol) | Writes variable's value to the target system by a symbol object (acquired using `getSymbol()`). Converts the value from a Javascript object to a raw value. |
426
+
427
+
428
+
429
+
430
+
431
+
432
+ ## Creating a client
433
+
434
+ Settings are passed via the [`Client`](https://jisotalo.fi/ads-client/classes/Client.html) constructor. The following settings are mandatory:
435
+ - [`targetAmsNetId`](https://jisotalo.fi/ads-client/interfaces/AdsClientSettings.html#targetAmsNetId) - Target runtime AmsNetId
436
+ - [`targetAdsPort`](https://jisotalo.fi/ads-client/interfaces/AdsClientSettings.html#targetAdsPort) - Target runtime ADS port
437
+
438
+ See other settings from the [`AdsClientSettings` documentation](https://jisotalo.fi/ads-client/interfaces/AdsClientSettings.html).
40
439
 
41
440
  ```js
42
441
  const client = new Client({
43
442
  targetAmsNetId: "localhost",
44
443
  targetAdsPort: 851
45
444
  });
445
+ ```
446
+
447
+ ## Connecting
46
448
 
47
- await client.connect();
449
+ It's a good practice to start a connection at startup and keep it open until the app is closed.
450
+ If there are connection issues or the PLC software is updated, the client will handle everything automatically.
451
+
452
+
453
+ ```js
454
+ const { Client } = require('ads-client');
455
+
456
+ const client = new Client({
457
+ targetAmsNetId: 'localhost',
458
+ targetAdsPort: 851
459
+ })
460
+
461
+ client.connect()
462
+ .then(res => {
463
+ console.log(`Connected to the ${res.targetAmsNetId}`)
464
+ console.log(`Router assigned us AmsNetId ${res.localAmsNetId} and port ${res.localAdsPort}`)
465
+
466
+ }).catch(err => {
467
+ console.log('Error:', err)
468
+ });
48
469
  ```
49
470
 
50
- ### Read a value
471
+ ## Reading values
472
+
473
+ ### Reading any value
474
+
475
+ Use [`readValue()`](TODO-DOC-URL-HERE/classes/Client.html#readValue) to read any PLC value as a Javascript object. If using Typescript, the type of the PLC variable can be passed as well (`readValue<T>()`).
476
+
477
+ The only exception is the dereferenced value of a reference/pointer, see [Reading reference/pointer](#reading-referencepointer).
51
478
 
52
479
  ```js
53
- const res = await client.readValue('GVL_Example.StringValue');
54
- console.log(res.value);
480
+ try {
481
+ let res;
55
482
 
56
- //Typescript:
57
- const res = await client.readValue<string>('GVL_Example.StringValue');
58
- console.log(res.value); //res.value is typed as string (instead of any)
483
+ //Example: INT
484
+ res = await client.readValue('GVL_Read.StandardTypes.INT_');
485
+ console.log(res.value);
486
+ // 32767
487
+
488
+ //Example: STRING
489
+ res = await client.readValue('GVL_Read.StandardTypes.STRING_');
490
+ console.log(res.value);
491
+ // A test string ääöö!!@@
492
+
493
+ //Example: DT
494
+ res = await client.readValue('GVL_Read.StandardTypes.DT_');
495
+ console.log(res.value);
496
+ // 2106-02-06T06:28:15.000Z (Date object)
497
+
498
+ //Example: STRUCT
499
+ res = await client.readValue('GVL_Read.ComplexTypes.STRUCT_');
500
+ console.log(res.value);
501
+ /*
502
+ {
503
+ BOOL_: true,
504
+ BOOL_2: false,
505
+ BYTE_: 255,
506
+ WORD_: 65535,
507
+ //...and so on
508
+ }
509
+ */
510
+
511
+ //Example: FUNCTION_BLOCK
512
+ res = await client.readValue('GVL_Read.ComplexTypes.BLOCK_2'); //TON
513
+ console.log(res.value);
514
+ // { IN: false, PT: 2500, Q: false, ET: 0, M: false, StartTime: 0 }
59
515
 
516
+ //Example: ARRAY
517
+ res = await client.readValue('GVL_Read.StandardArrays.REAL_3');
518
+ console.log(res.value);
519
+ // [ 75483.546875, 0, -75483.546875 ]
520
+
521
+ //Example: ENUM
522
+ res = await client.readValue('GVL_Read.ComplexTypes.ENUM_');
523
+ console.log(res.value);
524
+ // { name: 'Running', value: 100 }
525
+
526
+ } catch (err) {
527
+ console.log("Error:", err);
528
+ }
60
529
  ```
61
530
 
62
- ### Write a value
531
+ **Typescript example**:
532
+
533
+ ```ts
534
+ let res;
535
+
536
+ //Example: INT
537
+ res = await client.readValue<number>('GVL_Read.StandardTypes.INT_');
538
+ console.log(res.value); //res.value is typed as number
539
+ // 32767
540
+
541
+ //Example: STRUCT
542
+ interface ST_ComplexTypes {
543
+ BOOL_: boolean,
544
+ BOOL_2: boolean,
545
+ BYTE_: number,
546
+ WORD_: number,
547
+ //..and so on
548
+ }
549
+
550
+ res = await client.readValue<ST_ComplexTypes>('GVL_Read.ComplexTypes.STRUCT_');
551
+ console.log(res.value); //res.value is typed as ST_ComplexTypes
552
+ /*
553
+ {
554
+ BOOL_: true,
555
+ BOOL_2: false,
556
+ BYTE_: 255,
557
+ WORD_: 65535,
558
+ //..and so on
559
+ }
560
+ */
561
+ ```
562
+
563
+ ### Reading raw data
564
+
565
+ Use [`readRaw()`](TODO-DOC-URL-HERE/classes/Client.html#readRaw) to read any PLC value as raw data. Raw data is a `Buffer` object, containing the data as bytes.
566
+
567
+ The only exception is the dereferenced value of a reference/pointer, see [Reading reference/pointer](#reading-referencepointer).
568
+
569
+ The `indexGroup` and `indexOffset` can be acquired for example by using [`getSymbol()`](TODO-DOC-URL-HERE/classes/Client.html#getSymbol).
63
570
 
64
571
  ```js
65
- await client.writeValue('GVL_Example.StringValue', 'a new value');
572
+ try {
573
+ //Example: Reading raw data by index offset and index group
574
+ //and converting it to a Javascript object manually
575
+ const data = await client.readRaw(16448, 414816, 2);
576
+ console.log(data); //<Buffer ff 7f>
577
+
578
+ const converted = await client.convertFromRaw(data, 'INT');
579
+ console.log(converted); //32767
580
+
581
+ } catch (err) {
582
+ console.log("Error:", err);
583
+ }
66
584
  ```
67
- ### Subscribe to value changes
585
+
586
+ [`readRawByPath()`](TODO-DOC-URL-HERE/classes/Client.html#readRawByPath) can be used to read raw data by a variable path.
68
587
 
69
588
  ```js
70
- await client.subscribe({
71
- target: 'GVL_Example.ChangingValue',
72
- cycleTime: 100,
73
- callback: (data, subscription) => console.log(`${data.timestamp}: Value changed to ${data.value}`)
74
- });
589
+ try {
590
+ //Example: Reading raw data by variable path
591
+ //and converting it to a Javascript object manually
592
+ const data = await client.readRawByPath('GVL_Read.StandardTypes.INT_');
593
+ console.log(data); //<Buffer ff 7f>
75
594
 
76
- //Typescript:
77
- await client.subscribe<number>({
78
- target: 'GVL_Example.ChangingValue',
79
- cycleTime: 100,
80
- callback: (data, subscription) => {
81
- //data.value is typed as string (instead of any)
82
- console.log(`${data.timestamp}: Value changed to ${data.value}`);
595
+ const converted = await client.convertFromRaw(data, 'INT');
596
+ console.log(converted); //32767
597
+
598
+ } catch (err) {
599
+ console.log("Error:", err);
600
+ }
601
+ ```
602
+
603
+ ### Reading reference/pointer
604
+
605
+ The dereferenced value of a reference (`REFERENCE TO`) or a pointer (`POINTER TO`) can be read
606
+ using [`readRawByPath()`](TODO-DOC-URL-HERE/classes/Client.html#readRawByPath).
607
+
608
+ ```js
609
+ try {
610
+ //Reading a raw POINTER value (Note the dereference operator ^)
611
+ const rawPtrValue = await client.readRawByPath('GVL_Read.ComplexTypes.POINTER_^');
612
+
613
+ //Converting to a Javascript object
614
+ const ptrValue = await client.convertFromRaw(rawPtrValue, 'ST_StandardTypes');
615
+ console.log(ptrValue);
616
+
617
+ //Reading a raw REFERENCE value
618
+ const rawRefValue = await client.readRawByPath('GVL_Read.ComplexTypes.REFERENCE_');
619
+
620
+ //Converting to a Javascript object
621
+ const refValue = await client.convertFromRaw(rawRefValue, 'ST_StandardTypes');
622
+ console.log(refValue);
623
+
624
+ //Short version:
625
+ const refValue2 = await client.convertFromRaw(
626
+ await client.readRawByPath('GVL_Read.ComplexTypes.REFERENCE_'),
627
+ 'ST_StandardTypes'
628
+ );
629
+
630
+ } catch (err) {
631
+ console.log("Error:", err);
632
+ }
633
+ ```
634
+
635
+ Another way is to use [variable handles](TODO-DOC-URL-HERE/classes/Client.html#createVariableHandle).
636
+
637
+ ```js
638
+ try {
639
+ //Reading a POINTER value (Note the dereference operator ^)
640
+ const ptrHandle = await client.createVariableHandle('GVL_Read.ComplexTypes.POINTER_^');
641
+ const rawPtrValue = await client.readRawByHandle(ptrHandle);
642
+ await client.deleteVariableHandle(ptrHandle);
643
+
644
+ //Converting to a Javascript object
645
+ const ptrValue = await client.convertFromRaw(rawPtrValue, 'ST_StandardTypes');
646
+ console.log(ptrValue);
647
+
648
+ //Reading a REFERENCE value
649
+ const refHandle = await client.createVariableHandle('GVL_Read.ComplexTypes.REFERENCE_');
650
+ const rawRefValue = await client.readRawByHandle(refHandle);
651
+ await client.deleteVariableHandle(refHandle);
652
+
653
+ //Converting to a Javascript object
654
+ const refValue = await client.convertFromRaw(rawRefValue, 'ST_StandardTypes');
655
+ console.log(refValue);
656
+
657
+ } catch (err) {
658
+ console.log("Error:", err);
659
+ }
660
+ ```
661
+
662
+ ## Writing values
663
+
664
+ ### Writing any value
665
+
666
+ Use [`writeValue()`](TODO-DOC-URL-HERE/classes/Client.html#writeValue) to write any PLC value.
667
+
668
+ The only exception is the dereferenced value of a reference/pointer, see [Writing reference/pointer](#writing-referencepointer).
669
+
670
+ ```js
671
+ try {
672
+ //Example: INT
673
+ await client.writeValue('GVL_Write.StandardTypes.INT_', 32767);
674
+
675
+ //Example: STRING
676
+ await client.writeValue('GVL_Write.StandardTypes.STRING_', 'This is a test');
677
+
678
+ //Example: DT
679
+ await client.writeValue('GVL_Write.StandardTypes.DT_', new Date());
680
+
681
+ //Example: STRUCT (all properties)
682
+ await client.writeValue('GVL_Write.ComplexTypes.STRUCT_', {
683
+ BOOL_: true,
684
+ BOOL_2: false,
685
+ BYTE_: 255,
686
+ WORD_: 65535,
687
+ //...and so on
688
+ });
689
+
690
+ //Example: STRUCT (only some properties)
691
+ await client.writeValue('GVL_Write.ComplexTypes.STRUCT_', {
692
+ WORD_: 65535
693
+ }, true); //<-- NOTE: autoFill set
694
+
695
+ //Example: FUNCTION_BLOCK (all properties)
696
+ await client.writeValue('GVL_Write.ComplexTypes.BLOCK_2', {
697
+ IN: false,
698
+ PT: 2500,
699
+ Q: false,
700
+ ET: 0,
701
+ M: false,
702
+ StartTime: 0
703
+ });
704
+
705
+ //Example: FUNCTION_BLOCK (only some properties)
706
+ await client.writeValue('GVL_Write.ComplexTypes.BLOCK_2', {
707
+ IN: true
708
+ }, true); //<-- NOTE: autoFill set
709
+
710
+ //Example: ARRAY
711
+ await client.writeValue('GVL_Write.StandardArrays.REAL_3', [
712
+ 75483.546875,
713
+ 0,
714
+ -75483.546875
715
+ ]);
716
+
717
+ //Example: ENUM
718
+ res = await client.writeValue('GVL_Write.ComplexTypes.ENUM_', 'Running');
719
+ //...or...
720
+ res = await client.writeValue('GVL_Write.ComplexTypes.ENUM_', 100);
721
+
722
+ } catch (err) {
723
+ console.log("Error:", err);
724
+ }
725
+ ```
726
+
727
+ ### Writing raw data
728
+
729
+ Use [`writeRaw()`](TODO-DOC-URL-HERE/classes/Client.html#writeRaw) to write any PLC value using raw data. Raw data is a `Buffer` object, containing the data as bytes.
730
+
731
+ The only exception is the dereferenced value of a reference/pointer, see [Reading reference/pointer](#reading-referencepointer).
732
+
733
+ The `indexGroup` and `indexOffset` can be acquired for example by using [`getSymbol()`](TODO-DOC-URL-HERE/classes/Client.html#getSymbol).
734
+
735
+ ```js
736
+ try {
737
+ //Example: Writing a INT variable by index offset and index group using raw data
738
+ const data = await client.convertToRaw(32767, 'INT');
739
+ console.log(data); //<Buffer ff 7f>
740
+
741
+ await client.writeRaw(16448, 414816, data);
742
+
743
+ } catch (err) {
744
+ console.log("Error:", err);
745
+ }
746
+ ```
747
+
748
+ [`writeRawByPath()`](TODO-DOC-URL-HERE/classes/Client.html#writeRawByPath) can be used to write raw data by a variable path.
749
+
750
+ ```js
751
+ try {
752
+ //Example: Writing a INT variable by its variable path using raw data
753
+ const data = await client.convertToRaw(32767, 'INT');
754
+ console.log(data); //<Buffer ff 7f>
755
+
756
+ await client.writeRawByPath('GVL_Write.StandardTypes.INT_', data);
757
+
758
+ } catch (err) {
759
+ console.log("Error:", err);
760
+ }
761
+ ```
762
+
763
+ ### Writing reference/pointer
764
+
765
+ The dereferenced value of a reference (`REFERENCE TO`) or a pointer (`POINTER TO`) can be written
766
+ using [`writeRawByPath()`](TODO-DOC-URL-HERE/classes/Client.html#writeRawByPath).
767
+
768
+ ```js
769
+ try {
770
+ //Writing a POINTER value
771
+ const ptrValue = {...} //some value
772
+ const rawPtrValue = await client.convertToRaw(ptrValue, 'ST_StandardTypes');
773
+
774
+ await client.writeRawByPath('GVL_Write.ComplexTypes.POINTER_^', rawPtrValue);
775
+
776
+ //Writing a REFERENCE value
777
+ const refValue = {...} //some value
778
+ const rawRefValue = await client.convertToRaw(refValue, 'ST_StandardTypes');
779
+ await client.writeRawByPath('GVL_Write.ComplexTypes.REFERENCE_', rawRefValue);
780
+
781
+ } catch (err) {
782
+ console.log("Error:", err);
783
+ }
784
+ ```
785
+
786
+ Another way is to use [variable handles](TODO-DOC-URL-HERE/classes/Client.html#createVariableHandle).
787
+
788
+ ```js
789
+ try {
790
+ //Writing a POINTER value (Note the dereference operator ^)
791
+ const ptrValue = {...} //some value
792
+ const rawPtrValue = await client.convertToRaw(ptrValue, 'ST_StandardTypes');
793
+
794
+ const ptrHandle = await client.createVariableHandle('GVL_Write.ComplexTypes.POINTER_^');
795
+ await client.writeRawByHandle(ptrHandle, rawPtrValue);
796
+ await client.deleteVariableHandle(ptrHandle);
797
+
798
+ //Writing a REFERENCE value
799
+ const refValue = {...} //some value
800
+ const rawRefValue = await client.convertToRaw(refValue, 'ST_StandardTypes');
801
+
802
+ const refHandle = await client.createVariableHandle('GVL_Write.ComplexTypes.REFERENCE_');
803
+ await client.writeRawByHandle(refHandle, rawRefValue);
804
+ await client.deleteVariableHandle(refHandle);
805
+
806
+ } catch (err) {
807
+ console.log("Error:", err);
808
+ }
809
+ ```
810
+
811
+ ## Subscribing to value changes
812
+
813
+ In ads-client, subscriptions are used to handle ADS notifications.
814
+
815
+ By subscribing to a variable value changes, the target system (PLC) will send ADS notifications when the value changes (or every x milliseconds). The client then receives these notifications and calls the callback function with the latest value.
816
+
817
+ More information about ADS notifications at [Beckhoff Infosys: Use of ADS Notifications](https://infosys.beckhoff.com/content/1033/tc3_ads.net/9407523595.html?id=431879546285476216).
818
+
819
+ ### Any value
820
+
821
+ Use [`subscribeValue()`](TODO-DOC-URL-HERE/classes/Client.html#subscribeValue) or [`subscribe()`](TODO-DOC-URL-HERE/classes/Client.html#subscribe) to subscribe to PLC variable value changes.
822
+
823
+ Example: Subscribe to changes of `GVL_Subscription.NumericValue_10ms`. The callback is called when the PLC value changes (at maximum every 100 milliseconds).
824
+ ```js
825
+ try {
826
+ const sub = await client.subscribeValue(
827
+ 'GVL_Subscription.NumericValue_10ms',
828
+ (data, subscription) => {
829
+ console.log(`Value of ${subscription.symbol.name} has changed: ${data.value}`);
830
+ },
831
+ 100
832
+ );
833
+
834
+ } catch (err) {
835
+ console.log("Error:", err);
836
+ }
837
+ ```
838
+
839
+ Example: Subscribe to value of `GVL_Subscription.NumericValue_1000ms`. The callback is called with the latest value every 100 milliseconds (changed or not).
840
+
841
+ ```js
842
+ try {
843
+ const valueChanged = (data, subscription) => {
844
+ console.log(`Value of ${subscription.symbol.name}: ${data.value}`);
83
845
  }
84
- });
846
+
847
+ const sub = await client.subscribeValue(
848
+ 'GVL_Subscription.NumericValue_1000ms',
849
+ valueChanged,
850
+ 100,
851
+ false
852
+ );
853
+
854
+ } catch (err) {
855
+ console.log("Error:", err);
856
+ }
85
857
  ```
86
858
 
87
- ## Support
859
+ Example: Same as previous example but using [`subscribe()`](TODO-DOC-URL-HERE/classes/Client.html#subscribe) and Typescript type for the variable value. A type can be provided for `subscribeValue<T>()` as well.
88
860
 
89
- * Bugs and feature requests:
90
- * [Github Issues](https://github.com/jisotalo/ads-client/issues)
91
- * Help, support and discussion:
92
- * [Github Discussions](https://github.com/jisotalo/ads-client/discussions)
93
- * Professional support:
94
- * Support and also development available
95
- * Contact me!
861
+ ```js
862
+ //NOTE: Typescript
863
+ try {
864
+ const valueChanged = (data, subscription) => {
865
+ //data.value is typed as "number" instead of "any" (see subscribe() call below)
866
+ console.log(`Value of ${subscription.symbol.name}: ${data.value}`);
867
+ }
96
868
 
97
- If the library has been useful for you or your business, Paypal can be used to support my work. Or contact me and let's discuss the options!
869
+ const sub = await client.subscribe<number>({
870
+ target: 'GVL_Subscription.NumericValue_1000ms',
871
+ callback: valueChanged,
872
+ cycleTime: 100,
873
+ sendOnChange: false
874
+ });
98
875
 
99
- [![Donate](https://img.shields.io/badge/Donate-PayPal-yellow)](https://www.paypal.com/donate/?business=KUWBXXCVGZZME&no_recurring=0&currency_code=EUR)
876
+ } catch (err) {
877
+ console.log("Error:", err);
878
+ }
879
+ ```
100
880
 
101
- ## TwinCAT 2
881
+ ### Raw data
102
882
 
103
- The library works also with TwinCAT 2.
883
+ Use [`subscribeRaw()`](TODO-DOC-URL-HERE/classes/Client.html#subscribeRaw) or [`subscribe()`](TODO-DOC-URL-HERE/classes/Client.html#subscribe) to subscribe to raw value changes.
104
884
 
105
- Please note the following things when communicating with TC2 systems:
106
- * ADS port for first PLC runtime is 801 instead of 851
107
- * All variable names are in UPPERCASE
108
- * All data type names are in UPPERCASE
109
- * Global variables are accessed with dot (`.`) prefix, without the GVL name
110
- * ENUMs are always numeric values only
111
- * Empty structs and function blocks (no members) can't be read
885
+ The `indexGroup` and `indexOffset` can be acquired for example by using [`getSymbol()`](TODO-DOC-URL-HERE/classes/Client.html#getSymbol).
886
+
887
+ Example: Subscribe to raw address of `indexGroup` = 16448, `indexOffset` = 414816 and `size` = 2 bytes.
888
+
889
+ ```js
890
+ try {
891
+ await client.subscribeRaw(16448, 414816, 2, (data, subscription) => {
892
+ console.log(`Value has changed: ${data.value.toString('hex')}`);
893
+ }, 100);
894
+
895
+ } catch (err) {
896
+ console.log("Error:", err);
897
+ }
898
+ ```
899
+
900
+ Same using [`subscribe()`](TODO-DOC-URL-HERE/classes/Client.html#subscribe):
901
+ ```js
902
+ try {
903
+ await client.subscribe({
904
+ target: {
905
+ indexGroup: 16448,
906
+ indexOffset: 414816,
907
+ size: 2
908
+ },
909
+ callback: (data, subscription) => {
910
+ console.log(`Value has changed: ${data.value.toString('hex')}`);
911
+ },
912
+ cycleTime: 100
913
+ });
914
+
915
+ } catch (err) {
916
+ console.log("Error:", err);
917
+ }
918
+ ```
919
+
920
+ ### Unsubscribing
921
+
922
+ Subscriptions should always be cancelled when no longer needed (to save PLC resources). Use [`unsubscribe()`](TODO-DOC-URL-HERE/classes/Client.html#unsubscribe) or subscription object's [`ActiveSubscription.unsubscribe()`](TODO-DOC-URL-HERE/interfaces/ActiveSubscription.html#unsubscribe) to unsubscribe.
923
+
924
+ ```js
925
+ const sub = await client.subscribeValue(...);
926
+
927
+ //Later when no longer needed
928
+ await sub.unsubscribe();
929
+ //or await client.unsubscribe(sub);
930
+ ```
931
+
932
+ ## Using variable handles
933
+
934
+ Variable handles are another alternative to read and write raw data.
935
+
936
+ A handle is created to a specific PLC variable and after that, read and write operations are available.
937
+ There is no need to use `indexGroup` or `indexOffset`.
938
+
939
+ Handles should always be deleted after no longer needed, as the PLC has limited number of handles.
940
+ However, it's a perfectly valid practice to keep the handles open as long as needed.
941
+
942
+ Handles can also be used to read/write reference and pointer values, see [Reading reference/pointer](#reading-referencepointer).
943
+
944
+ ### Reading a value using a variable handle
945
+
946
+ ```js
947
+ //Creating a handle
948
+ const handle = await client.createVariableHandle('GVL_Read.StandardTypes.INT_');
949
+
950
+ //Reading a value
951
+ const data = await client.readRawByHandle(handle);
952
+
953
+ //Deleting the handle
954
+ await client.deleteVariableHandle(handle);
955
+
956
+ //Converting to a Javascript value
957
+ const converted = await client.convertFromRaw(data, 'INT');
958
+ console.log(data); //<Buffer ff 7f>
959
+ console.log(converted); //32767
960
+ ```
961
+
962
+ ### Writing a value using a variable handle
963
+
964
+ ```js
965
+ //Creating a raw value
966
+ const data = await client.convertToRaw(32767, 'INT');
967
+ console.log(data); //<Buffer ff 7f>
968
+
969
+ //Creating a handle
970
+ const handle = await client.createVariableHandle('GVL_Write.StandardTypes.INT_');
971
+
972
+ //Writing the value
973
+ await client.writeRawByHandle(handle, data);
974
+
975
+ //Deleting the handle
976
+ await client.deleteVariableHandle(handle);
977
+ ```
978
+
979
+ ## Calling function block RPC methods
980
+
981
+ If a function block method has pragma `{attribute 'TcRpcEnable'}`, the method can be called from ads-client.
982
+
983
+ Read more at [Beckhoff Infosys: Attribute 'TcRpcEnable'](https://infosys.beckhoff.com/english.php?content=../content/1033/tc3_plc_intro/7145472907.html).
984
+
985
+ ### Things to note when using RPC Methods
112
986
 
113
- See the TwinCAT 2 tests for supported and tested features.
987
+ - Do not use online change if you change RPC method parameters or return data types
988
+ - Make sure that parameters and return value have no pack-mode pragmas defined, otherwise data might be corrupted
989
+ - Do not use `ARRAY` values directly in parameters or return value, encapsulate arrays inside struct and use the struct instead
990
+ - The feature isn't well documented by Bechkhoff, so there might be some things that aren't taken into account
991
+
992
+ ### Simple RPC method example
993
+
994
+ ### RPC methods with structs
995
+
996
+ ## Converting from/to raw data
997
+
998
+ README in progress.
999
+
1000
+ ## Other features
1001
+
1002
+ README in progress.
1003
+
1004
+ ## Disconnecting
1005
+
1006
+ After the client is no more used, always use [`disconnect()`](TODO-DOC-URL-HERE/classes/Client.html#disconnect) to release all subscription handles and other resources.
1007
+
1008
+ ```js
1009
+ await client.disconnect();
1010
+ ```
1011
+
1012
+ ## FAQ
1013
+
1014
+ ### Lot's of connection issues and timeouts
1015
+ Things to try:
1016
+ - Remove all TwinCAT routes and create them again (yes, really)
1017
+ - Increase value of [`timeoutDelay`](TODO-DOC-URL-HERE/interfaces/AdsClientSettings.html#timeoutDelay) setting
1018
+ - Cache all data types and symbols straight after connecting using [`cacheDataTypes`](TODO-DOC-URL-HERE/classes/Client.html#cacheDataTypes) and [`cacheSymbols`](TODO-DOC-URL-HERE/classes/Client.html#cacheSymbols)
1019
+
1020
+ ### Getting `TypeError: Do not know how to serialize a BigInt`
1021
+ - `JSON.stringify` doesn't understand BigInt values (such as `LINT` or similar 64 bit PLC values)
1022
+ - Check [this Github issue](https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-953187833) for a patch
1023
+ - `BigInt.prototype.toJSON = function() { return this.toString() }`
1024
+
1025
+ ### Can I connect from Raspberry Pi to TwinCAT?
1026
+
1027
+ Yes, for example using [Setup 3 - Connect from any Node.js system](#setup-3---connect-from-any-nodejs-system).
1028
+ 1. Open a TCP port 48898 from your PLC
1029
+ 2. Edit `StaticRoutes.xml` file from your PLC
1030
+ 3. Connect from the Raspberry Pi using the PLC IP address as `routerAddress` and the AmsNetID written to `StaticRoutes.xml` as `localAmsNetId`
1031
+
1032
+ ### Receiving ADS error 1808 `Symbol not found` even when it should be found
1033
+
1034
+ - Make sure you have updated the latest PLC software using *download*. Sometimes online change causes this.
1035
+ - If you are using TwinCAT 2, see chapter [Differences when using with TwinCAT 2](#differences-when-using-with-twincat-2)
1036
+
1037
+ ### Having timeouts or 'mailbox is full' errors
1038
+
1039
+ - The AMS router is capable of handling only limited number of requests in a certain time.
1040
+ - Other possible reason is that operating system TCP window is full because of large number of requests.
1041
+ - Solution:
1042
+ - Use structs or arrays to send data in larger packets
1043
+ - Try raw/multi commands to decrease data usage
1044
+
1045
+ ### Having problems to connect from OSX or Raspberry Pi to target PLC
1046
+
1047
+ - You need to connect to the PLC AMS router instead
1048
+ - See [this issue comment](https://github.com/jisotalo/ads-client/issues/51#issuecomment-758016428)
1049
+
1050
+ ### A data type is not found even when it should be
1051
+
1052
+ If you use methods like `convertFromRaw()` and `getDataType()` but receive an error similar to `ClientException: Finding data type *data type* failed`, make sure you have really written the data type correctly.
1053
+
1054
+ For example, when copying a variable name from TwinCAT online view using CTRL+C, it might not work:
1055
+ - Displayed name: `ARRAY [0..1, 0..1] OF ST_Example`
1056
+ - The value copied to clipboard `ARRAY [0..1, 0..1] OF ST_Example`
1057
+ - --> **This causes error!**
1058
+ - The real data type name that needs to be used is `ARRAY [0..1,0..1] OF ST_Example` (note no whitespace between array dimensions)
1059
+
1060
+ If you have problems, try to read the symbol object using `getSymbol()`. The final solution is to read all data types using `getDataTypes()` and manually finding the correct type.
1061
+
1062
+ ### ClientException: Connection failed: Device system manager state read failed
1063
+
1064
+ - The `targetAmsNetId` didn't contain a system manager service (port `10000`)
1065
+ - The target is not a PLC and `rawClient` setting is not set
1066
+ - Solution:
1067
+ - Double-check connection settings
1068
+ - [Use `rawClient` setting ](#connecting-to-targets-without-a-plc-runtime)
1069
+
1070
+ ### Connection failed (error EADDRNOTAVAIL)
1071
+ This could happen if you have manually provided `localAddress` or `localTcpPort` that don't exist.
1072
+ For example, setting `localAddress` to `192.168.10.1` when the computer has only ethernet interface with IP `192.168.1.1`.
1073
+
1074
+ See also https://github.com/jisotalo/ads-client/issues/82
1075
+
1076
+ ### Problems running ads-client with docker
1077
+
1078
+ - EADDRNOTAVAIL: See above and https://github.com/jisotalo/ads-client/issues/82
1079
+
1080
+ ### How to connect to PLC that is in CONFIG mode?
1081
+ As default, the ads-client checks if the target has PLC runtime at given port. However, when target system manager is at config mode, there is none. The client will throw an error during connecting:
1082
+
1083
+ `Connection failed - failed to set PLC connection. If target is not PLC runtime, use setting "rawClient". If system is in config mode or there is no PLC software yet, you might want to use setting "allowHalfOpen"`
1084
+
1085
+ You can disable the check by providing setting `allowHalfOpen: true`. After that, it's possible to start the PLC by `setTcSystemToRun()`.
1086
+
1087
+ Another option is to use setting `rawClient: true` - see [Connecting to targets without a PLC runtime](#connecting-to-targets-without-a-plc-runtime).
1088
+
1089
+ ### Issues with TwinCAT 2 low-end devices (BK9050, BC9050 etc.)
1090
+ * You can only use raw commands (such as `readRaw()`, `writeRaw()`, `subscribeRaw()`) as these devices provide no symbols
1091
+ * See [issue 114](https://github.com/jisotalo/ads-client/issues/114) and [issue 116](https://github.com/jisotalo/ads-client/issues/116)
1092
+
1093
+
1094
+
1095
+ ## External links
1096
+
1097
+ README in progress.
114
1098
 
115
1099
  ## Library testing
116
1100
 
117
- Target is that library has tests for all its features, see `./test/` directory.
1101
+ All features of this library are tested using quite large test suite - see `./test/` directory.
118
1102
  This prevents regression, thus updating the ads-client should be always safe.
119
1103
 
1104
+ There are separate tests for TwinCAT 2 and TwinCAT 3.
1105
+
120
1106
  PLC projects for running test suites are located in the following repository:
121
1107
  [https://github.com/jisotalo/ads-client-test-plc-project/tree/v2-dev](https://github.com/jisotalo/ads-client-test-plc-project/tree/v2-dev).
122
1108