跳到主要内容

文件传输 (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#PythonJavaC++RustC
OpcUaFileOpcUaFileOpcUaFileOpcUaFileOpcUaFileDarraUa_File_*
DownloadTodownload_todownloadToDownloadTodownload_toDarraUa_File_DownloadTo
UploadFromupload_fromuploadFromUploadFromupload_fromDarraUa_File_UploadFrom

下一步