ciplink 0.3.2__tar.gz → 0.3.3__tar.gz

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.
Files changed (82) hide show
  1. {ciplink-0.3.2 → ciplink-0.3.3}/Cargo.lock +30 -4
  2. {ciplink-0.3.2 → ciplink-0.3.3}/Cargo.toml +1 -1
  3. {ciplink-0.3.2 → ciplink-0.3.3}/PKG-INFO +20 -2
  4. {ciplink-0.3.2 → ciplink-0.3.3}/README.md +19 -1
  5. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/Cargo.toml +1 -0
  6. ciplink-0.3.3/crates/ciplink/src/browse.rs +498 -0
  7. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/cip.rs +64 -35
  8. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/lib.rs +1 -0
  9. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/driver.rs +38 -0
  10. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/src/lib.rs +238 -0
  11. ciplink-0.3.3/crates/ciplink-py/tests/test_browse.py +88 -0
  12. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/_version.py +1 -1
  13. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/cip_driver.py +76 -1
  14. {ciplink-0.3.2 → ciplink-0.3.3}/LICENSE +0 -0
  15. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/README.md +0 -0
  16. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/epath.rs +0 -0
  17. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/error.rs +0 -0
  18. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/identity.rs +0 -0
  19. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/auth.rs +0 -0
  20. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/bundle.rs +0 -0
  21. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/bundle_data.rs +0 -0
  22. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/descriptions.rs +0 -0
  23. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/metadata.rs +0 -0
  24. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/mod.rs +0 -0
  25. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/rw.rs +0 -0
  26. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/tag_cache.rs +0 -0
  27. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/trend.rs +0 -0
  28. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/logix/types.rs +0 -0
  29. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/packets.rs +0 -0
  30. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/reader.rs +0 -0
  31. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/slc/driver.rs +0 -0
  32. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/slc/mod.rs +0 -0
  33. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/slc/pccc.rs +0 -0
  34. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/status.rs +0 -0
  35. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/tables.rs +0 -0
  36. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/transport.rs +0 -0
  37. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/types.rs +0 -0
  38. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink/src/value.rs +0 -0
  39. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/.gitignore +0 -0
  40. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/Cargo.toml +0 -0
  41. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/bench/cpu_bench.py +0 -0
  42. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/bench/tags_bench.py +0 -0
  43. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/build.rs +0 -0
  44. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/src/defs.rs +0 -0
  45. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/conftest.py +0 -0
  46. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/dump_driver.py +0 -0
  47. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/test_binding.py +0 -0
  48. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/test_definitions.py +0 -0
  49. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/test_parity.py +0 -0
  50. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/test_sim_checks.py +0 -0
  51. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/test_tagserver.py +0 -0
  52. {ciplink-0.3.2 → ciplink-0.3.3}/crates/ciplink-py/tests/test_trend.py +0 -0
  53. {ciplink-0.3.2 → ciplink-0.3.3}/pyproject.toml +0 -0
  54. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/__init__.py +0 -0
  55. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/_logix_bundle_codec.py +0 -0
  56. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/_logix_metadata_bundle.py +0 -0
  57. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/cip/__init__.py +0 -0
  58. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/cip/data_types.py +0 -0
  59. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/cip/object_library.py +0 -0
  60. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/cip/pccc.py +0 -0
  61. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/cip/services.py +0 -0
  62. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/cip/status_info.py +0 -0
  63. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/const.py +0 -0
  64. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/custom_types.py +0 -0
  65. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/exceptions.py +0 -0
  66. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/logger.py +0 -0
  67. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/logix_auth.py +0 -0
  68. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/logix_driver.py +0 -0
  69. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/logix_metadata.py +0 -0
  70. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/map.py +0 -0
  71. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/packets/__init__.py +0 -0
  72. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/packets/base.py +0 -0
  73. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/packets/cip.py +0 -0
  74. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/packets/ethernetip.py +0 -0
  75. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/packets/logix.py +0 -0
  76. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/packets/util.py +0 -0
  77. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/py.typed +0 -0
  78. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/slc_driver.py +0 -0
  79. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/socket_.py +0 -0
  80. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/tag.py +0 -0
  81. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/trend.py +0 -0
  82. {ciplink-0.3.2 → ciplink-0.3.3}/python/ciplink/util.py +0 -0
