ehatool 6.0.0.dev0__py3-none-any.whl
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.
- ehatool/VERSION +1 -0
- ehatool/__init__.py +4 -0
- ehatool/acceptance.py +92 -0
- ehatool/brt27.py +105 -0
- ehatool/brt27_sim.py +114 -0
- ehatool/calibration.py +111 -0
- ehatool/can_sniff.py +162 -0
- ehatool/cia402.py +31 -0
- ehatool/cli.py +541 -0
- ehatool/console.py +31 -0
- ehatool/device/__init__.py +4 -0
- ehatool/device/can.py +201 -0
- ehatool/device/can_discovery.py +387 -0
- ehatool/device/can_discovery.toml +19 -0
- ehatool/device/io.py +20 -0
- ehatool/devices.py +187 -0
- ehatool/diagnostics.py +58 -0
- ehatool/diagnostics.toml +208 -0
- ehatool/discovery.py +95 -0
- ehatool/display.toml +127 -0
- ehatool/ecat.py +520 -0
- ehatool/ecat.toml +17 -0
- ehatool/ecat_probe.py +401 -0
- ehatool/ecat_probe.toml +14 -0
- ehatool/eha_od.json +5871 -0
- ehatool/experiment.py +576 -0
- ehatool/image.py +70 -0
- ehatool/info.py +121 -0
- ehatool/info.toml +41 -0
- ehatool/install_host.py +243 -0
- ehatool/install_host.toml +27 -0
- ehatool/link.py +811 -0
- ehatool/link.toml +18 -0
- ehatool/live.py +112 -0
- ehatool/motor.py +86 -0
- ehatool/od.py +200 -0
- ehatool/odrive.py +450 -0
- ehatool/output.py +208 -0
- ehatool/ram_load.py +62 -0
- ehatool/scope.py +50 -0
- ehatool/sil.py +260 -0
- ehatool/update.py +320 -0
- ehatool/usb_discovery.py +164 -0
- ehatool/usb_discovery.toml +16 -0
- ehatool/web/__init__.py +28 -0
- ehatool/web/brt_sim.py +130 -0
- ehatool/web/canbus.py +95 -0
- ehatool/web/devices.py +216 -0
- ehatool/web/experiments.py +226 -0
- ehatool/web/job_params.py +208 -0
- ehatool/web/layout.toml +61 -0
- ehatool/web/longrun.py +430 -0
- ehatool/web/polling.py +41 -0
- ehatool/web/recipes/bench.toml +18 -0
- ehatool/web/records.py +333 -0
- ehatool/web/requests.py +254 -0
- ehatool/web/server.py +1051 -0
- ehatool/web/session.py +1552 -0
- ehatool/web/static/THIRD_PARTY_LICENSES.txt +133 -0
- ehatool/web/static/assets/ehapower-logo-Cr84XeX3.png +0 -0
- ehatool/web/static/assets/ehapower-mark-Con0OjPM.png +0 -0
- ehatool/web/static/assets/index-CdLvwKa-.css +1 -0
- ehatool/web/static/assets/index-DiLUQD1i.js +134 -0
- ehatool/web/static/index.html +16 -0
- ehatool/web/streams.py +64 -0
- ehatool/web/workspaces.py +124 -0
- ehatool/workflows/__init__.py +4 -0
- ehatool/workflows/cancheck.py +394 -0
- ehatool/workflows/cancheck.toml +9 -0
- ehatool/workflows/checks.py +43 -0
- ehatool/workflows/usbcheck.py +212 -0
- ehatool-6.0.0.dev0.dist-info/METADATA +38 -0
- ehatool-6.0.0.dev0.dist-info/RECORD +77 -0
- ehatool-6.0.0.dev0.dist-info/WHEEL +5 -0
- ehatool-6.0.0.dev0.dist-info/entry_points.txt +2 -0
- ehatool-6.0.0.dev0.dist-info/licenses/LICENSE +21 -0
- ehatool-6.0.0.dev0.dist-info/top_level.txt +1 -0
ehatool/ecat_probe.py
ADDED
|
@@ -0,0 +1,401 @@
|
|
|
1
|
+
# Copyright The eha-firmware Contributors
|
|
2
|
+
|
|
3
|
+
## @file
|
|
4
|
+
## @brief 宿主网卡枚举、被动 EtherCAT 观察与显式 BRD Type/Revision 探测。
|
|
5
|
+
|
|
6
|
+
import ctypes
|
|
7
|
+
import ctypes.util
|
|
8
|
+
import errno
|
|
9
|
+
import pathlib
|
|
10
|
+
import re
|
|
11
|
+
import secrets
|
|
12
|
+
import select
|
|
13
|
+
import socket
|
|
14
|
+
import struct
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
import tomllib
|
|
18
|
+
|
|
19
|
+
with pathlib.Path(__file__).with_suffix('.toml').open('rb') as file:
|
|
20
|
+
MESSAGES = tomllib.load(file)['messages']
|
|
21
|
+
|
|
22
|
+
ETHERTYPE = 0x88A4
|
|
23
|
+
OBSERVE_S = 0.10
|
|
24
|
+
PROBE_S = 0.20
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def build_probe(source, index, adp):
|
|
28
|
+
"""构造单个 BRD 0x0000(Type/Revision),零数据、零 WKC,不包含 FCS。"""
|
|
29
|
+
datagram = struct.pack('<BBHHHH', 7, index, adp, 0, 2, 0) + bytes(4)
|
|
30
|
+
frame = b'\xff' * 6 + source + struct.pack('!H', ETHERTYPE) + struct.pack('<H', 0x100E) + datagram
|
|
31
|
+
return frame.ljust(60, b'\x00')
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parse_reply(frame, request):
|
|
35
|
+
"""只接受当前请求的有效返回,返回 WKC;本机发包副本返回 None。"""
|
|
36
|
+
if len(request) < 30 or len(frame) < 30 or frame[:14] != request[:14]:
|
|
37
|
+
return None
|
|
38
|
+
header, = struct.unpack_from('<H', frame, 14)
|
|
39
|
+
if header != 0x100E or request[14:16] != frame[14:16]:
|
|
40
|
+
return None
|
|
41
|
+
command, index, adp, ado, flags, _irq = struct.unpack_from('<BBHHHH', frame, 16)
|
|
42
|
+
req_command, req_index, req_adp, req_ado, req_flags, _ = struct.unpack_from('<BBHHHH', request, 16)
|
|
43
|
+
if (req_command, req_ado, req_flags) != (7, 0, 2):
|
|
44
|
+
return None
|
|
45
|
+
if (command, index, ado) != (req_command, req_index, req_ado) or flags & ~0x4000 != 2:
|
|
46
|
+
return None
|
|
47
|
+
wkc, = struct.unpack_from('<H', frame, 28)
|
|
48
|
+
if not wkc or (adp - req_adp) & 0xFFFF != wkc:
|
|
49
|
+
return None
|
|
50
|
+
return wkc
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _is_ethercat(frame):
|
|
54
|
+
"""仅将长度合法的 EtherCAT 数据报当成活动证据。"""
|
|
55
|
+
if len(frame) < 28 or frame[12:14] != struct.pack('!H', ETHERTYPE):
|
|
56
|
+
return False
|
|
57
|
+
header, = struct.unpack_from('<H', frame, 14)
|
|
58
|
+
length = header & 0x7FF
|
|
59
|
+
return header & 0xF800 == 0x1000 and length >= 12 and len(frame) >= 16 + length
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
def _record(ifname, name, *, up, physical, reason=None):
|
|
63
|
+
return {'via': 'ecat', 'role': 'interface', 'ifname': ifname, 'name': name,
|
|
64
|
+
'state': 'unobserved', 'count': None, 'up': up, 'physical': physical,
|
|
65
|
+
'eligible': up and physical, 'reason': reason, 'method': 'os'}
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def _read_sysfs(path):
|
|
69
|
+
try:
|
|
70
|
+
return path.read_text().strip()
|
|
71
|
+
except (OSError, ValueError):
|
|
72
|
+
return None
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _linux_interfaces(ifname=None):
|
|
76
|
+
records = []
|
|
77
|
+
for _index, name in socket.if_nameindex():
|
|
78
|
+
if ifname is not None and name != ifname:
|
|
79
|
+
continue
|
|
80
|
+
path = pathlib.Path('/sys/class/net') / name
|
|
81
|
+
kind = _read_sysfs(path / 'type')
|
|
82
|
+
flags_text = _read_sysfs(path / 'flags')
|
|
83
|
+
flags = int(flags_text, 16) if flags_text else 0
|
|
84
|
+
carrier = _read_sysfs(path / 'carrier')
|
|
85
|
+
up = bool(flags & 1) and carrier != '0'
|
|
86
|
+
wired = kind == '1' and not (path / 'wireless').exists()
|
|
87
|
+
physical = wired and (path / 'device').exists()
|
|
88
|
+
# 显式指定的虚拟 Ethernet 可用于隔离测试;仍保留 physical=False。
|
|
89
|
+
eligible = up and wired and (physical or ifname is not None)
|
|
90
|
+
reason = None if eligible else ('down' if not up else 'unsupported_link')
|
|
91
|
+
record = _record(name, name, up=up, physical=physical, reason=reason)
|
|
92
|
+
record['eligible'] = eligible
|
|
93
|
+
records.append(record)
|
|
94
|
+
return records
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class _PcapIf(ctypes.Structure):
|
|
98
|
+
pass
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
_PcapIf._fields_ = [('next', ctypes.POINTER(_PcapIf)), ('name', ctypes.c_char_p),
|
|
102
|
+
('description', ctypes.c_char_p), ('addresses', ctypes.c_void_p), ('flags', ctypes.c_uint)]
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
class _Timeval(ctypes.Structure):
|
|
106
|
+
_fields_ = [('seconds', ctypes.c_long), ('microseconds', ctypes.c_long)]
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
class _PcapHeader(ctypes.Structure):
|
|
110
|
+
_fields_ = [('timestamp', _Timeval), ('caplen', ctypes.c_uint32), ('length', ctypes.c_uint32)]
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
class _BpfProgram(ctypes.Structure):
|
|
114
|
+
_fields_ = [('length', ctypes.c_uint), ('instructions', ctypes.c_void_p)]
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _pcap_library():
|
|
118
|
+
path = ctypes.util.find_library('pcap')
|
|
119
|
+
if not path:
|
|
120
|
+
raise RuntimeError(MESSAGES['pcap_missing'])
|
|
121
|
+
lib = ctypes.CDLL(path)
|
|
122
|
+
signatures = {
|
|
123
|
+
'pcap_findalldevs': ([ctypes.POINTER(ctypes.POINTER(_PcapIf)), ctypes.c_char_p], ctypes.c_int),
|
|
124
|
+
'pcap_freealldevs': ([ctypes.POINTER(_PcapIf)], None),
|
|
125
|
+
'pcap_create': ([ctypes.c_char_p, ctypes.c_char_p], ctypes.c_void_p),
|
|
126
|
+
'pcap_set_snaplen': ([ctypes.c_void_p, ctypes.c_int], ctypes.c_int),
|
|
127
|
+
'pcap_set_promisc': ([ctypes.c_void_p, ctypes.c_int], ctypes.c_int),
|
|
128
|
+
'pcap_set_timeout': ([ctypes.c_void_p, ctypes.c_int], ctypes.c_int),
|
|
129
|
+
'pcap_set_immediate_mode': ([ctypes.c_void_p, ctypes.c_int], ctypes.c_int),
|
|
130
|
+
'pcap_activate': ([ctypes.c_void_p], ctypes.c_int),
|
|
131
|
+
'pcap_datalink': ([ctypes.c_void_p], ctypes.c_int),
|
|
132
|
+
'pcap_setnonblock': ([ctypes.c_void_p, ctypes.c_int, ctypes.c_char_p], ctypes.c_int),
|
|
133
|
+
'pcap_get_selectable_fd': ([ctypes.c_void_p], ctypes.c_int),
|
|
134
|
+
'pcap_next_ex': ([ctypes.c_void_p, ctypes.POINTER(ctypes.POINTER(_PcapHeader)),
|
|
135
|
+
ctypes.POINTER(ctypes.POINTER(ctypes.c_ubyte))], ctypes.c_int),
|
|
136
|
+
'pcap_compile': ([ctypes.c_void_p, ctypes.POINTER(_BpfProgram), ctypes.c_char_p,
|
|
137
|
+
ctypes.c_int, ctypes.c_uint32], ctypes.c_int),
|
|
138
|
+
'pcap_setfilter': ([ctypes.c_void_p, ctypes.POINTER(_BpfProgram)], ctypes.c_int),
|
|
139
|
+
'pcap_freecode': ([ctypes.POINTER(_BpfProgram)], None),
|
|
140
|
+
'pcap_inject': ([ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t], ctypes.c_ssize_t),
|
|
141
|
+
'pcap_geterr': ([ctypes.c_void_p], ctypes.c_char_p),
|
|
142
|
+
'pcap_close': ([ctypes.c_void_p], None),
|
|
143
|
+
}
|
|
144
|
+
for name, (args, result) in signatures.items():
|
|
145
|
+
function = getattr(lib, name)
|
|
146
|
+
function.argtypes, function.restype = args, result
|
|
147
|
+
return lib
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _mac_interface_types():
|
|
151
|
+
"""SystemConfiguration 给出 BSD 名对应的接口类型,避免凭 en 前缀判断。"""
|
|
152
|
+
cf = ctypes.CDLL('/System/Library/Frameworks/CoreFoundation.framework/CoreFoundation')
|
|
153
|
+
sc = ctypes.CDLL('/System/Library/Frameworks/SystemConfiguration.framework/SystemConfiguration')
|
|
154
|
+
cf.CFArrayGetCount.argtypes, cf.CFArrayGetCount.restype = [ctypes.c_void_p], ctypes.c_long
|
|
155
|
+
cf.CFArrayGetValueAtIndex.argtypes = [ctypes.c_void_p, ctypes.c_long]
|
|
156
|
+
cf.CFArrayGetValueAtIndex.restype = ctypes.c_void_p
|
|
157
|
+
cf.CFStringGetCString.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_long, ctypes.c_uint32]
|
|
158
|
+
cf.CFStringGetCString.restype = ctypes.c_bool
|
|
159
|
+
cf.CFRelease.argtypes, cf.CFRelease.restype = [ctypes.c_void_p], None
|
|
160
|
+
sc.SCNetworkInterfaceCopyAll.restype = ctypes.c_void_p
|
|
161
|
+
for name in ('SCNetworkInterfaceGetBSDName', 'SCNetworkInterfaceGetInterfaceType'):
|
|
162
|
+
function = getattr(sc, name)
|
|
163
|
+
function.argtypes, function.restype = [ctypes.c_void_p], ctypes.c_void_p
|
|
164
|
+
|
|
165
|
+
def string(value):
|
|
166
|
+
buffer = ctypes.create_string_buffer(512)
|
|
167
|
+
return buffer.value.decode() if value and cf.CFStringGetCString(value, buffer, len(buffer), 0x08000100) else None
|
|
168
|
+
|
|
169
|
+
array = sc.SCNetworkInterfaceCopyAll()
|
|
170
|
+
if not array:
|
|
171
|
+
return {}
|
|
172
|
+
try:
|
|
173
|
+
result = {}
|
|
174
|
+
for index in range(cf.CFArrayGetCount(array)):
|
|
175
|
+
item = cf.CFArrayGetValueAtIndex(array, index)
|
|
176
|
+
name = string(sc.SCNetworkInterfaceGetBSDName(item))
|
|
177
|
+
if name:
|
|
178
|
+
result[name] = string(sc.SCNetworkInterfaceGetInterfaceType(item))
|
|
179
|
+
return result
|
|
180
|
+
finally:
|
|
181
|
+
cf.CFRelease(array)
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _mac_functional_types():
|
|
185
|
+
"""读取 Darwin ifreq 的功能类型;这里的 ioctl 只查询宿主接口元数据。"""
|
|
186
|
+
import fcntl
|
|
187
|
+
|
|
188
|
+
result = {}
|
|
189
|
+
# Darwin net/if.h 与 sys/sockio.h:SIOCGIFFUNCTIONALTYPE,32 字节 ifreq,值在 union 首字段。
|
|
190
|
+
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as control:
|
|
191
|
+
for _index, name in socket.if_nameindex():
|
|
192
|
+
request = bytearray(struct.pack('16s16x', name.encode()))
|
|
193
|
+
try:
|
|
194
|
+
fcntl.ioctl(control.fileno(), 0xC02069AD, request, True)
|
|
195
|
+
except OSError:
|
|
196
|
+
continue
|
|
197
|
+
result[name], = struct.unpack_from('I', request, 16)
|
|
198
|
+
return result
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _mac_interfaces(ifname=None):
|
|
202
|
+
lib = _pcap_library()
|
|
203
|
+
kinds = _mac_interface_types()
|
|
204
|
+
functional = _mac_functional_types()
|
|
205
|
+
pointer = ctypes.POINTER(_PcapIf)()
|
|
206
|
+
error = ctypes.create_string_buffer(256)
|
|
207
|
+
if lib.pcap_findalldevs(ctypes.byref(pointer), error) != 0:
|
|
208
|
+
raise OSError(error.value.decode(errors='replace'))
|
|
209
|
+
records = []
|
|
210
|
+
try:
|
|
211
|
+
current = pointer
|
|
212
|
+
while current:
|
|
213
|
+
entry = current.contents
|
|
214
|
+
name = entry.name.decode()
|
|
215
|
+
if ifname is None or name == ifname:
|
|
216
|
+
flags = entry.flags
|
|
217
|
+
up = bool(flags & 2) and flags & 0x30 != 0x20
|
|
218
|
+
kind = kinds.get(name)
|
|
219
|
+
# Darwin 的 WiFi 功能类型包括 infra=3、AWDL=4。软件桥和虚拟机口也会报告 wired=2,
|
|
220
|
+
# 因此单凭这个值不提升为物理接口;Apple 固定的克隆接口族按其本身语义排除。
|
|
221
|
+
built_in_virtual = re.fullmatch(r'(?:utun|bridge|vmenet)[0-9]+', name) is not None
|
|
222
|
+
wireless = functional.get(name) in (3, 4) or bool(flags & 8)
|
|
223
|
+
known_excluded = built_in_virtual or wireless or bool(flags & 1)
|
|
224
|
+
physical = kind == 'Ethernet' and not known_excluded
|
|
225
|
+
reason = None if up and physical else ('down' if not up else 'unsupported_link')
|
|
226
|
+
if up and kind is None and not known_excluded:
|
|
227
|
+
reason = 'classification_unknown'
|
|
228
|
+
description = entry.description.decode(errors='replace') if entry.description else name
|
|
229
|
+
records.append(_record(name, description, up=up, physical=physical, reason=reason))
|
|
230
|
+
current = entry.next
|
|
231
|
+
finally:
|
|
232
|
+
lib.pcap_freealldevs(pointer)
|
|
233
|
+
return records
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def enumerate_interfaces(ifname=None):
|
|
237
|
+
if sys.platform.startswith('linux'):
|
|
238
|
+
return _linux_interfaces(ifname)
|
|
239
|
+
if sys.platform == 'darwin':
|
|
240
|
+
return _mac_interfaces(ifname)
|
|
241
|
+
raise RuntimeError(MESSAGES['unsupported'])
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
class _PacketSocket:
|
|
245
|
+
def __init__(self, ifname):
|
|
246
|
+
self.socket = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(ETHERTYPE))
|
|
247
|
+
try:
|
|
248
|
+
self.socket.bind((ifname, 0))
|
|
249
|
+
self.socket.setblocking(False)
|
|
250
|
+
except BaseException:
|
|
251
|
+
self.close()
|
|
252
|
+
raise
|
|
253
|
+
|
|
254
|
+
def receive(self, deadline):
|
|
255
|
+
remaining = deadline - time.monotonic()
|
|
256
|
+
if remaining <= 0 or not select.select([self.socket], [], [], remaining)[0]:
|
|
257
|
+
return None
|
|
258
|
+
try:
|
|
259
|
+
return self.socket.recv(2048)
|
|
260
|
+
except BlockingIOError:
|
|
261
|
+
return None
|
|
262
|
+
|
|
263
|
+
def send(self, frame):
|
|
264
|
+
if self.socket.send(frame) != len(frame):
|
|
265
|
+
raise OSError('short Ethernet write')
|
|
266
|
+
|
|
267
|
+
def close(self):
|
|
268
|
+
self.socket.close()
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
class _PcapSocket:
|
|
272
|
+
def __init__(self, ifname):
|
|
273
|
+
self.lib = _pcap_library()
|
|
274
|
+
self.handle = None
|
|
275
|
+
error = ctypes.create_string_buffer(256)
|
|
276
|
+
handle = self.lib.pcap_create(ifname.encode(), error)
|
|
277
|
+
if not handle:
|
|
278
|
+
raise OSError(error.value.decode(errors='replace'))
|
|
279
|
+
self.handle = handle
|
|
280
|
+
try:
|
|
281
|
+
for name, value in (('snaplen', 2048), ('promisc', 0), ('timeout', 10), ('immediate_mode', 1)):
|
|
282
|
+
if getattr(self.lib, 'pcap_set_' + name)(handle, value) != 0:
|
|
283
|
+
self._error()
|
|
284
|
+
status = self.lib.pcap_activate(handle)
|
|
285
|
+
if status in (-8, -11):
|
|
286
|
+
raise PermissionError(self.lib.pcap_geterr(handle).decode(errors='replace'))
|
|
287
|
+
if status < 0:
|
|
288
|
+
self._error()
|
|
289
|
+
if self.lib.pcap_datalink(handle) != 1:
|
|
290
|
+
raise RuntimeError(MESSAGES['pcap_link'])
|
|
291
|
+
if self.lib.pcap_setnonblock(handle, 1, error) != 0:
|
|
292
|
+
raise RuntimeError(MESSAGES['pcap_nonblock'])
|
|
293
|
+
program = _BpfProgram()
|
|
294
|
+
if self.lib.pcap_compile(handle, ctypes.byref(program), b'ether proto 0x88a4', 1, 0xFFFFFFFF) != 0:
|
|
295
|
+
self._error()
|
|
296
|
+
try:
|
|
297
|
+
if self.lib.pcap_setfilter(handle, ctypes.byref(program)) != 0:
|
|
298
|
+
self._error()
|
|
299
|
+
finally:
|
|
300
|
+
self.lib.pcap_freecode(ctypes.byref(program))
|
|
301
|
+
self.fd = self.lib.pcap_get_selectable_fd(handle)
|
|
302
|
+
except BaseException:
|
|
303
|
+
self.close()
|
|
304
|
+
raise
|
|
305
|
+
|
|
306
|
+
def _error(self):
|
|
307
|
+
reason = self.lib.pcap_geterr(self.handle)
|
|
308
|
+
raise OSError(reason.decode(errors='replace') if reason else 'libpcap')
|
|
309
|
+
|
|
310
|
+
def receive(self, deadline):
|
|
311
|
+
while time.monotonic() < deadline:
|
|
312
|
+
header = ctypes.POINTER(_PcapHeader)()
|
|
313
|
+
packet = ctypes.POINTER(ctypes.c_ubyte)()
|
|
314
|
+
result = self.lib.pcap_next_ex(self.handle, ctypes.byref(header), ctypes.byref(packet))
|
|
315
|
+
if result == 1:
|
|
316
|
+
return ctypes.string_at(packet, header.contents.caplen)
|
|
317
|
+
if result < 0:
|
|
318
|
+
self._error()
|
|
319
|
+
remaining = deadline - time.monotonic()
|
|
320
|
+
if remaining <= 0:
|
|
321
|
+
break
|
|
322
|
+
if self.fd >= 0:
|
|
323
|
+
select.select([self.fd], [], [], min(remaining, 0.01))
|
|
324
|
+
else:
|
|
325
|
+
time.sleep(min(remaining, 0.005))
|
|
326
|
+
return None
|
|
327
|
+
|
|
328
|
+
def send(self, frame):
|
|
329
|
+
buffer = ctypes.create_string_buffer(frame)
|
|
330
|
+
if self.lib.pcap_inject(self.handle, buffer, len(frame)) != len(frame):
|
|
331
|
+
self._error()
|
|
332
|
+
|
|
333
|
+
def close(self):
|
|
334
|
+
if self.handle:
|
|
335
|
+
self.lib.pcap_close(self.handle)
|
|
336
|
+
self.handle = None
|
|
337
|
+
|
|
338
|
+
|
|
339
|
+
def _open_interface(ifname):
|
|
340
|
+
return _PacketSocket(ifname) if sys.platform.startswith('linux') else _PcapSocket(ifname)
|
|
341
|
+
|
|
342
|
+
|
|
343
|
+
def _inspect(record, probe):
|
|
344
|
+
connection = _open_interface(record['ifname'])
|
|
345
|
+
try:
|
|
346
|
+
deadline = time.monotonic() + OBSERVE_S
|
|
347
|
+
while time.monotonic() < deadline:
|
|
348
|
+
frame = connection.receive(deadline)
|
|
349
|
+
if frame is not None and _is_ethercat(frame):
|
|
350
|
+
record.update(state='observed', method='passive')
|
|
351
|
+
return
|
|
352
|
+
record.update(state='quiet', method='passive')
|
|
353
|
+
if not probe:
|
|
354
|
+
return
|
|
355
|
+
request = build_probe(b'\x02' + secrets.token_bytes(5), secrets.randbelow(256), secrets.randbelow(65536))
|
|
356
|
+
deadline = time.monotonic() + PROBE_S
|
|
357
|
+
connection.send(request)
|
|
358
|
+
while time.monotonic() < deadline:
|
|
359
|
+
frame = connection.receive(deadline)
|
|
360
|
+
if frame is None:
|
|
361
|
+
continue
|
|
362
|
+
count = parse_reply(frame, request)
|
|
363
|
+
if count is not None and time.monotonic() <= deadline:
|
|
364
|
+
record.update(state='responded', method='brd_type', count=count)
|
|
365
|
+
return
|
|
366
|
+
if _is_ethercat(frame) and frame != request and frame[6:12] != request[6:12]:
|
|
367
|
+
record.update(state='observed', method='passive')
|
|
368
|
+
return
|
|
369
|
+
record.update(state='quiet', method='brd_type')
|
|
370
|
+
finally:
|
|
371
|
+
connection.close()
|
|
372
|
+
|
|
373
|
+
|
|
374
|
+
def scan_interfaces(*, probe=False, ifname=None):
|
|
375
|
+
"""列网口并有界观察;probe 显式允许在未观察到主站的候选口发一次 BRD。"""
|
|
376
|
+
issues = []
|
|
377
|
+
try:
|
|
378
|
+
records = enumerate_interfaces(ifname)
|
|
379
|
+
except (OSError, RuntimeError, AttributeError) as error:
|
|
380
|
+
return [], [{'via': 'ecat', 'state': 'unavailable',
|
|
381
|
+
'message': MESSAGES['list_failed'].format(reason=error), 'ifname': ifname}]
|
|
382
|
+
if ifname is not None and not records:
|
|
383
|
+
return [], [{'via': 'ecat', 'state': 'unavailable',
|
|
384
|
+
'message': MESSAGES['missing_interface'].format(ifname=ifname), 'ifname': ifname}]
|
|
385
|
+
for record in records:
|
|
386
|
+
if not record['eligible']:
|
|
387
|
+
record['state'] = 'down' if not record['up'] else 'excluded'
|
|
388
|
+
if record['reason'] == 'classification_unknown':
|
|
389
|
+
issues.append({'via': 'ecat', 'state': 'unavailable', 'ifname': record['ifname'],
|
|
390
|
+
'message': MESSAGES['classification_unknown'].format(ifname=record['ifname'])})
|
|
391
|
+
continue
|
|
392
|
+
try:
|
|
393
|
+
_inspect(record, probe)
|
|
394
|
+
except (OSError, RuntimeError) as error:
|
|
395
|
+
denied = isinstance(error, PermissionError) or getattr(error, 'errno', None) in (errno.EPERM, errno.EACCES)
|
|
396
|
+
state = 'permission' if denied else 'unavailable'
|
|
397
|
+
record['state'] = state
|
|
398
|
+
issues.append({'via': 'ecat', 'state': state, 'ifname': record['ifname'],
|
|
399
|
+
'message': MESSAGES['permission' if denied else 'access'].format(
|
|
400
|
+
ifname=record['ifname'], reason=error)})
|
|
401
|
+
return records, issues
|
ehatool/ecat_probe.toml
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
# EtherCAT 网口发现只使用宿主与 ESC 协议事实。
|
|
2
|
+
[messages]
|
|
3
|
+
unsupported = "当前系统不支持 EtherCAT 原始网络发现"
|
|
4
|
+
missing_interface = "没有找到指定网卡 {ifname}"
|
|
5
|
+
permission = "网卡 {ifname} 的原始网络访问被拒绝,请检查 AF_PACKET/BPF 权限({reason})"
|
|
6
|
+
access = "无法访问网卡 {ifname}({reason})"
|
|
7
|
+
list_failed = "无法枚举 EtherCAT 网卡({reason})"
|
|
8
|
+
pcap_missing = "未找到系统 libpcap"
|
|
9
|
+
pcap_failure = "libpcap 操作失败({reason})"
|
|
10
|
+
pcap_link = "网卡捕获格式不是 Ethernet"
|
|
11
|
+
pcap_nonblock = "libpcap 不支持本发现器需要的非阻塞读取"
|
|
12
|
+
unsupported_link = "网卡不是可自动探测的物理有线 Ethernet 接口"
|
|
13
|
+
down = "网卡未启用或链路已断开"
|
|
14
|
+
classification_unknown = "系统未将网卡 {ifname} 识别为物理有线接口,请核实系统网卡类型及驱动;当前接口无法用于自动探测"
|