ads-client 1.14.2 → 2.0.0-beta.1

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
@@ -2,1785 +2,346 @@
2
2
 
3
3
 
4
4
  [![npm version](https://img.shields.io/npm/v/ads-client)](https://www.npmjs.org/package/ads-client)
5
- [![Donate](https://img.shields.io/badge/Donate-PayPal-yellow)](https://www.paypal.com/donate/?business=KUWBXXCVGZZME&no_recurring=0&currency_code=EUR)
6
5
  [![GitHub](https://img.shields.io/badge/View%20on-GitHub-brightgreen)](https://github.com/jisotalo/ads-client)
7
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)
8
8
 
9
- Beckhoff TwinCAT ADS client library for Node.js (unofficial). Connects to Beckhoff TwinCAT automation systems using ADS protocol.
10
-
11
- Coded from scratch using [TwinCAT ADS specification](https://infosys.beckhoff.com/content/1033/tc3_ads_intro/116157835.html?id=124964102706356243) and [Beckhoff.TwinCAT.Ads nuget package](https://www.nuget.org/packages/Beckhoff.TwinCAT.Ads/5.0.0-preview6). Inspiration from similar projects like [node-ads](https://www.npmjs.com/package/node-ads), [beckhoff-js](https://www.npmjs.com/package/beckhoff-js) and [iecstruct](https://www.npmjs.com/package/iecstruct).
12
-
13
- There is automatically created documentation available at https://jisotalo.github.io/ads-client/
14
-
15
- # Project status
16
- This project is currently "ready". It's maintained actively and used in projects by the author and others (also lot's of commercial projects)
17
-
18
- Bugs are fixed if found and new features can be added. Please let me know if you have any ideas!
19
-
20
- And if you want you can buy me a beer using PayPal :)
21
-
22
- [![Donate](https://img.shields.io/badge/Donate%20a%20beer!-PayPal-yellow)](https://www.paypal.com/donate/?business=KUWBXXCVGZZME&no_recurring=0&currency_code=EUR)
23
-
24
-
25
- # Using Node-RED?
26
- Check out the [node-red-contrib-ads-client](https://www.npmjs.com/package/node-red-contrib-ads-client) package. It's an `ads-client` wrapper for Node-RED to get the same functionality.
27
-
28
-
29
- # Table of contents
30
- - [Installation](#installation)
31
- - [Features](#features)
32
- - [Supported and tested platforms](#supported-and-tested-platforms)
33
- - [Connection setups and possibilities](#connection-setups-and-possibilities)
34
- - [Enabling localhost support on TwinCAT 3](#enabling-localhost-support-on-twincat-3)
35
- - [IMPORTANT: Writing STRUCT variables](#important-writing-struct-variables)
36
- - [IMPORTANT: Things to know when using with TwinCAT 2](#important-things-to-know-when-using-with-twincat-2)
37
- - [Connecting to systems without PLC runtime](#connecting-to-systems-without-plc-runtime)
38
- - [Getting started](#getting-started)
39
- * [Data types used in getting started](#data-types-used-in-getting-started)
40
- * [Creating a new Client instance](#creating-a-new-client-instance)
41
- * [Available settings](#available-settings)
42
- * [Connecting and disconnecting](#connecting-and-disconnecting)
43
- * [Reading any type PLC variable](#reading-any-type-plc-variable)
44
- + [Example: Reading `INT` type variable](#example-reading-int-type-variable)
45
- + [Example: Reading `STRING` type variable](#example-reading-string-type-variable)
46
- + [Example: Reading `ENUM` type variable](#example-reading-enum-type-variable)
47
- + [Example: Reading `STRUCT` type variable](#example-reading-struct-type-variable)
48
- + [Example: Reading `ARRAY OF INT` type variable](#example-reading-array-of-int-type-variable)
49
- + [Example: Reading `ARRAY OF STRUCT` type variable](#example-reading-array-of-struct-type-variable)
50
- + [Example: Reading `FUNCTION BLOCK` type variable](#example-reading-function-block-type-variable)
51
- * [Writing any type PLC variable](#writing-any-type-plc-variable)
52
- + [Example: Writing `INT` type variable](#example-writing-int-type-variable)
53
- + [Example: Writing `STRING` type variable](#example-writing-string-type-variable)
54
- + [Example: Writing `ENUM` type variable](#example-writing-enum-type-variable)
55
- + [Example: Writing `STRUCT` type variable](#example-writing-struct-type-variable)
56
- + [Example: Writing `STRUCT` type variable (with autoFill parameter)](#example-writing-struct-type-variable-with-autofill-parameter-)
57
- + [Example: Writing `ARRAY OF INT` type variable](#example-writing-array-of-int-type-variable)
58
- + [Example: Writing `ARRAY of STRUCT` type variable](#example-writing-array-of-struct-type-variable)
59
- + [Example: Writing `FUNCTION BLOCK` type variable](#example-writing-function-block-type-variable)
60
- * [Subscribing to PLC variables (device notifications)](#subscribing-to-plc-variables-device-notifications-)
61
- + [Subcribe to variable value (on-change)](#subcribe-to-variable-value-on-change-)
62
- + [Subcribe to variable value (cyclic)](#subcribe-to-variable-value-cyclic-)
63
- * [Reading and writing raw data](#reading-and-writing-raw-data)
64
- + [Getting symbol index group, offset and size](#getting-symbol-index-group-offset-and-size)
65
- + [Reading a single raw value](#reading-a-single-raw-value)
66
- + [Writing a single raw value](#writing-a-single-raw-value)
67
- + [Reading multiple raw values](#reading-multiple-raw-values)
68
- + [Writing multiple raw values](#writing-multiple-raw-values)
69
- + [Creating a variable handle and reading a raw value](#creating-a-variable-handle-and-reading-a-raw-value)
70
- + [Creating a variable handle and writing a raw value](#creating-a-variable-handle-and-writing-a-raw-value)
71
- + [Creating and deleting multiple variable handles](#creating-and-deleting-multiple-variable-handles)
72
- + [Converting a raw value to Javascript object](#converting-a-raw-value-to-javascript-object)
73
- + [Converting a Javascript object to raw value](#converting-a-javascript-object-to-raw-value)
74
- * [Reading and writing `POINTER TO` and `REFERENCE TO` variables](#reading-and-writing-pointer-to-and-reference-to-variables)
75
- + [Reading a `REFERENCE TO` value](#reading-a-reference-to-value)
76
- + [Writing a `REFERENCE TO` value](#writing-a-reference-to-value)
77
- + [Reading a `POINTER TO` value](#reading-a-pointer-to-value)
78
- + [Writing a `POINTER TO` value](#writing-a-pointer-to-value)
79
- * [Calling a function block method with parameters using RPC (remote procedure call)](#calling-a-function-block-method-with-parameters-using-rpc-remote-procedure-call-)
80
- + [Calling a simple RPC method](#calling-a-simple-rpc-method)
81
- + [Using structs with RPC methods](#using-structs-with-rpc-methods)
82
- * [Starting and stopping the PLC](#starting-and-stopping-the-plc)
83
- * [Starting and stopping the TwinCAT system](#starting-and-stopping-the-twincat-system)
84
- * [Sending custom ADS commands](#sending-custom-ads-commands)
85
- - [Available ads-client events](#available-ads-client-events)
86
- * [Example: Printing to console when PLC runtime state changes:](#example-printing-to-console-when-plc-runtime-state-changes-)
87
- * [Example: Catching an error that is not directly from a method call](#example-catching-an-error-that-is-not-directly-from-a-method-call)
88
- - [Debugging](#debugging)
89
- * [Enabling debug from code](#enabling-debug-from-code)
90
- * [Enabling debugging from terminal](#enabling-debugging-from-terminal)
91
- - [FAQ](#faq)
92
- - [Automatic testing](#automatic-testing)
93
- - [Documentation](#documentation)
94
- - [License](#license)
95
-
96
-
97
- # Installation
98
-
99
- Install the [npm package](https://www.npmjs.com/package/ads-client) using npm command:
100
- ```bash
101
- npm i ads-client
102
- ```
103
-
104
- Include the module in your code
105
- ```js
106
- const ads = require('ads-client')
107
- ```
108
- # Features
109
-
110
- - TwinCAT 2 and TwinCAT 3 support
111
- - Promise and async/await support
112
- - Supports connecting to the local TwinCAT 3 runtime (see [enabling localhost support](#localhost-support))
113
- - Supports multiple connections from the same host
114
- - Reading and writing all any PLC variable
115
- - Subscribing to PLC variables (ADS notifications)
116
- - Automatic conversion between PLC<->Javascript objects
117
- - PLC symbol and data type handling and caching
118
- - Reading PLC runtime and system manager states
119
- - Automatic 32/64 bit variable support (PVOID, XINT, etc.)
120
- - Automatic cache and subscription refreshing when PLC program changes or system starts
121
- - Automatic byte alignment support (all pack-modes automatically supported)
122
- - **From version 1.6.0 upwards**
123
- - Older versions: `{attribute 'pack_mode' := '1'}` is required above STRUCT definition
124
- - Possibility to call function block methods (RPC - remote procedure call)
125
- - **From version 1.8.0 upwards**
126
-
127
-
128
- # Supported and tested platforms
129
-
130
- The ads-client package is tested so far with the following setups:
131
- - TwinCAT 2.11 running on VirtualBox Windows XP 32bit **(from version 1.9.0 upwards)**
132
- - TwinCAT 2 support not tested with hardware PLC yet but should work
133
- - TwinCAT 3 4020 running on 64bit Windows 10 **(TC3 builds <= 4020 are working from version 1.9.0 upwards)**
134
- - TwinCAT 3 4022.27 running on 64bit Windows 10
135
- - TwinCAT 3 4024.4 running on 64bit Windows 10
136
- - TwinCAT 3 4022.27 running on 32bit and 64bit Windows 7 Embedded on Beckhoff PLC
137
- - TwinCAT 3 4024.12 running on 64bit Windows 7 Embedded on Beckhoff PLC
138
- - Node.js v10.16.3 and newer
139
- - NOTE: 64 bit integer values are supported only with Node.js v.12+
140
-
141
- Tested on the following operating systems / platforms
142
- - Windows 7 and 10
143
- - Raspberry Pi 4
144
- - OSX Catalina
145
-
146
-
147
- # Connection setups and possibilities
148
-
149
- The ads-client can be used in different system configurations. The following figure has different possible setups:
150
-
151
- [![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)
152
-
153
- ## Setup 1 - Connect from Windows PC to the PLC
154
-
155
- Suggested use cases:
156
- - When using Windows operating system and TwinCAT runtime can be installed
157
- - When opening a TCP port from PLC is a no-go
158
-
159
- Requirements:
160
- - Client has TwinCAT runtime or XAE installed
161
- - ADS route is created between the client and the PLC
162
-
163
-
164
- Example connection to PLC with AmsNetId of `192.168.1.120.1.1`.
165
- ```js
166
- const client = new ads.Client({
167
- targetAmsNetId: '192.168.1.120.1.1',
168
- targetAdsPort: 851,
169
- })
170
- ```
171
-
172
- ## Setup 2 - Connecting from Unix/Windows/etc. system to the PLC
173
-
174
- Suggested use cases:
175
- - On Windows when TwinCAT installation is not possible, but .NET Core is available
176
- - Unix based system and .NET Core available
177
-
178
- Requirements:
179
- - Client has [AdsRouterConsole](https://www.nuget.org/packages/Beckhoff.TwinCAT.Ads.AdsRouterConsole/5.0.0-preview4) running
180
- - ADS route is created between the client and the PLC (as in the nuget package instructions)
181
-
182
- Example connection when PLC has AmsNetId of `192.168.1.120.1.1`.
183
- ```js
184
- const client = new ads.Client({
185
- targetAmsNetId: '192.168.1.120.1.1',
186
- targetAdsPort: 851,
187
- })
188
- ```
189
-
190
-
191
-
192
- ## Setup 3 - Connecting from any Node.js supported system to the PLC
193
-
194
- Suggested use cases:
195
- - When opening TCP port from PLC is possible
196
- - When fast connection is required (1 router less -> faster response)
197
-
198
- Requirements:
199
- - NOTE: Only one connection / client is possible!
200
- - PLC has TCP port 48898 open (default router port)
201
- - NOTE: Windows Firewall might block, make sure Ethernet connection is handled as "private"
202
- - Local AmsNetId and ADS port are given manually
203
- - Given `localAmsNetId` is not already in use
204
- - Given `localAdsPort` is not already in use
205
- - PLC has ADS route manually created to client IP address and client `localAmsNetId`
206
- - See example after code sample
207
-
208
- Example connection when PLC has AmsNetId of `192.168.1.120.1.1` and IP of `192.168.1.120`.
209
- ```js
210
- const client = new ads.Client({
211
- localAmsNetId: '192.168.1.10.1.1', //Can be anything but needs to be in PLC StaticRoutes.xml file
212
- localAdsPort: 32750, //Can be anything that is not used
213
- targetAmsNetId: '192.168.1.120.1.1',
214
- targetAdsPort: 851,
215
- routerAddress: '192.168.1.120', //PLC ip address
216
- routerTcpPort: 48898 //PLC needs to have this port opened. Test disabling all firewalls if problems
217
- })
218
- ```
219
-
220
- Adding a route to the PLC can be done editing `TwinCAT\3.1\Target\StaticRoutes.xml` file from PLC. Add the following inside `<RemoteConnections>` tag. In this example, client should use meanual AmsNetId `192.168.1.10.1.1` and client has IP address `192.168.1.10`.
221
- ```xml
222
- <Route>
223
- <Name>UI</Name>
224
- <Address>192.168.1.10</Address>
225
- <NetId>192.168.1.10.1.1</NetId>
226
- <Type>TCP_IP</Type>
227
- <Flags>64</Flags>
228
- </Route>
229
- ```
230
-
231
- See also [this issue comment](https://github.com/jisotalo/ads-client/issues/51#issuecomment-758016428) by hansipete for one possible way how to do adding the route.
232
-
233
- ## Setup 4 - Connect to the localhost (PLC and client on the same machine)
234
-
235
- Suggested use cases:
236
- - When testing PLC systems on the local computer
237
- - When using panel PC/PLC combination
238
- - When PLC has monitor and it's used as user interface
239
-
240
-
241
- Requirements:
242
- - AMS router TCP loopback enabled (see [Enabling localhost support](#enabling-localhost-support))
243
-
244
- Example connection to local PLC runtime
245
-
246
- ```js
247
- const client = new ads.Client({
248
- targetAmsNetId: '127.0.0.1.1.1', //or 'localhost'
249
- targetAdsPort: 851,
250
- })
251
-
252
- ```
253
-
254
-
255
- # Enabling localhost support on TwinCAT 3
256
- *NOTE: Only required for TwinCAT 3 versions older than 4024.5. Newer versions should have this already enabled.*
257
-
258
- ***Note:** Probably not working for TwinCAT 2*
259
-
260
- If you want to connect to the local TwinCAT runtime (Node.js and the TwinCAT on the same computer - **as example setup 4**), the ADS router TCP loopback feature has to be enabled. Tested with TwinCAT 4022.27 and 4024.4.
9
+ Beckhoff TwinCAT ADS client library for Node.js (unofficial).
261
10
 
262
- The following method is from [Beckhoff.TwinCAT.Ads nuget package](https://www.nuget.org/packages/Beckhoff.TwinCAT.Ads/5.0.0-preview6) installation guide.
11
+ Connect to a Beckhoff TwinCAT automation system using the ADS protocol from a Node.js app.
263
12
 
264
- 1. Stop TwinCAT System Service
13
+ ## v2 project status
265
14
 
266
- 2. Open registery editor (`regedit`)
15
+ **24.08.2024:** Beta 1 released!
267
16
 
268
- 3. Depending on the operating system, navigate to
269
- ```
270
- 32 bit operating system:
271
- HKEY_LOCAL_MACHINE\SOFTWARE\Beckhoff\TwinCAT3\System\
272
-
273
- 64 bit it operating system:
274
- HKEY_LOCAL_MACHINE\SOFTWARE\WOW6432Node\Beckhoff\TwinCAT3\System\
275
- ```
276
-
277
- 4. Create new DWORD registery named `EnableAmsTcpLoopback` and set value to 1 (example figure below from 64 bit system)
278
-
279
- ![ads-client-tcp-loopback](https://user-images.githubusercontent.com/13457157/82748398-2640bf00-9daa-11ea-98e5-0032b3537969.png)
280
-
281
- 5. Restart TwinCAT system
282
-
283
- Now you can connect to the localhost using `targetAmsNetId` address of `127.0.0.1.1.1` or `localhost`.
284
-
285
- # IMPORTANT: Writing STRUCT variables
286
-
287
- When writing a struct using `writeSymbol`, the given Javascript object keys are handled as case-insensitive because the TwinCAT 3 system is case-insensitive.
288
-
289
- In practise this means that the following Javascript objects are used as-equals if passing to the `writeSymbol` method:
290
-
291
- ```js
292
- {
293
- sometext: 'hello',
294
- somereal: 3.14
295
- }
296
- ```
297
-
298
- ```js
299
- {
300
- SOmeTEXT: 'hello',
301
- SOMEreal: 3.14
302
- }
303
- ```
304
-
305
- **NOTE** If the object has multiple keys with same name, `writeSymbol` tries to find the same case as in PLC. If it's not found, it depends on the `Object.find()` method which one is selected.
306
-
307
- ```js
308
- //In this case, probably the first one (sometext) is selected and the SOMEtext is skipped.
309
- {
310
- sometext: 'hello',
311
- SOMEtext: 'good day'
312
- }
313
- ```
314
-
315
-
316
- # IMPORTANT: Things to know when using with TwinCAT 2
317
-
318
- Almost everything should work with TwinCAT 2 but please understand the following
319
-
320
- ## TwinCAT 2 first PLC runtime ADS port is 801 instead of 851
321
-
322
- ```js
323
- const client = new ads.Client({
324
- targetAmsNetId: '...',
325
- targetAdsPort: 801, //NOTE
326
- })
327
- ```
328
-
329
- ## Variable names are returned in UPPERCASE on TC2 systems
330
- This might cause problems if your app is used with both TC2 & TC3 systems.
331
-
332
- ![image](https://user-images.githubusercontent.com/13457157/86540055-96df0d80-bf0a-11ea-8f94-7e04515213c2.png)
333
-
334
- ## Global variable paths are given different on TC2
335
-
336
- The GVL name is not given, dot (.) is used instead.
337
-
338
- ```js
339
- await client.readSymbol('GVL_Test.ExampleSTRUCT') //TwinCAT 3
340
- await client.readSymbol('.ExampleSTRUCT') //TwinCAT 2
341
- ```
342
-
343
- ## InvokeRpcMethod is not possible on TC2
344
- This is the only one non-working feature as there are no methods in TC2.
345
-
346
-
347
- # Connecting to systems without PLC runtime
348
-
349
- Since version 1.13.0 it's possible to connect to systems without PLC runtime and/or system manager using `ads-client`.
350
-
351
- In previous versions, the client always checked the system state (RUN, CONFIG). However when connecting to different systems (non-PLC systems), there might be no system manager service. With default configuration this causes an error:
352
- ```
353
- ClientException: Connection failed: Device system manager state read failed
354
- ```
355
-
356
- By providing `bareClient` setting, the client connects to the router or target and nothing else. After that, the client can be used to read/write data. However, connection losses etc. need to be handled by the user.
357
-
358
-
359
- ```js
360
- const client = new ads.Client({
361
- targetAmsNetId: '192.168.5.131.3.1',
362
- targetAdsPort: 1002,
363
- bareClient: true //NOTE
364
- })
365
- ```
366
-
367
- # Getting started
368
-
369
- This chapter includes some short getting started examples. See the JSDoc [documentation](#documentation) for detailed description of library classes and methods.
17
+ All breaking changes are (hopefully) now done.
370
18
 
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
+ * See [CHANGELOG.md](https://github.com/jisotalo/ads-client/blob/v2-dev/CHANGELOG.md) for some more changes
22
+ * Clone repository and open `docs/index.html` in browser for documentation
371
23
 
372
- ## Data types used in getting started
373
-
374
- These examples assume that the PLC has the following Global Variable List (GVL):
375
- ```
376
- //GVL_Test
377
- VAR_GLOBAL
378
- TestINT : INT := 1234;
379
- TestSTRING : STRING := 'Hello this is a test string';
380
- ExampleSTRUCT : ST_Example;
381
- TestARRAY : ARRAY[0..4] OF INT := [0, 10, 200, 3000, 4000];
382
- TestARRAY2 : ARRAY[0..4] OF ST_Example := [(SomeText := 'Just for demo purposes')];
383
- TestENUM : E_TestEnum := E_TestEnum.Running;
384
- IncrementingValue : INT; //This should change every 500 ms or so
385
- TestTimer : TON := (PT := T#2S500MS);
386
- END_VAR
387
- ```
388
-
389
- The `ST_Example` should be defined as below:
390
- ```
391
- TYPE ST_Example :
392
- STRUCT
393
- SomeText : STRING(50) := 'Hello ads-client';
394
- SomeReal : REAL := 3.14159265359;
395
- SomeDate : DT := DT#2020-4-13-12:25:33;
396
- END_STRUCT
397
- END_TYPE
398
- ```
399
-
400
- The `E_TestEnum` should be defined as below:
401
- ```
402
- TYPE E_TestEnum :
403
- (
404
- Disabled := 0,
405
- Starting := 50,
406
- Running := 100,
407
- Stopping := 200
408
- );
409
- END_TYPE
410
- ```
411
-
412
- ## Creating a new Client instance
413
-
414
- The constructor takes settings as its parameter. Two settings are mandatory: `targetAmsNetId` and `targetAdsPort`. The first is the target PLC system AmsNetId (like *127.0.0.1.1.1* or *192.168.1.10.1.1*) and the latter is target system ADS port (*like 851 for TwinCAT 3 runtime 1*).
415
-
416
- ```js
417
- const ads = require('ads-client')
418
-
419
- //Creates a new Client instance and sets the local system and TC3 runtime 1 as target
420
- const client = new ads.Client({
421
- targetAmsNetId: '127.0.0.1.1.1', //Loopback address, same as 'localhost' since version 1.1.0
422
- targetAdsPort: 851,
423
- })
424
- ```
425
- ### Available settings
426
- **REQUIRED:**
427
- * `targetAmsNetId`
428
- * Target system AmsNetId
429
- * Use `127.0.0.1.1.1` or `localhost` if connecting to a local system
430
- * `targetAdsPort`
431
- * Target system ADS port.
432
- * TwinCAT 3: 851 (1st runtime), 852 (2nd runtime) and so on
433
- * TwinCAT 2: 801 (1st runtime)
434
-
435
- **Optional:**
436
- * `objectifyEnumerations`
437
- * Default value: `true`
438
- * If true, read ENUM data types are converted to objects instead of numbers, e.g. `{name: 'enumValue', value: 5}` instead of 5
439
- * `convertDatesToJavascript`
440
- * Default value: `true`
441
- * If true, PLC DT (DATE_AND_TIME) and DATE types are converted to Javascript dates
442
- * `readAndCacheSymbols`
443
- * Default value: `false`
444
- * If true, **all** PLC symbols are cached during connecting. Otherwise they are read and cached only when needed
445
- * `readAndCacheDataTypes`
446
- * Default value: `false`
447
- * If true, **all** PLC data types are cached during connecting. Otherwise they are read and cached only when needed
448
- * `disableSymbolVersionMonitoring`
449
- * Default value: `false`
450
- * If true, PLC symbol version changes aren't monitored and cached symbols and datatypes won't be updated after PLC program download
451
- * `routerTcpPort`
452
- * Default value: `48898`
453
- * Target ADS router TCP port
454
- * `routerAddress`
455
- * Default value: `localhost`
456
- * Target ADS router IP address/hostname
457
- * `localAddress`
458
- * Default value: `system default`
459
- * Local IP address to use, use this to change used network interface if required
460
- * `localTcpPort`
461
- * Default value: `system default`
462
- * Local TCP port to use for outgoing connections
463
- * `localAmsNetId`
464
- * Default value: `AMS router provides`
465
- * Local AmsNetId to use
466
- * Used especially when connecting from systems without own AMS router, like Raspberry Pi
467
- * See: [Connecting from any Node.js supported system to the PLC](#setup-3---connecting-from-any-nodejs-supported-system-to-the-plc)
468
- * `localAdsPort`
469
- * Default value: `AMS router provides`
470
- * Local ADS port to use
471
- * Used especially when connecting from systems without own AMS router, like Raspberry Pi
472
- * See: [Connecting from any Node.js supported system to the PLC](#setup-3---connecting-from-any-nodejs-supported-system-to-the-plc)
473
- * `timeoutDelay`
474
- * Default value: `2000`
475
- * Time (milliseconds) after connecting to the router or waiting for command response is canceled to a timeout
476
- * `hideConsoleWarnings`
477
- * Default value: `false`
478
- * If true, no warnings are written to console (=nothing is **ever** written to console)
479
- * `autoReconnect`
480
- * Default value: `true`
481
- * If true and connection is lost, the client tries to reconnect automatically
482
- * `reconnectInterval`
483
- * Default value: `2000`
484
- * Time (milliseconds) how often the lost connection is tried to re-establish
485
- * `checkStateInterval`
486
- * Default value: `1000`
487
- * Time (milliseconds) how often the system manager state is read to see if connection is OK
488
- * `connectionDownDelay`
489
- * Default value: `5000`
490
- * Time (milliseconds) after no successful reading of the system manager state the connection is determined to be lost
491
- * `allowHalfOpen`
492
- * Default value: `false`
493
- * If true, connect() is successful even if no PLC runtime is found (but target and system manager are available) - Can be useful if it's ok that after connecting the PLC runtime is not immediately available (example: connecting before uploading PLC code and reading data later) -
494
- * WARNING: If true, reinitializing subscriptions might fail after connection loss.
495
- * `disableBigInt`
496
- * Default value: `false`
497
- * If true, 64-bit integer PLC variables are kept as `Buffer` objects instead of converting to Javascript `BigInt` variables (JSON.strigify and libraries that use it have no BigInt support)
498
- * `bareClient`
499
- * Default value: `false`
500
- * If true, only direct ads connection is established (no system manager)
501
- * Can be used to connect to systems without PLC runtime
502
- * See [Connecting to systems without PLC runtime](#connecting-to-systems-without-plc-runtime)
24
+ ## Getting started
503
25
 
26
+ README is under construction.
504
27
 
505
- ## Connecting and disconnecting
28
+ ### Install
29
+ `npm install ads-client@beta`
506
30
 
507
- Connecting to the local TwinCAT 3 runtime 1 (port is 851) using local ADS router (= you have TwinCAT ADS router installed).
31
+ ### Create a client
508
32
 
509
33
  ```js
510
- const ads = require('ads-client')
34
+ const { Client } = require('ads-client');
511
35
 
512
- const client = new ads.Client({
513
- targetAmsNetId: '127.0.0.1.1.1',
36
+ const client = new Client({
37
+ targetAmsNetId: "localhost",
514
38
  targetAdsPort: 851
515
- })
516
-
517
- client.connect()
518
- .then(res => {
519
- console.log(`Connected to the ${res.targetAmsNetId}`)
520
- console.log(`Router assigned us AmsNetId ${res.localAmsNetId} and port ${res.localAdsPort}`)
521
-
522
- return client.disconnect()
523
- })
524
- .then(() => {
525
- console.log('Disconnected')
526
- })
527
- .catch(err => {
528
- console.log('Something failed:', err)
529
- })
530
-
531
- /*
532
- Example console output:
533
-
534
- Connected to the 127.0.0.1.1.1
535
- Router assigned us AmsNetId 192.168.1.1.1.1 and port 36837
536
- Disconnected
537
- */
538
- ```
539
-
540
-
541
- ## Reading any type PLC variable
542
-
543
- Using `readSymbol` method it is possible to read variables of **any type** from the PLC (except references and pointers). These include base scalar type variables, structs, function blocks, arrays and so on. These examples cover just a few cases.
544
-
545
- See full `readSymbol` documentation [from the docs](https://jisotalo.github.io/ads-client/Client.html#readSymbol).
546
-
547
- For references and pointers see chapter [Reading and writing POINTER TO and REFERENCE TO variables](#reading-and-writing-pointer-to-and-reference-to-variables).
548
-
549
- ### Example: Reading `INT` type variable
550
- ```js
551
- //Using Promises
552
- client.readSymbol('GVL_Test.TestSTRING')
553
- .then(res => {
554
- console.log(`Value read: ${res.value}`)
555
- })
556
- .catch(err => {
557
- console.log('Something failed:', err)
558
- })
559
-
560
- /*
561
- Example console output:
562
-
563
- Value read: 1234
564
- */
565
- ```
566
-
567
- ---
568
-
569
- ### Example: Reading `STRING` type variable
570
- ```js
571
- client.readSymbol('GVL_Test.TestSTRING')
572
- .then(res => {
573
- console.log(`Value read: ${res.value}`)
574
- })
575
- .catch(err => {
576
- console.log('Something failed:', err)
577
- })
578
- /*
579
- Example console output:
580
-
581
- Value read: Hello this is a test string
582
- */
583
- ```
584
-
585
- ---
586
-
587
-
588
-
589
- ### Example: Reading `ENUM` type variable
590
-
591
- If setting `objectifyEnumerations` is set to false, only ENUM value (number) is returned. As default, both string representation and integer value are returned.
592
-
593
- ```js
594
- //objectifyEnumerations: true
595
- client.readSymbol('GVL_Test.TestENUM')
596
- .then(res => {
597
- console.log(`Value read: ${res.value}`)
598
- })
599
- .catch(err => {
600
- console.log('Something failed:', err)
601
- })
602
-
603
- /*
604
- Example console output:
605
-
606
- Value read: { name: 'Running', value: 100 }
607
- */
608
- ```
609
-
610
- ---
611
-
612
-
613
- ### Example: Reading `STRUCT` type variable
614
-
615
-
616
- ```js
617
- //Using await for example purposes
618
- try {
619
- const res = await client.readSymbol('GVL_Test.ExampleSTRUCT')
620
-
621
- console.log('Value read:', res.value)
622
- } catch (err) {
623
- console.log('Reading failed:', err)
624
- }
625
-
626
- /*
627
- Example console output:
628
-
629
- Value read: { SomeText: 'Hello ads-client',
630
- SomeReal: 3.1415927410125732,
631
- SomeDate: 2020-04-13T12:25:33.000Z }
632
- */
633
- ```
634
-
635
- ---
636
-
637
-
638
-
639
- ### Example: Reading `ARRAY OF INT` type variable
640
-
641
-
642
- ```js
643
- try {
644
- const res = await client.readSymbol('GVL_Test.TestARRAY')
645
-
646
- console.log('Value read:', res.value)
647
- } catch (err) {
648
- console.log('Reading failed:', err)
649
- }
650
-
651
- /*
652
- Example console output:
653
-
654
- Value read: [ 0, 10, 200, 3000, 4000 ]
655
- */
656
- ```
657
-
658
- ---
659
-
660
- ### Example: Reading `ARRAY OF STRUCT` type variable
661
-
662
- ```javascript
663
- try {
664
- const res = await client.readSymbol('GVL_Test.TestARRAY2')
665
-
666
- console.log('Value read:', res.value)
667
- } catch (err) {
668
- console.log('Reading failed:', err)
669
- }
670
-
671
- /*
672
- Example console output:
673
-
674
- Value read: [ { SomeText: 'Just for demo purposes',
675
- SomeReal: 3.1415927410125732,
676
- SomeDate: 2020-04-13T12:25:33.000Z },
677
- { SomeText: 'Hello ads-client',
678
- SomeReal: 3.1415927410125732,
679
- SomeDate: 2020-04-13T12:25:33.000Z },
680
- { SomeText: 'Hello ads-client',
681
- SomeReal: 3.1415927410125732,
682
- SomeDate: 2020-04-13T12:25:33.000Z },
683
- { SomeText: 'Hello ads-client',
684
- SomeReal: 3.1415927410125732,
685
- SomeDate: 2020-04-13T12:25:33.000Z },
686
- { SomeText: 'Hello ads-client',
687
- SomeReal: 3.1415927410125732,
688
- SomeDate: 2020-04-13T12:25:33.000Z } ]
689
- */
690
- ```
691
-
692
-
693
- ----
694
-
695
- ### Example: Reading `FUNCTION BLOCK` type variable
696
-
697
- Example of reading `TON` timer function block.
698
-
699
- ```javascript
700
- try {
701
- const res = await client.readSymbol('GVL_Test.TestTimer')
702
-
703
- console.log('Value read:', res.value)
704
- } catch (err) {
705
- console.log('Reading failed:', err)
706
- }
707
-
708
- /*
709
- Example console output:
710
-
711
- Value read: { IN: false, PT: 2500, Q: false, ET: 0, M: false, StartTime: 0 }
712
- */
713
- ```
714
-
715
-
716
- ----
717
-
718
-
719
- ## Writing any type PLC variable
720
-
721
- Using `writeSymbol` method it is possible to write variables of **any type** to the PLC (except references and pointers). These include base scalar type variables, structs, function blocks, arrays and so on. These examples cover just a few cases.
722
-
723
- See full `writeSymbol` documentation [from the docs](https://jisotalo.github.io/ads-client/Client.html#writeSymbol).
724
-
725
- For references and pointers see chapter [Reading and writing POINTER TO and REFERENCE TO variables](#reading-and-writing-pointer-to-and-reference-to-variables).
726
-
727
- ---
728
-
729
- ### Example: Writing `INT` type variable
730
-
731
-
732
- ```js
733
- try {
734
- const res = await client.writeSymbol('GVL_Test.TestINT', 5)
735
-
736
- console.log('Value written:', res.value)
737
- } catch (err) {
738
- console.log('Something failed:', err)
739
- }
740
- ```
741
-
742
- ---
743
-
744
- ### Example: Writing `STRING` type variable
745
-
746
- ```js
747
-
748
- try {
749
- const res = await client.writeSymbol('GVL_Test.TestSTRING', 'Changing the string value to this')
750
-
751
- console.log('Value written:', res.value)
752
- } catch (err) {
753
- console.log('Something failed:', err)
754
- }
755
- ```
756
-
757
-
758
- ---
759
-
760
- ### Example: Writing `ENUM` type variable
761
-
762
- When writing `ENUM` value, it can always be given as number or string.
763
-
764
-
765
- ```js
766
- try {
767
- const res = await client.writeSymbol('GVL_Test.TestENUM', 'Starting')
768
- //The following does the same:
769
- //const res = await client.writeSymbol('GVL_Test.TestENUM', 50)
770
-
771
- console.log('Value written:', res.value)
772
- } catch (err) {
773
- console.log('Something failed:', err)
774
- }
775
- ```
776
-
777
- ---
778
- ### Example: Writing `STRUCT` type variable
779
-
780
- ```js
781
- try {
782
- const res = await client.writeSymbol('GVL_Test.ExampleSTRUCT', {
783
- SomeText: 'Hello to you too, Mr. PLC!',
784
- SomeReal: 5456.06854,
785
- SomeDate: new Date()
786
- })
787
-
788
- console.log('Value written:', res.value)
789
- } catch (err) {
790
- console.log('Something failed:', err)
791
- }
792
- ```
793
-
794
-
795
- ### Example: Writing `STRUCT` type variable (with autoFill parameter)
796
-
797
- ---
798
-
799
- The following code will not work. The PLC struct has three members but we provide only two, which causes an exception.
800
-
801
-
802
- ```js
803
- //NOTE: This won't work
804
- try {
805
- const res = await client.writeSymbol('GVL_Test.ExampleSTRUCT', {
806
- SomeReal: 123.45,
807
- SomeText: 'This will not work...'
808
- })
809
-
810
- } catch (err) {
811
- console.log('Something failed:', err)
812
- }
813
-
814
- /*
815
- Example console output
816
-
817
- Something failed: { ClientException: Writing symbol GVL_Test.ExampleSTRUCT failed: Given Javascript object is missing key/value for at least ".SomeDate" (DATE_AND_TIME) - Set writeSymbol() 3rd parameter (autoFill) to true to allow uncomplete objects
818
- at Promise ...
819
- */
820
- ```
821
-
822
- We need to tell the `WriteSymbol` that we **indeed** want to write just some members and the rest will stay the same. This happens by setting the 3rd parameter `autoFill` to true.
823
-
824
- If `autoFill` is true, the method first reads the latest value and then writes it with only the new given changes.
825
-
826
- ```js
827
- try {
828
- const res = await client.writeSymbol('GVL_Test.ExampleSTRUCT', {
829
- SomeReal: 123.45,
830
- SomeText: 'But this works!'
831
- }, true) //Note this!
832
-
833
- console.log('Value written:', res.value)
834
-
835
- } catch (err) {
836
- console.log('Something failed:', err)
837
- }
39
+ });
838
40
  ```
839
41
 
42
+ ### Read a value
840
43
 
841
- Of course, it would be possible to do with two separate commands too:
842
44
  ```js
843
- res = await client.writeSymbol('GVL_Test.ExampleSTRUCT.SomeReal', 123.45)
844
- res = await client.writeSymbol('GVL_Test.ExampleSTRUCT.SomeText', 'This is also possible')
45
+ const res = await client.readValue('GVL_Example.StringValue');
46
+ console.log(res.value);
845
47
  ```
846
48
 
847
- ---
848
-
849
- ### Example: Writing `ARRAY OF INT` type variable
49
+ ### Write a value
850
50
 
851
51
  ```js
852
- try {
853
- const res = await client.writeSymbol('GVL_Test.TestArray', [9999, 8888, 6666, 5555, 4444])
854
-
855
- console.log('Value written:', res.value)
856
-
857
- } catch (err) {
858
- console.log('Something failed:', err)
859
- return
860
- }
52
+ await client.writeValue('GVL_Example.StringValue', 'a new value');
861
53
  ```
862
-
863
- ---
864
-
865
- ### Example: Writing `ARRAY of STRUCT` type variable
54
+ ### Subscribe to value changes
866
55
 
867
56
  ```js
868
- try {
869
- const res = await client.writeSymbol('GVL_Test.TestArray',
870
- [ { SomeText: 'First value',
871
- SomeReal: 1.0,
872
- SomeDate: new Date()},
873
- { SomeText: 'Second',
874
- SomeReal: 10.10,
875
- SomeDate: new Date()},
876
- { SomeText: 'Third',
877
- SomeReal: 20.20,
878
- SomeDate: new Date()},
879
- { SomeText: 'Fourth',
880
- SomeReal: 30.30,
881
- SomeDate: new Date()},
882
- { SomeText: 'Fifth',
883
- SomeReal: 40.40,
884
- SomeDate: new Date()}]
885
- )
886
-
887
- console.log('Value written:', res.value)
888
-
889
- } catch (err) {
890
- console.log('Something failed:', err)
891
- return
892
- }
57
+ await client.subscribe({
58
+ target: 'GVL_Example.ChangingValue',
59
+ cycleTime: 100,
60
+ callback: (data, subscription) => console.log(`${data.timestamp}: Value changed to ${data.value}`)
61
+ });
893
62
  ```
894
63
 
895
- ---
896
- ### Example: Writing `FUNCTION BLOCK` type variable
897
-
898
- Starting a timer from Node.js and setting time to 60 seconds.
64
+ ## Support
899
65
 
900
- **NOTE:** Using autoFill parameter to keep the rest as-is.
901
- ```js
902
- try {
903
- const res = await client.writeSymbol('GVL_Test.TestTimer', {
904
- IN: true,
905
- PT: 60000,
906
- }, true)
907
-
908
- console.log('Value written:', res.value)
909
- } catch (err) {
910
- console.log('Something failed:', err)
911
- }
66
+ * Bugs and feature requests:
67
+ * [Github Issues](https://github.com/jisotalo/ads-client/issues)
68
+ * Help, support and discussion:
69
+ * [Github Discussions](https://github.com/jisotalo/ads-client/discussions)
70
+ * Professional support:
71
+ * Support and also development available
72
+ * Contact me!
912
73
 
913
- /*
914
- Example console output
74
+ 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!
915
75
 
916
- Value written: { IN: true, PT: 60000, Q: false, ET: 0, M: false, StartTime: 0 }
917
- */
918
- ```
76
+ [![Donate](https://img.shields.io/badge/Donate-PayPal-yellow)](https://www.paypal.com/donate/?business=KUWBXXCVGZZME&no_recurring=0&currency_code=EUR)
919
77
 
920
- ## Subscribing to PLC variables (device notifications)
921
-
922
- By using `subscribe` method, we can receive variable values automatically from the PLC if they change or periodically.
923
-
924
- See full `subscribe` documentation [from the docs](https://jisotalo.github.io/ads-client/Client.html#subscribe).
925
-
926
- ---
927
-
928
- ### Subcribe to variable value (on-change)
929
-
930
-
931
- The following wants the PLC to check if the value has changed every 1000 milliseconds. If it has changed, callback is called with the latest value in `data` parameter.
932
-
933
- After 10 seconds the subscription is unsubscribed.
934
-
935
- ```js
936
- try {
937
- let subscription = await client.subscribe('GVL_Test.IncrementingValue', (data, sub) => {
938
- //Note: The sub parameter is the same as returned by client.subcribe()
939
- console.log(`${data.timeStamp}: Value changed to ${data.value}`)
940
-
941
- }, 1000)
942
-
943
- console.log(`Subscribed to ${subscription.target}`)
944
-
945
- //Unsubscribe and disconnect after 10 seconds
946
- setTimeout((async () => {
947
- //The subscribe() returns object that contains unsubscribe() method
948
- await subscription.unsubscribe()
949
-
950
- console.log('Unsubscribed')
951
- }), 10000)
952
-
953
- } catch (err) {
954
- console.log('Something failed:', err)
955
- return
956
- }
957
-
958
- /*
959
- Example console output
960
-
961
- Subscribed to GVL_Test.IncrementingValue
962
- Mon Apr 13 2020 13:02:26 GMT+0300 (GMT+03:00): Value changed to 1586
963
- Mon Apr 13 2020 13:02:27 GMT+0300 (GMT+03:00): Value changed to 1588
964
- Mon Apr 13 2020 13:02:28 GMT+0300 (GMT+03:00): Value changed to 1590
965
- ...
966
- Mon Apr 13 2020 13:02:34 GMT+0300 (GMT+03:00): Value changed to 1602
967
- Unsubscribed
968
- ```
969
-
970
- ---
971
-
972
- ### Subcribe to variable value (cyclic)
973
-
974
- The following wants the PLC to send the variable value every 1000 milliseconds. The callback is called with the latest value in `data` parameter (it might have changed or not).
975
-
976
- ```js
977
- //Our callback function
978
- const onChange = (data, sub) => {
979
- console.log(`${data.timeStamp}: ${sub.target} changed to ${data.value}`)
980
-
981
- //We can call sub.unsubscribe() here if we want
982
- }
983
-
984
- try {
985
- let subscription = await client.subscribe('GVL_Test.IncrementingValue', onChange, 1000, false)
986
-
987
- console.log(`Subscribed to ${subscription.target}`)
988
-
989
- } catch (err) {
990
- console.log('Something failed:', err)
991
- return
992
- }
993
-
994
- /*
995
- Example console output
996
-
997
-
998
- Subscribed to GVL_Test.IncrementingValue
999
- Mon Apr 13 2020 13:09:04 GMT+0300 (GMT+03:00): GVL_Test.IncrementingValue changed to 273
1000
- Mon Apr 13 2020 13:09:05 GMT+0300 (GMT+03:00): GVL_Test.IncrementingValue changed to 275
1001
- Mon Apr 13 2020 13:09:06 GMT+0300 (GMT+03:00): GVL_Test.IncrementingValue changed to 277
1002
- ...
1003
- ```
1004
-
1005
- ## Reading and writing raw data
1006
-
1007
- It's possible to read and write raw data using ads-client. Reading will result in a `Buffer` object, that contains the read data as bytes. Writing accepts a `Buffer` object that is then written to the PLC.
1008
-
1009
- Handling raw data is usually the most fastest and efficient way, as there is usually much less network traffic required. The methods require known `indexGroup` and `indexOffset` values.
1010
-
1011
- ### Getting symbol index group, offset and size
1012
-
1013
- Variable symbol information can be acquired with method `getSymbolInfo`. The symbol infoc contains required `indexGroup`, `indexOffset` and `size`.
1014
-
1015
- ```js
1016
- const info = await client.getSymbolInfo('GVL_Test.TestINT')
1017
- console.log(info)
1018
- /*
1019
- { indexGroup: 16448,
1020
- indexOffset: 414816,
1021
- size: 2,
1022
- dataType: 2,
1023
- dataTypeStr: 'ADST_INT16',
1024
- flags: 8,
1025
- flagsStr: [ 'TypeGuid' ],
1026
- arrayDimension: 0,
1027
- nameLength: 16,
1028
- typeLength: 3,
1029
- commentLength: 0,
1030
- name: 'GVL_Test.TestINT',
1031
- type: 'INT',
1032
- comment: '' }
1033
- */
1034
- ```
1035
-
1036
- ### Reading a single raw value
1037
- ```js
1038
- //Reading DINT from indexGroup 16448 and indexOffset 411836 (4 bytes)
1039
- const result = await client.readRaw(16448, 411836, 4)
1040
- console.log(result) //<Buffer 37 61 00 00>
1041
- ```
1042
-
1043
- ### Writing a single raw value
1044
- ```js
1045
- //Writing value 123 to DINT from indexGroup 16448 and indexOffset 411836 (4 bytes)
1046
- const data = Buffer.alloc(4)
1047
- data.writeInt32LE(123)
1048
-
1049
- await client.writeRaw(16448, 411836, data)
1050
- ```
1051
-
1052
- ### Reading multiple raw values
1053
-
1054
- Starting from version 1.3.0 you can use ADS sum commands to read multiple values in a single request. This is faster than reading one by one.
1055
-
1056
- Method returns an array of results, one result object for each read operation. If result has `success` of true, the read was succesful and data is located in `data`. Otherwise error information can be read from `errorInfo`.
1057
-
1058
- ```js
1059
- const result = await client.readRawMulti([
1060
- {
1061
- indexGroup: 16448,
1062
- indexOffset: 411836,
1063
- size: 4
1064
- },{
1065
- indexGroup: 123, //Note: Incorrect on purpose
1066
- indexOffset: 436040,
1067
- size: 255
1068
- }
1069
- ])
1070
- console.log(result)
1071
- /*
1072
- [ { success: true,
1073
- errorInfo: { error: false, errorCode: 0, errorStr: 'No error' },
1074
- target: { indexGroup: 16448, indexOffset: 411836 },
1075
- data: <Buffer 00 43 3a d4> },
1076
- { success: false,
1077
- errorInfo:
1078
- { error: true, errorCode: 1794, errorStr: 'Invalid index group' },
1079
- target: { indexGroup: 123, indexOffset: 436040 },
1080
- data:
1081
- <Buffer 00 00 00 00 ... > } ]
1082
- */
1083
- ```
1084
-
1085
- ### Writing multiple raw values
1086
-
1087
- Starting from version 1.3.0 you can use ADS sum commands to write multiple values in a single request. This is faster than writing one by one.
1088
-
1089
- Method returns an array of results, one result object for each write operation. If result has `success` of true, the write was succesful. Otherwise error information can be read from `errorInfo`.
1090
-
1091
- ```js
1092
- //Create raw data for DINT with value 555
1093
- const data = Buffer.alloc(4)
1094
- data.writeInt32LE(555)
1095
-
1096
- const result = await client.writeRawMulti([
1097
- {
1098
- indexGroup: 16448,
1099
- indexOffset: 411836,
1100
- data: data
1101
- },{
1102
- indexGroup: 123, //Note: Incorrect on purpose
1103
- indexOffset: 436040,
1104
- data: Buffer.alloc(255)
1105
- }
1106
- ])
1107
- console.log(result)
1108
- /*
1109
- [ { success: true,
1110
- errorInfo: { error: false, errorCode: 0, errorStr: 'No error' },
1111
- target: { indexGroup: 16448, indexOffset: 411836 } },
1112
- { success: false,
1113
- errorInfo:
1114
- { error: true,
1115
- errorCode: 1793,
1116
- errorStr: 'Service is not supported by server' },
1117
- target: { indexGroup: 123, indexOffset: 436040 } } ]
1118
- */
1119
- ```
1120
-
1121
- ### Creating a variable handle and reading a raw value
1122
-
1123
- Using handles is another alternative for reading and writing raw data. A handle is first made using variable name and then using the returned handle, read and write operations can be made. No need to know `indexGroup` and `indexOffset`.
1124
-
1125
- NOTE: Handles should always be deleted if no more used. This doesn't mean that it wouldn't be a good habit to use the same handle all the time (for example in application backend until app is terminated). The reason is that there are limited number of handles available.
1126
-
1127
- ```js
1128
- const handle = await client.createVariableHandle('GVL_Test.TestINT')
1129
- console.log(handle)
1130
- //{ handle: 905969897, size: 2, type: 'INT' }
1131
-
1132
- const result = await client.readRawByHandle(handle)
1133
- console.log(result)
1134
- //<Buffer d2 04>
1135
-
1136
- await client.deleteVariableHandle(handle)
1137
- ```
1138
-
1139
-
1140
- ### Creating a variable handle and writing a raw value
1141
-
1142
- See *Creating a variable handle and reading a raw value* for more info about handles.
1143
-
1144
- ```js
1145
- const handle = await client.createVariableHandle('GVL_Test.TestINT')
1146
- console.log(handle)
1147
- //{ handle: 905969897, size: 2, type: 'INT' }
1148
-
1149
- //Create raw data for INT with value 12345
1150
- const data = Buffer.alloc(2)
1151
- data.writeInt32LE(12345)
1152
-
1153
- await client.writeRawByHandle(handle, data)
1154
- await client.deleteVariableHandle(handle)
1155
- ```
1156
-
1157
- ### Creating and deleting multiple variable handles
1158
-
1159
- Since version 1.10.0 it is possible to create and delete multiple handles at once. This is faster than one by one as everything is sent in one packet.
1160
-
1161
- **NOTE:** It `createVariableHandleMulti()` returns only the handle as number. No size and data type are returned as in `createVariableHandle()`.
1162
-
1163
- ```js
1164
- //Create three handles at once
1165
- const handles = (await client.createVariableHandleMulti([
1166
- 'GVL_Test.TestINT',
1167
- 'GVL_Test.TestENUM',
1168
- 'GVL_Test.THIS_IS_NOT_FOUND'
1169
- ]))
1170
-
1171
- console.log(handles)
1172
- /*
1173
- [
1174
- {
1175
- success: true,
1176
- errorInfo: { error: false, errorCode: 0, errorStr: 'No error' },
1177
- target: 'GVL_Test.TestINT',
1178
- handle: 570425600
1179
- },
1180
- {
1181
- success: true,
1182
- errorInfo: { error: false, errorCode: 0, errorStr: 'No error' },
1183
- target: 'GVL_Test.TestENUM',
1184
- handle: 570425601
1185
- },
1186
- {
1187
- success: false,
1188
- errorInfo: { error: true, errorCode: 1808, errorStr: 'Symbol not found' },
1189
- target: 'GVL_Test.THIS_IS_NOT_FOUND',
1190
- handle: null
1191
- }
1192
- ]
1193
- */
1194
-
1195
- //Read data from first handle, note that raw methods understand object as input
1196
- console.log(await client.readRawByHandle(handles[0])) //Output: <Buffer d2 04>
1197
-
1198
- //Read data from second handle, note that only handle number is given
1199
- console.log(await client.readRawByHandle(handles[1].handle)) //Output: <Buffer 64 00>
1200
-
1201
- //Delete handles
1202
- await client.deleteVariableHandleMulti(handles)
1203
- ```
1204
-
1205
-
1206
-
1207
- ### Converting a raw value to Javascript object
1208
- Using `convertFromRaw` method, raw data can be converted to Javascript object. The conversion works internally like in `readSymbol`.
1209
-
1210
- ```js
1211
- //result = <Buffer 37 61 00 00>
1212
- const value = await client.convertFromRaw(result, 'DINT')
1213
- console.log(value) //24887
1214
- ```
1215
-
1216
- Example with `readRawMulti` and custom struct:
1217
- ```js
1218
- const result = await client.readRawMulti([
1219
- {
1220
- indexGroup: 16448,
1221
- indexOffset: 449659,
1222
- size: 59
1223
- },{
1224
- indexGroup: 16448,
1225
- indexOffset: 436040,
1226
- size: 255
1227
- }
1228
- ])
1229
-
1230
- const value = await client.convertFromRaw(result[0].data, 'ST_Example')
1231
- console.log(value)
1232
- /*
1233
- { SomeText: 'Hello ads-client',
1234
- SomeReal: 3.1415927410125732,
1235
- SomeDate: 2020-04-13T12:25:33.000Z }
1236
- */
1237
- ```
1238
-
1239
- ### Converting a Javascript object to raw value
1240
- Using `convertToRaw` method, Javascript object can be converted to raw data. The conversion works internally like in `writeSymbol`.
1241
-
1242
-
1243
- ```js
1244
- const data = await client.convertToRaw(12345, 'INT')
1245
- console.log(data) //<Buffer 39 30>
1246
- ```
1247
-
1248
- The 3rd parameter `autoFill` works as in `writeSymbol`.
1249
- ```js
1250
- const data = await client.convertToRaw(
1251
- {
1252
- SomeText: 'Hello ads-client',
1253
- SomeReal: 3.1415927410125732,
1254
- }, 'ST_Example', true //NOTE: autoFill=true (as there is no SomeDate given)
1255
- )
1256
- console.log(data)
1257
- //<Buffer 48 65 6c 6c 6f 20 ... >
1258
- ```
1259
-
1260
- ## Reading and writing `POINTER TO` and `REFERENCE TO` variables
1261
-
1262
- It's also possible to work with both `POINTER TO xxx` and `REFERENCE TO xxx` variables with `ads-client`.
1263
-
1264
- - Note that using `ReadSymbol()` and `WriteSymbol()` is not possible
1265
- - Easiest way to read is `readRawByName()`
1266
- - Writing is can be done with `createVariableHandle()`, which is suitable for reading too
1267
- - Pointers require dereference operator ^ in order to work
1268
-
1269
-
1270
- ### Reading a `REFERENCE TO` value
1271
-
1272
- The value needs to be read as a raw Buffer first and then it can be converted to correct data type. `createVariableHandle()` works too but this is slightly faster and easier.
1273
-
1274
- ```js
1275
- //GVL_Test has variable TestREFERENCE : REFERENCE TO ST_Example;
1276
-
1277
- const value = await client.convertFromRaw(
1278
- await client.readRawByName('GVL_Test.TestREFERENCE'),
1279
- 'ST_Example'
1280
- )
1281
- console.log(value)
1282
- /*
1283
- {
1284
- SomeText: 'Hello ads-client',
1285
- SomeReal: 3.1415927410125732,
1286
- SomeDate: 2020-04-13T12:25:33.000Z
1287
- }
1288
- */
1289
- ```
1290
-
1291
-
1292
- ### Writing a `REFERENCE TO` value
1293
-
1294
- In order to write a reference, a variable handle needs to be created. Also the data neeeds to be converted to a raw Buffer before writing.
1295
-
1296
- ```js
1297
- //GVL_Test has variable TestREFERENCE : REFERENCE TO ST_Example;
1298
-
1299
- const value = {
1300
- SomeText: 'Hello reference variable',
1301
- SomeReal: 12345,
1302
- SomeDate: new Date()
1303
- }
1304
-
1305
- //Creating handle to the varialbe
1306
- const handle = await client.createVariableHandle('GVL_Test.TestREFERENCE')
1307
-
1308
- //Writing raw Buffer data that is first created from object
1309
- await client.writeRawByHandle(
1310
- handle,
1311
- await client.convertToRaw(value, 'ST_Example')
1312
- )
1313
-
1314
- //Always delete the handle if not reusing it later
1315
- await client.deleteVariableHandle(handle)
1316
- ```
1317
-
1318
-
1319
-
1320
- ### Reading a `POINTER TO` value
1321
-
1322
- Similar as with reference except that a dereference operator `^` is required.
1323
-
1324
- ```js
1325
- //GVL_Test has variable TestPOINTER : POINTER TO ST_Example;
1326
-
1327
- const value = await client.convertFromRaw(
1328
- await client.readRawByName('GVL_Test.TestPOINTER^'), //note ^
1329
- 'ST_Example'
1330
- )
1331
- console.log(value)
1332
- /*
1333
- {
1334
- SomeText: 'Hello ads-client',
1335
- SomeReal: 3.1415927410125732,
1336
- SomeDate: 2020-04-13T12:25:33.000Z
1337
- }
1338
- */
1339
- ```
1340
-
1341
-
1342
- ### Writing a `POINTER TO` value
1343
-
1344
- Similar as with reference except that a dereference operator `^` is required.
1345
-
1346
- ```js
1347
- //GVL_Test has variable TestPOINTER : POINTER TO ST_Example;
1348
-
1349
- const value = {
1350
- SomeText: 'Hello pointer variable',
1351
- SomeReal: 12345,
1352
- SomeDate: new Date()
1353
- }
1354
-
1355
- //Creating handle to the varialbe
1356
- const handle = await client.createVariableHandle('GVL_Test.TestPOINTER^') //note ^
1357
-
1358
- //Writing raw Buffer data that is first created from object
1359
- await client.writeRawByHandle(
1360
- handle,
1361
- await client.convertToRaw(value, 'ST_Example')
1362
- )
1363
-
1364
- //Always delete the handle if not reusing it later
1365
- await client.deleteVariableHandle(handle)
1366
- ```
1367
-
1368
-
1369
- ## Calling a function block method with parameters using RPC (remote procedure call)
1370
- Starting from version 1.8.0, it is possible to call function block methods directly from Node.js. Input and output parameters are available as well as method return value. **Only supported on TwinCAT 3.**
1371
-
1372
- ---
1373
- **WARNING - IMPORTANT NOTE**
1374
- - Do not use online change if you change RPC method parameters or return data types
1375
- - Make sure that parameters and return value have no `pack-mode` pragmas defined, otherwise data might be corrupted
1376
- - Do not use `ARRAY` values directly in parameters or return value, encapsulate arrays inside struct and use the struct instead
1377
- - The feature is new and there might some bugs as it's not well documented by Beckhoff
1378
- ---
1379
-
1380
- In the following example we have a function block named `FB_RpcTest`. There is an instance of it at global variable list with a path of `GVL_Test.RpcTest`.
1381
-
1382
- ![image](https://user-images.githubusercontent.com/13457157/86382902-9cccb880-bc96-11ea-83b8-daae9de65a66.png)
1383
-
1384
- ### Calling a simple RPC method
1385
-
1386
- The code of `Calculator` method is the following. It has also VAR_OUTPUT parameters. Idea is that calculation is returned as outputs and return value tells if it was succesful.
1387
- ```
1388
- {attribute 'TcRpcEnable'}
1389
- METHOD Calculator : BOOL
1390
- VAR_INPUT
1391
- Value1 : REAL;
1392
- Value2 : REAL;
1393
- END_VAR
1394
- VAR_OUTPUT
1395
- Sum : REAL;
1396
- Product : REAL;
1397
- Division : REAL;
1398
- END_VAR
1399
-
1400
- //--- Code begins ---
1401
-
1402
- //Return TRUE if all success
1403
- Calculator := TRUE;
1404
-
1405
- Sum := Value1 + Value2;
1406
- Product := Value1 * Value2;
1407
-
1408
- IF Value2 <> 0 THEN
1409
- Division := Value1 / Value2;
1410
- ELSE
1411
- Division := 0;
1412
- Calculator := FALSE;
1413
- END_IF
1414
- ```
1415
-
1416
- The method can be called from Node.js:
1417
- ```js
1418
- const result = await client.invokeRpcMethod("GVL_Test.RpcTest","Calculator", {
1419
- Value1: 100.50,
1420
- Value2: 2.2
1421
- })
1422
-
1423
- console.log(result)
1424
-
1425
- /*
1426
- Example console output:
1427
-
1428
- {
1429
- returnValue: true,
1430
- outputs: {
1431
- Sum: 102.69999694824219,
1432
- Product: 221.10000610351562,
1433
- Division: 45.68181610107422
1434
- }
1435
- }
1436
- */
1437
- ```
1438
-
1439
- ### Using structs with RPC methods
1440
-
1441
- The code of the `StructTest` method is following. It has only one input and a return value (both are structs).
1442
-
1443
- ```
1444
- {attribute 'TcRpcEnable'}
1445
- METHOD StructTest : ST_Example
1446
- VAR_INPUT
1447
- Input : ST_Example;
1448
- END_VAR
1449
-
1450
- //--- Code begins ---
1451
-
1452
- StructTest.SomeText := CONCAT('Response: ', Input.SomeText);
1453
- StructTest.SomeReal := Input.SomeReal * 10.0;
1454
- StructTest.SomeDate := Input.SomeDate + T#24H;
1455
- ```
1456
- The method can be called from Node.js:
1457
-
1458
- ```js
1459
- const result = await client.invokeRpcMethod("GVL_Test.RpcTest","StructTest", {
1460
- Input: {
1461
- SomeText: 'Hello RPC method',
1462
- SomeReal: 1200.50,
1463
- SomeDate: new Date() //2020-07-03T14:57:22.000Z
1464
- }
1465
- })
1466
-
1467
- console.log(result)
1468
- /*
1469
- Example console output:
1470
-
1471
- {
1472
- returnValue: {
1473
- SomeText: 'Response: Hello RPC method',
1474
- SomeReal: 12005,
1475
- SomeDate: 2020-07-03T15:57:22.000Z
1476
- },
1477
- outputs: {}
1478
- }
1479
- */
1480
- ```
1481
-
1482
-
1483
- ## Starting and stopping the PLC
1484
-
1485
- The PLC runtime(s) can be started and stopped using following methods. Internally `WriteControl()` is used.
1486
-
1487
- Note that all following methods will fail, if the PLC is already in the target state.
1488
-
1489
- **Starting the PLC**
1490
- ```js
1491
- await client.startPlc() //Start the PLC from settings.targetAdsPort
1492
- await client.startPlc(852) //Start the PLC from ADS port 852
1493
- ```
1494
-
1495
- **Stopping the PLC**
1496
- ```js
1497
- await client.stopPlc() //Stop the PLC from settings.targetAdsPort
1498
- await client.stopPlc(852) //Stop the PLC from ADS port 852
1499
- ```
1500
-
1501
- **Restarting the PLC**
1502
- ```js
1503
- await client.restartPlc() //Restart the PLC from settings.targetAdsPort
1504
- await client.restartPlc(852) //Restart the PLC from ADS port 852
1505
- ```
1506
-
1507
- **Reading the PLC state**
1508
-
1509
- The PLC runtime state can always be read using `readPlcRuntimeState()` and the latest known state of PLC runtime at `settings.targetAdsPort` is located in `metaData.plcRuntimeState`.
1510
- ```js
1511
- await client.readPlcRuntimeState() //Read PLC runtime status from settings.targetAdsPort
1512
- //Example result: { adsState: 5, adsStateStr: 'Run', deviceState: 0 }
1513
- await client.readPlcRuntimeState(852) //Read PLC runtime status from ADS port 852
1514
- ```
1515
-
1516
- ## Starting and stopping the TwinCAT system
1517
-
1518
- The TwinCAT system can be started and set to config mode using following methods. This can be useful for example when updating the PLC software. Internally `WriteControl()` is used.
1519
-
1520
- Note that all following methods will fail, if the system is already in the target state/mode.
1521
-
1522
- **Setting the TwinCAT system to run mode**
1523
- ```js
1524
- await client.setSystemManagerToRun()
1525
- ```
1526
- **Setting the TwinCAT system to config mode**
1527
- ```js
1528
- await client.setSystemManagerToConfig()
1529
- ```
1530
- **Restart TwinCAT system**
1531
- ```js
1532
- //Same as calling setSystemManagerToRun()
1533
- await client.restartSystemManager()
1534
- ```
1535
-
1536
- **Reading the TwinCAT system state**
1537
-
1538
- The TwinCAT system state can always be read using `readSystemManagerState()` and the latest known state is located in `metaData.systemManagerState`.
1539
- ```js
1540
- await client.readSystemManagerState() //{ adsState: 5, adsStateStr: 'Run', deviceState: 1 }
1541
- ```
1542
-
1543
- ## Sending custom ADS commands
1544
-
1545
- Since version 1.11.0 it's possible to send any custom ADS commands using `sendAdsCommand()`
1546
-
1547
- **Example:** Read device info from system manager
1548
- ```js
1549
- //Read device info from system manager (port 10000)
1550
- const result = await client.sendAdsCommand(
1551
- ads.ADS.ADS_COMMAND.ReadDeviceInfo,
1552
- Buffer.alloc(0),
1553
- 10000
1554
- )
1555
- console.log(result)
1556
- /*
1557
- {
1558
- amsTcp: { command: 0, commandStr: 'Ads command', dataLength: 56 },
1559
- ams: {
1560
- targetAmsNetId: '192.168.5.131.1.1',
1561
- targetAdsPort: 37538,
1562
- sourceAmsNetId: '192.168.5.131.1.1',
1563
- sourceAdsPort: 10000,
1564
- adsCommand: 1,
1565
- adsCommandStr: 'ReadDeviceInfo',
1566
- stateFlags: 5,
1567
- stateFlagsStr: 'Response, AdsCommand, Tcp',
1568
- dataLength: 24,
1569
- errorCode: 0,
1570
- invokeId: 7,
1571
- error: false,
1572
- errorStr: ''
1573
- },
1574
- ads: {
1575
- rawData: <Buffer 00 00 00 00 03 01 b8 0f 54 77 69 6e 43 41 54 20 53 79 73 74 65 6d 00 00>,
1576
- errorCode: 0,
1577
- data: {
1578
- majorVersion: 3,
1579
- minorVersion: 1,
1580
- versionBuild: 4024,
1581
- deviceName: 'TwinCAT System'
1582
- },
1583
- error: false
1584
- }
1585
- }
1586
- */
1587
- ```
1588
-
1589
- **Example:** Read all ADS routes from target system
1590
-
1591
- See this gist for a simple example how to read all TwinCAT routes from target system:
1592
-
1593
- https://gist.github.com/jisotalo/cfcc9e4935dfc6f391667cad2cdcb6c6
1594
-
1595
- # Available ads-client events
1596
-
1597
- Since version 1.10.0 there are different events available from `Client` class instance.
1598
-
1599
- - `on('connectionLost')`
1600
- - Emitted when connection to target is lost
1601
- - `on('symbolVersionChange', symbolVersion)`
1602
- - Emitted when target symbol version changes
1603
- - `on('systemManagerStateChange', state)`
1604
- - Emitted when system manager state changes
1605
- - Note: Not available in all connection setups
1606
- - `on('routerStateChange', state)`
1607
- - Emitted when ADS router state changes
1608
- - Note: Not available in all connection setups
1609
- - `on('plcRuntimeStateChange', state)`
1610
- - Emitted when target PLC runtime state changes
1611
- - `on('ads-client-error', err)`
1612
- - Emitted when errors during communication
1613
- - Only those that aren't catched otherwise: Like if unknown command or unknown notification is received.
1614
- - No errors that are thrown in method calls!
1615
- - `on('connect', connectionInfo)`
1616
- - Emitted when connection is established to the target
1617
- - `on('disconnect')`
1618
- - Emitted when disconnected from the target
1619
- - `on('reconnect)`
1620
- - Emitted when connection is re-established (like after connectionLost event)
1621
-
1622
- ## Example: Printing to console when PLC runtime state changes:
1623
- ```js
1624
- client.on('plcRuntimeStateChange', state => {
1625
- console.log('State is now:', state)
1626
- })
1627
-
1628
- //When PLC is stopped:
1629
- //State is now: { adsState: 6, adsStateStr: 'Stop', deviceState: 0 }
1630
- ```
1631
-
1632
- ## Example: Catching an error that is not directly from a method call
1633
- ```js
1634
- client.on('ads-client-error', err => {
1635
- console.log('Error:', err.message)
1636
- })
1637
- //When unknown notification data is received:
1638
- //Error: Ads notification received but it has unknown notificationHandle (30). Use unsubscribe() to save resources.
1639
- ```
1640
-
1641
-
1642
-
1643
-
1644
- # Debugging
1645
- If you have problems or you are interested, you can enabled debug output to console. The ads-client uses `debug` package for debugging.
1646
-
1647
- Debugging can be enabled from terminal or from Javascript code.
1648
-
1649
- ## Enabling debug from code
1650
-
1651
- You can change the debug level with method `setDebugging(level)`:
1652
- ```js
1653
- client.setDebugging(2)
1654
- ```
1655
- Different debug levels explained:
1656
- - 0: No debugging (default)
1657
- - 1: Errors have full stack traces, no debug printing
1658
- - 2: Basic debug printing (same as `DEBUG='ads-client'`)
1659
- - 3: Detailed debug printing (same as `DEBUG='ads-client,ads-client:details'`)
1660
- - 4: Detailed debug printing and raw I/O data (same as `DEBUG='ads-client*'`)
1661
-
1662
- ## Enabling debugging from terminal
1663
- See the [debug package](https://www.npmjs.com/package/debug) for instructions.
1664
-
1665
- Example for Visual Studio Code (PowerShell):
1666
- ```bash
1667
- $env:DEBUG='ads-client,ads-client:details'
1668
- ```
1669
-
1670
- Different debug levels explained:
1671
- - Basic debug printing `DEBUG='ads-client'`
1672
- - Basic and detailed debug printing `DEBUG='ads-client,ads-client:details'`
1673
- - Basic, detailed and raw I/O data: `DEBUG='ads-client*'`
1674
-
1675
- # FAQ
1676
-
1677
- ### Connection is working very badly and lot's of timeouts
1678
- Possible fixes:
1679
- - Remove all routes and create them again
1680
- - Increase timeout delay setting (`timeoutDelay`)
1681
- - If you have very fast subscriptions, try to cache all data types before subscribing using `readAndCacheDataTypes()`
1682
-
1683
- ### When using JSON.stringify or similar I'm getting a `TypeError: Do not know how to serialize a BigInt`
1684
- - JSON.stringify doesn't understand BigInt (64 bit integer) values as default
1685
- - Use setting `disableBigInt: true` to receive Buffer objects instead of BigInts
1686
- - Another solution is to use something like [this](https://github.com/GoogleChromeLabs/jsbi/issues/30#issuecomment-521460510)
1687
-
1688
- ### Can I connect from Raspberry Pi to TwinCAT?
1689
-
1690
- Absolutely. See chapter "Supported platforms and setups", but basically:
1691
- 1. Open a TCP port 48898 from your PLC
1692
- 2. Edit StaticRoutes.xml file from your PLC
1693
- 3. Connect from Raspberry using the PLC IP address as router address and the local AMS Net Id you wrote to StaticRoutes.xml
1694
-
1695
- ### Receiving ADS error 1808 `Symbol not found` even when it should be found
1696
-
1697
- - Make sure you have updated the latest PLC software using *download*. It seems that online change isn't updating everything.
1698
- - If you are using TwinCAT 2, see chapter [IMPORTANT: Things to know when using with TwinCAT 2](#important-things-to-know-when-using-with-twincat-2)
1699
-
1700
- ### Having timeouts and/or 'mailbox is full' errors when sending lot's of ADS commands
1701
-
1702
- - The AMS router is capable of handling only limited number of requests in a certain time.
1703
- - Other possible reason is that operating system TCP window is full because of large number of requests.
1704
-
1705
- Solution:
1706
- - Use structs or arrays to send data in larger packets
1707
- - Try raw/multi commands to decrease data usage
1708
-
1709
- ### Having problems to connect from OSX or Raspberry Pi to target PLC
1710
-
1711
- - You need to connect to the PLC AMS router instead
1712
-
1713
- Solution:
1714
- - See [this issue comment](https://github.com/jisotalo/ads-client/issues/51#issuecomment-758016428) by hansipete how to do it.
1715
-
1716
- ### A data type is not found even when it should be
1717
-
1718
- 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.
1719
-
1720
- For example, when copying a variable name from TwinCAT online view using CTRL+C, it might not work:
1721
- - Displayed name: `ARRAY [0..1, 0..1] OF ST_Example`
1722
- - The value copied to clipboard `ARRAY [0..1, 0..1] OF ST_Example`
1723
- - --> **This causes error!**
1724
- - 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)
1725
-
1726
- If you have problems, try to read the variable information using `readSymbolInfo()`. The final solution is to read all data types using `readAndCacheDataTypes()` and manually finding the correct type.
1727
-
1728
- ### ClientException: Connection failed: Device system manager state read failed
1729
-
1730
- This error indicates that the given AmsnetId didn't contain system manager service (port 10000). If you connect to the PLC system, there is always system manager and PLC runtime(s). However, when connecting to other systems than PLC, it might be that there is no system manager service.
1731
-
1732
- Solution:
1733
- - Double check AmsNetId settings (if connecting directly to PLC)
1734
- - [Set `bareClient` setting to skip all system manager and PLC runtime checks](#connecting-to-systems-without-plc-runtime) (version 1.13.0 ->)
1735
-
1736
- ### Connection failed (error EADDRNOTAVAIL)
1737
- This could happen if you have manually provided `localAddress` or `localTcpPort` that don't exist.
1738
- For example, setting localAddress to 192.168.10.1 when the computer has only ethernet interface with IP 192.168.1.1.
1739
-
1740
- See https://github.com/jisotalo/ads-client/issues/82
1741
-
1742
- ### Problems running ads-client with docker
1743
-
1744
- - EADDRNOTAVAIL: See above and https://github.com/jisotalo/ads-client/issues/82
1745
-
1746
- ### How to connect to PLC that is in CONFIG mode?
1747
- 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.
1748
-
1749
- `Target and system manager found but couldn't connect to the PLC runtime (see settings allowHalfOpen and bareClient)`
1750
-
1751
- You can disable the check by providing setting `allowHalfOpen: true`. After that, it's possible to start the PLC by `setSystemManagerToRun()`. However, when using this setting internal subscription like symbol version etc. might not work properly.
1752
-
1753
- Another option is to use setting `bareClient: true` (since v.1.13.0). However, when using this option, the ads-client does not handle anything automatically - it's just a bare client (duh).
1754
-
1755
- I would suggest to use ads-client normally without any special settings. If the target is at config mode, use separate client instance to start it, and the again the normal instance to connect to a running system. This way the client works the best.
1756
-
1757
- ### Getting a message `Ads notification received but it has unknown notificationHandle (**). Use unsubscribe() to save resources.`
1758
-
1759
- Possible reasons:
1760
- * You have created notifications (subscriptions) using `subscribe()` and then closed the Node.js application without unsubscribing them first (TwinCAT still sends the data)
1761
- * You are connecting without router (providing directly the target IP as router address) and you have other connections too like TwinCAT XAE running. See issue: https://github.com/jisotalo/ads-client/issues/85
1762
-
1763
- Solution:
1764
- * When closing application, first unsubscribe from all notifications using `unsubscribeAll()`
1765
- * Use router instead of direct connection, see https://github.com/jisotalo/ads-client/issues/85#issuecomment-1193098519
1766
-
1767
- # Automatic testing
1768
- Since version 1.14.0 the library has automatic testing using Jest. Idea is to run the tests before updates to make sure everything works OK (this should have been done much earlier...)
1769
-
1770
- Separate PLC project is required for testing, see https://github.com/jisotalo/ads-client-test-plc-project for more project and more info.
1771
-
1772
- Tests are run with command `npm test` (not in npm version, please clone this repository).
1773
-
1774
- # Documentation
1775
-
1776
- You can find the full html documentation from the project [GitHub home page](https://jisotalo.github.io/ads-client/) as well as from `./docs/` folder in the repository.
78
+ ## Library testing
79
+
80
+ Target is that all functions of the library are always tested before releasing.
81
+
82
+ `npm test` results - updated 24.08.2024
83
+
84
+ <details>
85
+ <summary>Click to show test results</summary>
86
+ <pre>
87
+ √ IMPORTANT NOTE: This test requires running a specific PLC project locally (https://github.com/jisotalo/ads-client-test-plc-project)
88
+ connection
89
+ client is not connected at beginning (1 ms)
90
+ √ checking ads client settings (1 ms)
91
+ connecting to the target (31 ms)
92
+ √ checking that test PLC project is active (13 ms)
93
+ √ checking that test PLC project version is correct (10 ms)
94
+ caching of symbols and data types (1 ms)
95
+ reconnecting (36 ms)
96
+ resetting PLC to original state
97
+ resetting PLC (514 ms)
98
+ √ checking that reset was successful (8 ms)
99
+ checking that PLC is not running (12 ms)
100
+ √ setting IsReset to false (4 ms)
101
+ √ starting PLC (8 ms)
102
+ √ checking that test PLC project is running (506 ms)
103
+ testing PLC runtime stop, start, restart
104
+ √ stopping PLC (16 ms)
105
+ starting PLC (15 ms)
106
+ restarting PLC (538 ms)
107
+ system state, PLC runtime states and device information
108
+ √ reading TwinCAT system state (7 ms)
109
+ √ reading PLC runtime (port 851) state (5 ms)
110
+ √ reading PLC runtime (port 852) state (5 ms)
111
+ reading PLC runtime device info (4 ms)
112
+ √ reading TwinCAT system device info (5 ms)
113
+ √ reading PLC runtime symbol version (5 ms)
114
+ symbols and data types
115
+ √ reading upload info (4 ms)
116
+ √ reading all symbols (15 ms)
117
+ reading single symbol information (2 ms)
118
+ √ reading all data type information (19 ms)
119
+ reading single data type information (2 ms)
120
+ data conversion
121
+ converting a raw PLC value to a Javascript variable (5 ms)
122
+ converting a Javascript value to a raw PLC value (40 ms)
123
+ reading values
124
+ reading standard values
125
+ √ reading BOOL (15 ms)
126
+ √ reading BYTE (8 ms)
127
+ √ reading WORD (7 ms)
128
+ √ reading DWORD (6 ms)
129
+ √ reading SINT (11 ms)
130
+ reading USINT (6 ms)
131
+ √ reading INT (13 ms)
132
+ reading UINT (7 ms)
133
+ √ reading DINT (15 ms)
134
+ √ reading UDINT (8 ms)
135
+ reading REAL (32 ms)
136
+ reading STRING (15 ms)
137
+ reading DATE (8 ms)
138
+ √ reading DT (13 ms)
139
+ reading TOD (16 ms)
140
+ √ reading TIME (9 ms)
141
+ √ reading LWORD (8 ms)
142
+ reading LINT (12 ms)
143
+ reading ULINT (7 ms)
144
+ √ reading LREAL (29 ms)
145
+ √ reading WSTRING (12 ms)
146
+ √ reading LDATE (---- TODO: Needs TC 3.1.4026 ----)
147
+ reading LDT (---- TODO: Needs TC 3.1.4026 ----)
148
+ √ reading LTOD (---- TODO: Needs TC 3.1.4026 ----)
149
+ √ reading LTIME (7 ms)
150
+ reading standard array values
151
+ √ reading ARRAY OF BOOL (13 ms)
152
+ √ reading ARRAY OF BYTE (8 ms)
153
+ reading ARRAY OF WORD (7 ms)
154
+ √ reading ARRAY OF DWORD (8 ms)
155
+ √ reading ARRAY OF SINT (13 ms)
156
+ reading ARRAY OF USINT (7 ms)
157
+ reading ARRAY OF INT (15 ms)
158
+ reading ARRAY OF UINT (8 ms)
159
+ reading ARRAY OF DINT (16 ms)
160
+ √ reading ARRAY OF UDINT (10 ms)
161
+ √ reading ARRAY OF REAL (31 ms)
162
+ √ reading ARRAY OF STRING (15 ms)
163
+ reading ARRAY OF DATE (3 ms)
164
+ √ reading ARRAY OF DT (14 ms)
165
+ reading ARRAY OF TOD (14 ms)
166
+ √ reading ARRAY OF TIME (8 ms)
167
+ reading ARRAY OF LWORD (4 ms)
168
+ √ reading ARRAY OF LINT (10 ms)
169
+ reading ARRAY OF ULINT (4 ms)
170
+ √ reading ARRAY OF LREAL (24 ms)
171
+ reading ARRAY OF WSTRING (13 ms)
172
+ √ reading ARRAY OF LDATE (---- TODO: Needs TC 3.1.4026 ----)
173
+ √ reading ARRAY OF LDT (---- TODO: Needs TC 3.1.4026 ----)
174
+ reading ARRAY OF LTOD (---- TODO: Needs TC 3.1.4026 ----)
175
+ √ reading ARRAY OF LTIME (6 ms)
176
+ reading complex values
177
+ reading STRUCT (15 ms)
178
+ reading ALIAS (5 ms)
179
+ reading ENUM (41 ms)
180
+ reading POINTER (address) (7 ms)
181
+ reading SUBRANGE (7 ms)
182
+ reading UNION (23 ms)
183
+ reading FUNCTION_BLOCK (29 ms)
184
+ reading INTERFACE (9 ms)
185
+ reading complex array values
186
+ reading ARRAY OF STRUCT (18 ms)
187
+ reading ARRAY OF ALIAS (8 ms)
188
+ reading ARRAY OF ENUM (40 ms)
189
+ reading ARRAY OF POINTER (address) (7 ms)
190
+ reading ARRAY OF SUBRANGE (7 ms)
191
+ √ reading ARRAY OF UNION (8 ms)
192
+ √ reading ARRAY OF FUNCTION_BLOCK (32 ms)
193
+ √ reading ARRAY OF INTERFACE (6 ms)
194
+ reading special types / cases
195
+ √ reading ARRAY with negative index (7 ms)
196
+ reading multi-dimensional ARRAY (8 ms)
197
+ reading ARRAY OF ARRAY (8 ms)
198
+ reading STRUCT with pragma: {attribute 'pack_mode' := '1'} (9 ms)
199
+ √ reading STRUCT with pragma: {attribute 'pack_mode' := '8'} (9 ms)
200
+ √ reading an empty FUNCTION_BLOCK (7 ms)
201
+ reading an empty STRUCT (8 ms)
202
+ √ reading an empty ARRAY (7 ms)
203
+ reading a single BIT (14 ms)
204
+ reading a struct with BIT types (8 ms)
205
+ reading dereferenced POINTER and REFERENCE values
206
+ √ reading POINTER (value) (8 ms)
207
+ reading REFERENCE (value) (8 ms)
208
+ reading raw data
209
+ √ reading a raw value (5 ms)
210
+ reading a raw value using symbol (3 ms)
211
+ √ reading a raw value using path (2 ms)
212
+ reading multiple raw values (multi/sum command) (5 ms)
213
+ reading (misc)
214
+ reading a value using symbol (5 ms)
215
+ writing values
216
+ writing standard values
217
+ writing BOOL (23 ms)
218
+ √ writing BYTE (11 ms)
219
+ writing WORD (9 ms)
220
+ writing DWORD (9 ms)
221
+ writing SINT (24 ms)
222
+ √ writing USINT (12 ms)
223
+ writing INT (22 ms)
224
+ writing UINT (11 ms)
225
+ writing DINT (22 ms)
226
+ √ writing UDINT (9 ms)
227
+ √ writing REAL (47 ms)
228
+ √ writing STRING (24 ms)
229
+ √ writing DATE (12 ms)
230
+ writing DT (22 ms)
231
+ writing TOD (23 ms)
232
+ writing TIME (12 ms)
233
+ writing LWORD (12 ms)
234
+ writing LINT (25 ms)
235
+ √ writing ULINT (12 ms)
236
+ writing LREAL (47 ms)
237
+ writing WSTRING (21 ms)
238
+ √ writing LDATE (---- TODO: Needs TC 3.1.4026 ----)
239
+ writing LDT (---- TODO: Needs TC 3.1.4026 ----)
240
+ √ writing LTOD (---- TODO: Needs TC 3.1.4026 ----)
241
+ √ writing LTIME (11 ms)
242
+ writing standard array values
243
+ writing ARRAY OF BOOL (25 ms)
244
+ √ writing ARRAY OF BYTE (12 ms)
245
+ writing ARRAY OF WORD (10 ms)
246
+ √ writing ARRAY OF DWORD (13 ms)
247
+ writing ARRAY OF SINT (18 ms)
248
+ √ writing ARRAY OF USINT (9 ms)
249
+ √ writing ARRAY OF INT (19 ms)
250
+ writing ARRAY OF UINT (12 ms)
251
+ writing ARRAY OF DINT (19 ms)
252
+ √ writing ARRAY OF UDINT (10 ms)
253
+ √ writing ARRAY OF REAL (48 ms)
254
+ writing ARRAY OF STRING (25 ms)
255
+ √ writing ARRAY OF DATE (11 ms)
256
+ writing ARRAY OF DT (21 ms)
257
+ writing ARRAY OF TOD (25 ms)
258
+ writing ARRAY OF TIME (12 ms)
259
+ √ writing ARRAY OF LWORD (13 ms)
260
+ writing ARRAY OF LINT (23 ms)
261
+ writing ARRAY OF ULINT (12 ms)
262
+ writing ARRAY OF LREAL (48 ms)
263
+ √ writing ARRAY OF WSTRING (23 ms)
264
+ √ writing ARRAY OF LDATE (---- TODO: Needs TC 3.1.4026 ----)
265
+ √ writing ARRAY OF LDT (---- TODO: Needs TC 3.1.4026 ----) (1 ms)
266
+ √ writing ARRAY OF LTOD (---- TODO: Needs TC 3.1.4026 ----)
267
+ writing ARRAY OF LTIME (12 ms)
268
+ writing complex values
269
+ writing STRUCT (22 ms)
270
+ writing ALIAS (11 ms)
271
+ √ writing ENUM (54 ms)
272
+ writing POINTER (address) (17 ms)
273
+ writing SUBRANGE (20 ms)
274
+ writing UNION (48 ms)
275
+ writing FUNCTION_BLOCK (47 ms)
276
+ √ writing INTERFACE (15 ms)
277
+ writing complex array values
278
+ √ writing ARRAY OF STRUCT (26 ms)
279
+ writing ARRAY OF ALIAS (13 ms)
280
+ √ writing ARRAY OF ENUM (55 ms)
281
+ writing ARRAY OF POINTER (address) (16 ms)
282
+ √ writing ARRAY OF SUBRANGE (11 ms)
283
+ writing ARRAY OF UNION (13 ms)
284
+ √ writing ARRAY OF FUNCTION_BLOCK (48 ms)
285
+ √ writing ARRAY OF INTERFACE (15 ms)
286
+ writing special types / cases
287
+ √ writing ARRAY with negative index (17 ms)
288
+ writing multi-dimensional ARRAY (16 ms)
289
+ √ writing ARRAY OF ARRAY (16 ms)
290
+ writing STRUCT with pragma: {attribute 'pack_mode' := '1'} (14 ms)
291
+ √ writing STRUCT with pragma: {attribute 'pack_mode' := '8'} (14 ms)
292
+ writing an empty FUNCTION_BLOCK (7 ms)
293
+ √ writing an empty STRUCT (8 ms)
294
+ writing an empty ARRAY (7 ms)
295
+ √ writing a single BIT (39 ms)
296
+ √ writing a struct with BIT types (15 ms)
297
+ writing dereferenced POINTER and REFERENCE values
298
+ writing POINTER (value) (21 ms)
299
+ √ writing REFERENCE (value) (21 ms)
300
+ writing raw data
301
+ √ writing a raw value (7 ms)
302
+ √ writing a raw value using symbol (5 ms)
303
+ writing a raw value using path (16 ms)
304
+ √ writing multiple raw values (multi/sum command) (18 ms)
305
+ writing (misc)
306
+ √ writing a value using symbol (7 ms)
307
+ variable handles
308
+ creating and deleting a varible handle (14 ms)
309
+ √ reading value using a variable handle (10 ms)
310
+ √ writing value using a variable handle (31 ms)
311
+ creating and deleting multiple varible handles (multi/sum command) (9 ms)
312
+ subscriptions (ADS notifications)
313
+ √ subscribing and unsubscribing successfully (2036 ms)
314
+ √ subscribing to a changing value (10 ms) with default cycle time (3028 ms)
315
+ subscribing to a changing value (10 ms) with 10 ms cycle time (27 ms)
316
+ √ subscribing to a constant value with maximum delay of 2000 ms (2036 ms)
317
+ subscribing to a raw ADS address (229 ms)
318
+ √ subscribing using subscribeSymbol() (2020 ms)
319
+ subscribing to a raw ADS address using subscribeRaw() (219 ms)
320
+ remote procedure calls (RPC methods)
321
+ √ calling a RPC method (15 ms)
322
+ calling a RPC method with struct parameters (14 ms)
323
+ calling a RPC method without return value and without parameters (9 ms)
324
+ miscellaneous
325
+ √ sending read write ADS command (6 ms)
326
+ √ sending multiple read write ADS commands (multi/sum command) (10 ms)
327
+ issue specific tests
328
+ issue 103 (https://github.com/jisotalo/ads-client/issues/103)
329
+ √ calling unsubscribeAll() multiple times (should not crash to unhandled exception) (51 ms)
330
+ disconnecting
331
+ √ disconnecting client (5 ms)
332
+ controlling TwinCAT system service
333
+ connecting (1 ms)
334
+ setting TwinCAT system to config (2022 ms)
335
+ setting TwinCAT system to run (2027 ms)
336
+ disconnecting (2 ms)
337
+ </pre>
338
+ </details>
1777
339
 
1778
340
  # License
1779
341
 
1780
- Licensed under [MIT License](http://www.opensource.org/licenses/MIT) so commercial use is possible. Please respect the license, linking to this page is also much appreciated.
1781
-
342
+ Licensed under [MIT License](http://www.opensource.org/licenses/MIT).
1782
343
 
1783
- Copyright (c) 2020 Jussi Isotalo <<j.isotalo91@gmail.com>>
344
+ Copyright (c) Jussi Isotalo <<j.isotalo91@gmail.com>>
1784
345
 
1785
346
  Permission is hereby granted, free of charge, to any person obtaining a copy
1786
347
  of this software and associated documentation files (the "Software"), to deal