@@ -70,10 +70,11 @@ dependencies = [
70
70
 
71
71
  [[package]]
72
72
  name = "ciplink"
73
- version = "0.3.2"
73
+ version = "0.3.3"
74
74
  dependencies = [
75
75
  "chacha20poly1305",
76
76
  "getrandom 0.3.4",
77
+ "if-addrs",
77
78
  "indexmap",
78
79
  "log",
79
80
  "num-bigint",
@@ -85,7 +86,7 @@ dependencies = [
85
86
 
86
87
  [[package]]
87
88
  name = "ciplink-ffi"
88
- version = "0.3.2"
89
+ version = "0.3.3"
89
90
  dependencies = [
90
91
  "ciplink",
91
92
  "ciplink-sim",
@@ -95,7 +96,7 @@ dependencies = [
95
96
 
96
97
  [[package]]
97
98
  name = "ciplink-py"
98
- version = "0.3.2"
99
+ version = "0.3.3"
99
100
  dependencies = [
100
101
  "ciplink",
101
102
  "indexmap",
@@ -106,7 +107,7 @@ dependencies = [
106
107
 
107
108
  [[package]]
108
109
  name = "ciplink-sim"
109
- version = "0.3.2"
110
+ version = "0.3.3"
110
111
  dependencies = [
111
112
  "ciplink",
112
113
  "indexmap",
@@ -201,6 +202,16 @@ version = "0.5.0"
201
202
  source = "registry+https://github.com/rust-lang/crates.io-index"
202
203
  checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
203
204
 
205
+ [[package]]
206
+ name = "if-addrs"
207
+ version = "0.15.0"
208
+ source = "registry+https://github.com/rust-lang/crates.io-index"
209
+ checksum = "c0a05c691e1fae256cf7013d99dad472dc52d5543322761f83ec8d47eab40d2b"
210
+ dependencies = [
211
+ "libc",
212
+ "windows-sys",
213
+ ]
214
+
204
215
  [[package]]
205
216
  name = "indexmap"
206
217
  version = "2.14.2"
@@ -533,6 +544,21 @@ dependencies = [
533
544
  "wit-bindgen",
534
545
  ]
535
546
 
547
+ [[package]]
548
+ name = "windows-link"
549
+ version = "0.2.1"
550
+ source = "registry+https://github.com/rust-lang/crates.io-index"
551
+ checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
552
+
553
+ [[package]]
554
+ name = "windows-sys"
555
+ version = "0.61.2"
556
+ source = "registry+https://github.com/rust-lang/crates.io-index"
557
+ checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
558
+ dependencies = [
559
+ "windows-link",
560
+ ]
561
+
536
562
  [[package]]
537
563
  name = "wit-bindgen"
538
564
  version = "0.46.0"
@@ -3,7 +3,7 @@ resolver = "3"
3
3
  members = ["crates/ciplink", "crates/ciplink-py"]
4
4
 
5
5
  [workspace.package]
6
- version = "0.3.2"
6
+ version = "0.3.3"
7
7
  edition = "2024"
8
8
  rust-version = "1.85"
9
9
  license = "MIT"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: ciplink
3
- Version: 0.3.2
3
+ Version: 0.3.3
4
4
  Classifier: Development Status :: 4 - Beta
5
5
  Classifier: Intended Audience :: Developers
6
6
  Classifier: Intended Audience :: Manufacturing
@@ -62,7 +62,7 @@ flowchart LR
62
62
  | **Throughput** | many tags packed into each packet, with large values fragmented and chunked automatically |
63
63
  | **Tag discovery** | the tag list and UDT definitions are uploaded on connect, or loaded on first use with `lazy_tags`; a binary tag cache makes restarts near-instant |
64
64
  | **Online-edit safe** | tags are addressed by instance ID and checked against the controller's tag-table version on every read and write, so an online edit never silently returns the wrong tag |
65
- | **Extras** | tag descriptions, PLC clock, device discovery, module identity, and a simulated controller for testing |
65
+ | **Extras** | tag descriptions, PLC clock, device discovery, RSWho-style device browsing, module identity, and a simulated controller for testing |
66
66
  | **Trends** | the controller samples tags at a fixed period (down to 1 ms) and the driver uploads them in batches, like a Studio 5000 trend |
67
67
 
68
68
  ## Install
@@ -164,6 +164,24 @@ with LogixDriver("192.0.2.10") as plc:
164
164
  `capacity` (default 4096) bounds the samples waiting for `read()`; the oldest are dropped when it is full and
165
165
  counted in `dropped_samples`. `duration` (seconds) stops the trend by itself.
166
166
 
167
+ ## Browse devices
168
+
169
+ Like RSWho in FactoryTalk Linx: `get_ports()` lists a device's ports, `browse_port()` finds the module in each slot,
170
+ the node at each address or, on an EtherNet/IP port, every device on the port's subnet. Every node found has a
171
+ `route` to browse further (`""` is the device at the IP, `"bp/3"` the module in slot 3, `"bp/2/enet/192.168.1.10"` a
172
+ device behind the module in slot 2). `python -m examples.device_browser` is a small tree browser built on them. Every binding has browsing:
173
+ `get_ports`/`browse_port`/`scan_port` in Rust, C++ and Python (`iter_port` streams), `GetPorts`/`BrowsePort`/
174
+ `ScanPort` in C#, `ciplink_get_ports`/`ciplink_browse_port`/`ciplink_scan_port` in C.
175
+
176
+ ```python
177
+ from ciplink import CIPDriver
178
+
179
+ with CIPDriver("192.0.2.10") as drv:
180
+ for port in drv.get_ports(): # e.g. Backplane, EtherNet/IP
181
+ for node in drv.browse_port("", port): # every slot, or every address of the subnet
182
+ print(node["route"], node["identity"] and node["identity"]["product_name"])
183
+ ```
184
+
167
185
  ## Test without a PLC
168
186
 
169
187
  `ciplink-sim` is a simulated Logix or SLC controller that speaks real EtherNet/IP. Load it with tags and UDTs from
@@ -39,7 +39,7 @@ flowchart LR
39
39
  | **Throughput** | many tags packed into each packet, with large values fragmented and chunked automatically |
40
40
  | **Tag discovery** | the tag list and UDT definitions are uploaded on connect, or loaded on first use with `lazy_tags`; a binary tag cache makes restarts near-instant |
41
41
  | **Online-edit safe** | tags are addressed by instance ID and checked against the controller's tag-table version on every read and write, so an online edit never silently returns the wrong tag |
42
- | **Extras** | tag descriptions, PLC clock, device discovery, module identity, and a simulated controller for testing |
42
+ | **Extras** | tag descriptions, PLC clock, device discovery, RSWho-style device browsing, module identity, and a simulated controller for testing |
43
43
  | **Trends** | the controller samples tags at a fixed period (down to 1 ms) and the driver uploads them in batches, like a Studio 5000 trend |
44
44
 
45
45
  ## Install
@@ -141,6 +141,24 @@ with LogixDriver("192.0.2.10") as plc:
141
141
  `capacity` (default 4096) bounds the samples waiting for `read()`; the oldest are dropped when it is full and
142
142
  counted in `dropped_samples`. `duration` (seconds) stops the trend by itself.
143
143
 
144
+ ## Browse devices
145
+
146
+ Like RSWho in FactoryTalk Linx: `get_ports()` lists a device's ports, `browse_port()` finds the module in each slot,
147
+ the node at each address or, on an EtherNet/IP port, every device on the port's subnet. Every node found has a
148
+ `route` to browse further (`""` is the device at the IP, `"bp/3"` the module in slot 3, `"bp/2/enet/192.168.1.10"` a
149
+ device behind the module in slot 2). `python -m examples.device_browser` is a small tree browser built on them. Every binding has browsing:
150
+ `get_ports`/`browse_port`/`scan_port` in Rust, C++ and Python (`iter_port` streams), `GetPorts`/`BrowsePort`/
151
+ `ScanPort` in C#, `ciplink_get_ports`/`ciplink_browse_port`/`ciplink_scan_port` in C.
152
+
153
+ ```python
154
+ from ciplink import CIPDriver
155
+
156
+ with CIPDriver("192.0.2.10") as drv:
157
+ for port in drv.get_ports(): # e.g. Backplane, EtherNet/IP
158
+ for node in drv.browse_port("", port): # every slot, or every address of the subnet
159
+ print(node["route"], node["identity"] and node["identity"]["product_name"])
160
+ ```
161
+
144
162
  ## Test without a PLC
145
163
 
146
164
  `ciplink-sim` is a simulated Logix or SLC controller that speaks real EtherNet/IP. Load it with tags and UDTs from
@@ -16,6 +16,7 @@ repository.workspace = true
16
16
  [dependencies]
17
17
  chacha20poly1305 = "0.10"
18
18
  getrandom = "0.3"
19
+ if-addrs = "0.15"
19
20
  indexmap = "2"
20
21
  log = "0.4"
21
22
  num-bigint = "0.4"
@@ -0,0 +1,498 @@
1
+ //! Device browsing like RSWho in FactoryTalk Linx: the ports of a device (Port Object, class 0xF4) and the
2
+ //! devices on each port (Identity Object of every slot or node).
3
+ //!
4
+ //! A route is relative to the device at the driver's IP address, as text like a connection path: `""` is that
5
+ //! device, `bp/3` the module in slot 3 of its backplane, `bp/2/enet/192.168.1.10` a device behind the module
6
+ //! in slot 2. The driver's own connection path (e.g. a Logix `bp/0`) is not used.
7
+ //!
8
+ //! An empty slot or missing device costs a reply from the bridge, which may wait for its Unconnected Send
9
+ //! timeout (about 4 s), so a [`Scan`] probes the addresses of a port from several connections of its own.
10
+
11
+ use crate::cip::{CipConnection, CipOptions, GenericMessage, RoutePath};
12
+ use crate::epath::{LogicalValue, encode_epath, parse_cip_route};
13
+ use crate::identity::ModuleIdentity;
14
+ use crate::reader::Reader;
15
+ use crate::transport::Connector;
16
+ use crate::types::Elementary;
17
+ use crate::{Error, Result, Value};
18
+ use std::net::Ipv4Addr;
19
+ use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
20
+ use std::sync::{Arc, mpsc};
21
+
22
+ /// Class code of the Port Object.
23
+ pub const PORT_OBJECT: u16 = 0xF4;
24
+ const TCP_IP_INTERFACE: u16 = 0xF5;
25
+ const ETHERNET_LINK: u16 = 0xF6;
26
+ const GET_ATTRIBUTES_ALL: u8 = 0x01;
27
+ const GET_ATTRIBUTE_SINGLE: u8 = 0x0E;
28
+
29
+ /// One port of a device (an instance of its Port Object).
30
+ #[derive(Clone, Debug, PartialEq, Eq)]
31
+ pub struct PortInfo {
32
+ /// Port number, the port of a route segment through it (1 is the backplane).
33
+ pub number: u16,
34
+ /// Port type (attribute 1), e.g. 1 backplane, 2 ControlNet, 4 EtherNet/IP, 5 DeviceNet.
35
+ pub port_type: u16,
36
+ /// Port name (attribute 4), e.g. `"Backplane"` or `"A"`; empty if the device does not have one.
37
+ pub name: String,
38
+ /// This device's own address on the port (attribute 7), e.g. its slot; None if not reported.
39
+ pub address: Option<String>,
40
+ /// Node addresses on the port (attribute 8), None if not reported.
41
+ pub node_range: Option<(u16, u16)>,
42
+ /// EtherNet/IP ports: the IP address and subnet mask of the port (its TCP/IP Interface Object).
43
+ pub ip: Option<(Ipv4Addr, Ipv4Addr)>,
44
+ }
45
+
46
+ impl PortInfo {
47
+ /// The name of the port type.
48
+ pub fn type_name(&self) -> String {
49
+ port_type_name(self.port_type)
50
+ }
51
+
52
+ /// The addresses [`browse_port`](CipConnection::browse_port) probes: the reported node range, else the
53
+ /// usual range of the port type; on an EtherNet/IP port every host of its subnet, at most the /24 around
54
+ /// its own address. None if they are not known (an EtherNet/IP port without an IP address).
55
+ pub fn nodes(&self) -> Option<Vec<String>> {
56
+ let range = |first: u16, last: u16| Some((first..=last).map(|n| n.to_string()).collect());
57
+ if let Some((first, last)) = self.node_range {
58
+ return range(first, last);
59
+ }
60
+ match (self.port_type, self.ip) {
61
+ (4, Some((ip, mask))) => Some(subnet_hosts(ip, mask)),
62
+ (1, _) => range(0, 16), // a 17-slot chassis
63
+ (2 | 3, _) => range(1, 99), // ControlNet
64
+ (5, _) => range(0, 63), // DeviceNet
65
+ _ => None,
66
+ }
67
+ }
68
+ }
69
+
70
+ /// The host addresses of the subnet of `ip`, at most the /24 around it.
71
+ fn subnet_hosts(ip: Ipv4Addr, mask: Ipv4Addr) -> Vec<String> {
72
+ let mask = u32::from(mask).max(0xFFFF_FF00);
73
+ let network = u32::from(ip) & mask;
74
+ let broadcast = network | !mask;
75
+ (network.saturating_add(1)..broadcast)
76
+ .map(|a| Ipv4Addr::from(a).to_string())
77
+ .collect()
78
+ }
79
+
80
+ /// The instance of the Ethernet Link Object in a port's Link Object path (attribute 3: its size in words,
81
+ /// then the path), None if the path names another object.
82
+ fn link_instance(data: &[u8]) -> Option<u16> {
83
+ let mut r = Reader::new(data);
84
+ r.u16().ok()?;
85
+ let (mut class, mut instance) = (None, None);
86
+ while let Ok(segment) = r.u8() {
87
+ match segment {
88
+ 0x20 => class = Some(u16::from(r.u8().ok()?)),
89
+ 0x21 => class = r.u8().and_then(|_| r.u16()).ok(),
90
+ 0x24 => instance = Some(u16::from(r.u8().ok()?)),
91
+ 0x25 => instance = r.u8().and_then(|_| r.u16()).ok(),
92
+ _ => break,
93
+ }
94
+ }
95
+ (class? == ETHERNET_LINK).then_some(instance?)
96
+ }
97
+
98
+ /// The name of a CIP port type.
99
+ pub fn port_type_name(port_type: u16) -> String {
100
+ match port_type {
101
+ 0 => "None".into(),
102
+ 1 => "Backplane".into(),
103
+ 2 => "ControlNet".into(),
104
+ 3 => "ControlNet (redundant)".into(),
105
+ 4 => "EtherNet/IP".into(),
106
+ 5 => "DeviceNet".into(),
107
+ 200 => "CompoNet".into(),
108
+ 201 => "Modbus/TCP".into(),
109
+ 202 => "Modbus/SL".into(),
110
+ 203 => "SERCOS III".into(),
111
+ 65535 => "No active link".into(),
112
+ n @ 100..=199 => format!("Vendor specific ({n})"),
113
+ n => format!("Type {n}"),
114
+ }
115
+ }
116
+
117
+ /// One slot or node found by [`browse_port`](CipConnection::browse_port).
118
+ #[derive(Clone, Debug, PartialEq, Eq)]
119
+ pub struct Node {
120
+ /// Route to the node, to browse it further.
121
+ pub route: String,
122
+ /// Slot, node or IP address on the port.
123
+ pub address: String,
124
+ /// The node's identity, None if it did not answer.
125
+ pub identity: Option<ModuleIdentity>,
126
+ /// Why there is no identity (e.g. an empty slot).
127
+ pub error: Option<String>,
128
+ }
129
+
130
+ /// The route one hop past `route` on `port`.
131
+ pub fn child_route(route: &str, port: u16, address: &str) -> String {
132
+ let route = route.trim_matches('/');
133
+ if route.is_empty() {
134
+ format!("{port}/{address}")
135
+ } else {
136
+ format!("{route}/{port}/{address}")
137
+ }
138
+ }
139
+
140
+ /// The port and link of the port segment at the start of a padded EPATH, the link as text (e.g. `"3"`).
141
+ fn port_segment(data: &[u8]) -> Option<(u16, String)> {
142
+ let first = *data.first()?;
143
+ if first & 0xE0 != 0 {
144
+ return None; // not a port segment
145
+ }
146
+ let mut at = 1;
147
+ let link_size = if first & 0x10 != 0 {
148
+ at += 1;
149
+ usize::from(*data.get(1)?)
150
+ } else {
151
+ 1
152
+ };
153
+ let port = if first & 0x0F == 0x0F {
154
+ at += 2;
155
+ u16::from_le_bytes([*data.get(at - 2)?, *data.get(at - 1)?])
156
+ } else {
157
+ u16::from(first & 0x0F)
158
+ };
159
+ let link = data.get(at..at + link_size)?;
160
+ let link = match link {
161
+ [n] => n.to_string(),
162
+ text => String::from_utf8_lossy(text).into_owned(),
163
+ };
164
+ Some((port, link))
165
+ }
166
+
167
+ impl CipConnection {
168
+ /// Sends a request to the device at `route`: directly for `""`, else by Unconnected Send. The reply data,
169
+ /// or in the inner Err the error the device (or a bridge on the way) answered with.
170
+ fn request_at(
171
+ &mut self,
172
+ route: &str,
173
+ service: u8,
174
+ class: u16,
175
+ instance: u16,
176
+ attribute: Option<u16>,
177
+ name: &str,
178
+ ) -> Result<std::result::Result<Vec<u8>, String>> {
179
+ let route = route.trim_matches('/');
180
+ let route_path = if route.is_empty() {
181
+ RoutePath::None
182
+ } else {
183
+ RoutePath::Encoded(encode_epath(
184
+ &parse_cip_route(route, false)?,
185
+ true,
186
+ true,
187
+ true,
188
+ )?)
189
+ };
190
+ let msg = GenericMessage {
191
+ service,
192
+ class_code: LogicalValue::Int(class.into()),
193
+ instance: LogicalValue::Int(instance.into()),
194
+ attribute: attribute.map(|a| LogicalValue::Int(a.into())),
195
+ name: name.into(),
196
+ connected: false,
197
+ unconnected_send: !route.is_empty(),
198
+ route_path,
199
+ ..GenericMessage::default()
200
+ };
201
+ let reply = self.generic_message(&msg)?;
202
+ Ok(match reply.tag.error {
203
+ Some(err) => Err(err.message),
204
+ None => Ok(reply.data().unwrap_or_default().to_vec()),
205
+ })
206
+ }
207
+
208
+ /// The identity of the device at `route`. CommErrors pass through, a device that answers with an error
209
+ /// is a ResponseError.
210
+ pub fn identity_at(&mut self, route: &str) -> Result<ModuleIdentity> {
211
+ let data = self
212
+ .request_at(route, GET_ATTRIBUTES_ALL, 0x01, 1, None, "identity")?
213
+ .map_err(Error::response)?;
214
+ ModuleIdentity::decode(&mut Reader::new(&data))
215
+ }
216
+
217
+ /// The ports of the device at `route`, none if it has no Port Object.
218
+ pub fn ports_at(&mut self, route: &str) -> Result<Vec<PortInfo>> {
219
+ let get = |conn: &mut Self, instance: u16, attribute: u16| {
220
+ conn.request_at(
221
+ route,
222
+ GET_ATTRIBUTE_SINGLE,
223
+ PORT_OBJECT,
224
+ instance,
225
+ Some(attribute),
226
+ "port",
227
+ )
228
+ .map(|r| r.ok())
229
+ };
230
+ // class attribute 2: the highest instance
231
+ let Some(max) = get(self, 0, 2)? else {
232
+ return Ok(Vec::new());
233
+ };
234
+ let max = Reader::new(&max).u16().unwrap_or(0);
235
+ let mut ports = Vec::new();
236
+ for instance in 1..=max {
237
+ let Some(port_type) = get(self, instance, 1)? else {
238
+ continue;
239
+ };
240
+ let Ok(port_type) = Reader::new(&port_type).u16() else {
241
+ continue;
242
+ };
243
+ let number = get(self, instance, 2)?
244
+ .and_then(|d| Reader::new(&d).u16().ok())
245
+ .unwrap_or(instance);
246
+ let name = match get(self, instance, 4)? {
247
+ Some(d) => match Elementary::ShortString.decode(&mut Reader::new(&d)) {
248
+ Ok(Value::String(s)) => s,
249
+ _ => String::new(),
250
+ },
251
+ None => String::new(),
252
+ };
253
+ let address = get(self, instance, 7)?
254
+ .and_then(|d| port_segment(&d))
255
+ .map(|(_, link)| link);
256
+ let node_range = get(self, instance, 8)?.and_then(|d| {
257
+ let mut r = Reader::new(&d);
258
+ Some((r.u16().ok()?, r.u16().ok()?))
259
+ });
260
+ let ip = if port_type == 4 {
261
+ let link = get(self, instance, 3)?.and_then(|d| link_instance(&d));
262
+ self.port_ip(route, link.unwrap_or(1))?
263
+ } else {
264
+ None
265
+ };
266
+ ports.push(PortInfo {
267
+ number,
268
+ port_type,
269
+ name,
270
+ address,
271
+ node_range,
272
+ ip,
273
+ });
274
+ }
275
+ Ok(ports)
276
+ }
277
+
278
+ /// The IP address and subnet mask of instance `instance` of the TCP/IP Interface Object (attribute 5,
279
+ /// the interface configuration), None if not readable or not set.
280
+ fn port_ip(&mut self, route: &str, instance: u16) -> Result<Option<(Ipv4Addr, Ipv4Addr)>> {
281
+ let reply = self.request_at(
282
+ route,
283
+ GET_ATTRIBUTE_SINGLE,
284
+ TCP_IP_INTERFACE,
285
+ instance,
286
+ Some(5),
287
+ "tcp/ip",
288
+ )?;
289
+ Ok(reply.ok().and_then(|d| {
290
+ let mut r = Reader::new(&d);
291
+ let (ip, mask) = (Ipv4Addr::from(r.u32().ok()?), Ipv4Addr::from(r.u32().ok()?));
292
+ (!ip.is_unspecified()).then_some((ip, mask))
293
+ }))
294
+ }
295
+
296
+ /// A scan of `port` of the device at `route`: the addresses in `nodes`, by default (None) the port's own
297
+ /// [`nodes`](PortInfo::nodes) (none if the device has no such port).
298
+ pub fn scan(&mut self, route: &str, port: u16, nodes: Option<&[String]>) -> Result<Scan> {
299
+ let nodes = match nodes {
300
+ Some(nodes) => nodes.to_vec(),
301
+ None => self
302
+ .ports_at(route)?
303
+ .into_iter()
304
+ .find(|p| p.number == port)
305
+ .and_then(|p| p.nodes())
306
+ .unwrap_or_default(),
307
+ };
308
+ Ok(Scan {
309
+ host: format!("{}:{}", self.host(), self.port()),
310
+ socket_timeout: self.socket_timeout(),
311
+ connector: Arc::new(self.share_connector()),
312
+ route: route.to_owned(),
313
+ port,
314
+ nodes,
315
+ })
316
+ }
317
+ }
318
+
319
+ /// The probes of every address on a port, made by [`CipConnection::scan`] (or a driver's `scan_port` and
320
+ /// `browse_port`), which run on connections of their own to the device.
321
+ pub struct Scan {
322
+ host: String,
323
+ socket_timeout: Option<std::time::Duration>,
324
+ connector: Arc<Connector>,
325
+ route: String,
326
+ port: u16,
327
+ nodes: Vec<String>,
328
+ }
329
+
330
+ impl Scan {
331
+ /// The addresses probed.
332
+ pub fn nodes(&self) -> &[String] {
333
+ &self.nodes
334
+ }
335
+
336
+ /// Probes every address from `workers` connections at once (at least 1), calling `found` with each node as
337
+ /// it answers, in any order. Stops early when `found` returns false (probes under way finish first).
338
+ pub fn run(self, workers: usize, found: &mut dyn FnMut(Node) -> bool) {
339
+ let (next, stop) = (AtomicUsize::new(0), AtomicBool::new(false));
340
+ let (tx, rx) = mpsc::channel();
341
+ let scan = &self;
342
+ std::thread::scope(|threads| {
343
+ for _ in 0..workers.clamp(1, self.nodes.len().max(1)) {
344
+ let (tx, next, stop) = (tx.clone(), &next, &stop);
345
+ threads.spawn(move || {
346
+ let mut conn = None;
347
+ while !stop.load(Ordering::Relaxed) {
348
+ let Some(address) = scan.nodes.get(next.fetch_add(1, Ordering::Relaxed))
349
+ else {
350
+ break;
351
+ };
352
+ if tx.send(scan.probe(&mut conn, address)).is_err() {
353
+ break;
354
+ }
355
+ }
356
+ if let Some(mut conn) = conn {
357
+ let _ = conn.close();
358
+ }
359
+ });
360
+ }
361
+ drop(tx);
362
+ for node in rx.iter() {
363
+ if !found(node) {
364
+ stop.store(true, Ordering::Relaxed);
365
+ break;
366
+ }
367
+ }
368
+ drop(rx); // workers sending after a stop see the channel closed
369
+ });
370
+ }
371
+
372
+ /// Probes every address from `workers` connections at once; the nodes in the order of the addresses.
373
+ pub fn collect(self, workers: usize) -> Vec<Node> {
374
+ let order: std::collections::HashMap<String, usize> = (self.nodes.iter().cloned())
375
+ .enumerate()
376
+ .map(|(i, a)| (a, i))
377
+ .collect();
378
+ let mut nodes = Vec::with_capacity(self.nodes.len());
379
+ self.run(workers, &mut |node| {
380
+ nodes.push(node);
381
+ true
382
+ });
383
+ nodes.sort_by_key(|n| order.get(&n.address).copied());
384
+ nodes
385
+ }
386
+
387
+ /// The identity at one address, on this worker's connection (opened when needed, dropped after a
388
+ /// connection error so the next address opens a new one).
389
+ fn probe(&self, conn: &mut Option<CipConnection>, address: &str) -> Node {
390
+ let route = child_route(&self.route, self.port, address);
391
+ let result = (|| {
392
+ if conn.is_none() {
393
+ let options = CipOptions {
394
+ socket_timeout: self.socket_timeout,
395
+ ..CipOptions::default()
396
+ };
397
+ let connector = Arc::clone(&self.connector);
398
+ let connector: Connector = Box::new(move |h, p, t| connector(h, p, t));
399
+ let mut c = CipConnection::new(&self.host, options, connector, false)?;
400
+ if !c.open()? {
401
+ return Err(Error::comm("failed to register a session"));
402
+ }
403
+ *conn = Some(c);
404
+ }
405
+ let c = conn.as_mut().ok_or_else(|| Error::comm("no connection"))?;
406
+ c.identity_at(&route)
407
+ })();
408
+ let (identity, error) = match result {
409
+ Ok(identity) => (Some(identity), None),
410
+ Err(err) => {
411
+ if matches!(err, Error::Comm(_)) {
412
+ *conn = None;
413
+ }
414
+ (None, Some(err.to_string()))
415
+ }
416
+ };
417
+ Node {
418
+ route,
419
+ address: address.to_owned(),
420
+ identity,
421
+ error,
422
+ }
423
+ }
424
+ }
425
+
426
+ #[cfg(test)]
427
+ mod tests {
428
+ use super::*;
429
+
430
+ #[test]
431
+ fn port_segments_format_as_port_and_link() {
432
+ let seg = |data: &[u8]| port_segment(data).map(|(p, l)| format!("{p}/{l}"));
433
+ assert_eq!(seg(&[0x01, 0x03]).as_deref(), Some("1/3"));
434
+ let mut ip = vec![0x12, 8];
435
+ ip.extend(b"10.0.0.1");
436
+ assert_eq!(seg(&ip).as_deref(), Some("2/10.0.0.1"));
437
+ assert_eq!(seg(&[0x0F, 0x12, 0x00, 0x05]).as_deref(), Some("18/5"));
438
+ assert_eq!(seg(&[0x20, 0x01]), None);
439
+ assert_eq!(seg(&[]), None);
440
+ }
441
+
442
+ #[test]
443
+ fn child_routes_extend_the_route() {
444
+ assert_eq!(child_route("", 1, "3"), "1/3");
445
+ assert_eq!(child_route("1/2/", 2, "10.0.0.5"), "1/2/2/10.0.0.5");
446
+ }
447
+
448
+ #[test]
449
+ fn ports_without_a_node_range_use_their_type_default() {
450
+ let port = |port_type, node_range, ip| PortInfo {
451
+ number: 1,
452
+ port_type,
453
+ name: String::new(),
454
+ address: None,
455
+ node_range,
456
+ ip,
457
+ };
458
+ let span = |nodes: Option<Vec<String>>| {
459
+ nodes.map(|n| (n.len(), n[0].clone(), n[n.len() - 1].clone()))
460
+ };
461
+ let s = |t: &str| t.to_owned();
462
+ assert_eq!(
463
+ span(port(1, None, None).nodes()),
464
+ Some((17, s("0"), s("16")))
465
+ );
466
+ assert_eq!(
467
+ span(port(1, Some((0, 9)), None).nodes()),
468
+ Some((10, s("0"), s("9")))
469
+ );
470
+ assert_eq!(
471
+ span(port(5, None, None).nodes()),
472
+ Some((64, s("0"), s("63")))
473
+ );
474
+ assert_eq!(port(4, None, None).nodes(), None);
475
+ let ip = |a: &str, m: &str| Some((a.parse().expect("ip"), m.parse().expect("mask")));
476
+ let enet = port(4, None, ip("192.168.1.5", "255.255.255.0")).nodes();
477
+ assert_eq!(
478
+ span(enet),
479
+ Some((254, s("192.168.1.1"), s("192.168.1.254")))
480
+ );
481
+ // a bigger subnet is cut to the /24 around the port, a smaller one is kept
482
+ let wide = port(4, None, ip("10.20.30.40", "255.255.0.0")).nodes();
483
+ assert_eq!(span(wide), Some((254, s("10.20.30.1"), s("10.20.30.254"))));
484
+ let small = port(4, None, ip("10.0.0.70", "255.255.255.192")).nodes();
485
+ assert_eq!(span(small), Some((62, s("10.0.0.65"), s("10.0.0.126"))));
486
+ }
487
+
488
+ #[test]
489
+ fn link_object_paths_name_the_ethernet_link_instance() {
490
+ assert_eq!(link_instance(&[2, 0, 0x20, 0xF6, 0x24, 0x02]), Some(2));
491
+ assert_eq!(
492
+ link_instance(&[3, 0, 0x20, 0xF6, 0x25, 0, 0x01, 0x01]),
493
+ Some(0x101)
494
+ );
495
+ assert_eq!(link_instance(&[2, 0, 0x20, 0xF5, 0x24, 0x01]), None);
496
+ assert_eq!(link_instance(&[]), None);
497
+ }
498
+ }