文件传输 (OpcUaFile)
概述
OPC UA Part 5 §10 FileType (i=11575) 标准对象暴露 Open / Read / Write / Close / GetPosition / SetPosition 6 个 Method, SDK 封装为 OpcUaFile 类, 适用固件升级 / 配方传输 / 文件镜像。
API
| 方法 / 属性 | 类别 | 读写 | 说明 |
|---|---|---|---|
| OpcUaFile(ua, file_node_id) | 构造 | — | 绑定到 FileType 实例 (实例对象 NodeId, 不是类型 NodeId) |
| file.size | 属性 | 读 | 文件大小 (UInt64); 读失败返回 0 |
| file.writable | 属性 | 读 | 服务端层面是否可写; 失败返回 False |
| file.user_writable | 属性 | 读 | 当前用户是否可写; 失败返回 False |
| file.open_count | 属性 | 读 | 当前打开的 fileHandle 数量; 失败返回 0 |
| file.is_open | 属性 | 读 | 本地是否已 open |
| file.file_handle | 属性 | 读 | 服务端分配的 fileHandle (未 open 时为 0) |
| file.file_node_id | 属性 | 读 | 绑定的 FileType 实例 NodeId |
| file.open(mode) | 方法 | 写 | 打开; 已打开再调直接返回 StatusCode.Bad, 不发 RPC |
| file.read(length) | 方法 | 读 | 返回 (StatusCode, bytes); b"" 表示到末尾 |
| file.write(data) | 方法 | 写 | 写字节; None/空视作 no-op 返回 Good |
| file.get_position() | 方法 | 读 | 返回 (StatusCode, int) 当前读写位置 |
| file.set_position(pos) | 方法 | 写 | 跳转读写位置 |
| file.close() | 方法 | 写 | 关闭; 未打开时静默返回 Good |
| file.download_to(local_path, progress) | 高层 | 读 | 整文件下载, 返回 StatusCode |
| file.upload_from(local_path, progress) | 高层 | 写 | 整文件上传, 返回 StatusCode |
| file.dispose() | 资源 | — | 关闭未关闭的句柄, 不抛异常 |
ProgressCallback = Callable[[int, int], None] # progress(done, total)
class OpcUaFile:
def __init__(self, ua: "OpcUaSession", file_node_id: str): ...
def open(self, mode: FileOpenMode) -> StatusCode: ...
def close(self) -> StatusCode: ...
def read(self, length: int) -> Tuple[StatusCode, bytes]: ...
def write(self, data: Optional[bytes]) -> StatusCode: ...
def get_position(self) -> Tuple[StatusCode, int]: ...
def set_position(self, pos: int) -> StatusCode: ...
def download_to(self, local_path: str,
progress: Optional[ProgressCallback] = None) -> StatusCode: ...
def upload_from(self, local_path: str,
progress: Optional[ProgressCallback] = None) -> StatusCode: ...
| 参数 | 默认 | 说明 |
|---|---|---|
| ua | — | 已连接的 OpcUaSession; None 抛 ValueError |
| file_node_id | — | FileType 实例对象 NodeId; 空串抛 ValueError |
| mode | — | FileOpenMode 标志位, 可按位或 |
| length | — | <= 0 时直接返回 (StatusCode.Good, b"") |
| progress | None | progress(done, total); total = 0 表示服务端未提供 Size |
相关结构:
class FileOpenMode(IntFlag):
READ = 0x01 # 读
WRITE = 0x02 # 写
ERASE_EXISTING = 0x04 # 清空 (与 WRITE 组合)
APPEND = 0x08 # 追加
代码示例
from darra_opcua import DarraOpcUa, OpcUaFile, FileOpenMode, StatusCode
with DarraOpcUa("opc.tcp://device:4840") as ua:
ua.connect()
# 1) 一键下载固件
with OpcUaFile(ua, "ns=2;s=Firmware.Image") as f:
print(f"Size = {f.size} bytes")
def on_progress(done, total):
pct = f"{done * 100 // total}%" if total else "?%"
print(f"\r{pct} ({done}/{total})", end="")
rc = f.download_to(r"C:\dl\firmware.bin", progress=on_progress)
if rc != StatusCode.Good:
print(f"\n下载失败: {rc}")
# 2) 一键上传配方
with OpcUaFile(ua, "ns=2;s=Recipe.Current") as f2:
rc = f2.upload_from(r"C:\recipes\new.csv")
# 3) 手动流式读
with OpcUaFile(ua, "ns=2;s=Logs.Current") as f3:
f3.open(FileOpenMode.READ)
while True:
st, chunk = f3.read(4096)
if st != StatusCode.Good or not chunk:
break
process_chunk(chunk)
f3.close()
实现说明
- 块大小固定 4 KB,
download_to/upload_from都按此分片 - ByteString 无损传输, 保留 0x00-0xFF 全字节
- Method 定位: 自动解析文件实例的 Method; 服务端只暴露标准 FileType 类级 Method 时同样可用
download_to流式读整文件写本地并必定close(); 短读视为 EOF, 文件中间短读会提前截断upload_from以清空后写入方式上传 (会清空服务端原文件内容), 结束必定close()- 高层方法在
finally里必定close(), 中途失败也不会漏句柄
实现限制
- 所有方法失败时返回
StatusCode, 不抛异常; 服务端返回的非枚举状态码会被归一 (不在StatusCode枚举内的码退化为StatusCode.Bad) - 没有断点续传参数 —— 要续传得自己用
get_position/set_position接着搬 - 同一个
OpcUaFile实例不要并发调用 (一个实例只对应一个服务端句柄)
最佳实践
- 始终用
with语句, 退出时自动dispose()→close(); 漏 close 会泄漏服务端句柄 - 大文件想分段 / 续传: 记住
get_position()的位置, 重连后set_position(pos)再接着read/write - 不要并发同一个 file_handle
跨语言对照
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | DarraUa_OpcUaFile_* |
| DownloadTo | download_to | downloadTo | DownloadTo | download_to | DarraUa_OpcUaFile_DownloadTo |
| UploadFrom | upload_from | uploadFrom | UploadFrom | upload_from | DarraUa_OpcUaFile_UploadFrom |
| Open / Close | open / close | open / close | Open / Close | open / close | DarraUa_OpcUaFile_Open/_Close |
| Read / Write | read / write | read / write | Read / Write | read / write | DarraUa_OpcUaFile_Read/_Write |
| GetPosition / SetPosition | get_position / set_position | getPosition / setPosition | GetPosition / SetPosition | get_position / set_position | DarraUa_OpcUaFile_GetPosition/_SetPosition |
进度回调两侧形态不同: C# 是 IProgress<(ulong done, ulong total)>, Python 是 progress(done, total) 可调用对象。