跳到主要内容

文件传输 (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"")
progressNoneprogress(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#PythonJavaC++RustC
OpcUaFileOpcUaFileOpcUaFileOpcUaFileOpcUaFileDarraUa_OpcUaFile_*
DownloadTodownload_todownloadToDownloadTodownload_toDarraUa_OpcUaFile_DownloadTo
UploadFromupload_fromuploadFromUploadFromupload_fromDarraUa_OpcUaFile_UploadFrom
Open / Closeopen / closeopen / closeOpen / Closeopen / closeDarraUa_OpcUaFile_Open/_Close
Read / Writeread / writeread / writeRead / Writeread / writeDarraUa_OpcUaFile_Read/_Write
GetPosition / SetPositionget_position / set_positiongetPosition / setPositionGetPosition / SetPositionget_position / set_positionDarraUa_OpcUaFile_GetPosition/_SetPosition

进度回调两侧形态不同: C# 是 IProgress<(ulong done, ulong total)>, Python 是 progress(done, total) 可调用对象。

下一步​