文件传输 (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 实例 |
| file.size | 属性 | 读 | 文件大小 |
| file.writable | 属性 | 读 | 是否可写 |
| file.user_writable | 属性 | 读 | 当前用户可写 |
| file.open_count | 属性 | 读 | 当前打开数 |
| file.open(mode) | 方法 | 写 | 打开 |
| file.read(length) | 方法 | 读 | 读 N 字节 |
| file.write(data) | 方法 | 写 | 写字节 |
| file.close() | 方法 | 写 | 关闭 |
| file.download_to(local_path, progress) | 高层 | 读 | 下载 |
| file.upload_from(local_path, progress) | 高层 | 写 | 上传 |
相关结构:
class FileOpenMode(IntFlag):
READ = 0x01 # 读
WRITE = 0x02 # 写
ERASE_EXISTING = 0x04 # 清空 (与 WRITE 组合)
APPEND = 0x08 # 追加
代码示例
from 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):
print(f"\r{done * 100 // total}% ({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
- ByteString 走 ISO-8859-1 字符串桥接, 无损保留 0x00-0xFF
- Method NodeId 解析: 优先 TranslateBrowsePaths, fallback 类级 NodeId
最佳实践
- 始终用
with语句, 漏 close 会泄漏服务端句柄 - 大文件分段重试, 网络断后续传
- 不要并发同一 file_handle
跨语言对照
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | DarraUa_File_* |
| DownloadTo | download_to | downloadTo | DownloadTo | download_to | DarraUa_File_DownloadTo |
| UploadFrom | upload_from | uploadFrom | UploadFrom | upload_from | DarraUa_File_UploadFrom |