跳到主要内容

文件传输 (OpcUaFile)

概述​

OPC UA Part 5 §10 FileType (i=11575) 暴露 6 个 Method。SDK 封装为 OpcUaFile 类型, RAII 自动管理 close。

API​

方法 / 字段类别读写说明
OpcUaFile::new(&ua, file_node_id)构造—绑定, 直接返回 Self (非 Result)
file.is_open()方法读bool
file.file_handle()方法读u32
file.file_node_id()方法读&str
file.open(mode)方法写返回 StatusCode
file.read(length)方法读返回 (StatusCode, Vec<u8>) 元组
file.write(bytes)方法写返回 StatusCode
file.close()方法写返回 StatusCode (Drop 自动)
file.get_position()方法读返回 (StatusCode, u64)
file.set_position(pos)方法写返回 StatusCode
file.download_to(path, progress)高层读返回 StatusCode
file.upload_from(path, progress)高层写返回 StatusCode

open / close / read / write / download_to / upload_from / get_position / set_position 全部是 &mut self, 必须 let mut file = ...。返回值都是裸 StatusCode 或元组, 不是 Result, 不能加 ?。

download_to / upload_from 的 path 是 &std::path::Path (不是 &str), progress 是 Option<Box<dyn FnMut(u64, u64) + Send>> (不是裸闭包)。download_to 的 total 恒为 0 (size 子节点需要额外封装, 当前简化), 回调里算百分比必须先判 total > 0, 否则整数除零 panic。

相关结构:

pub struct FileOpenMode(pub u8);   // newtype

impl FileOpenMode {
pub const READ: FileOpenMode = FileOpenMode(0x01); // 读
pub const WRITE: FileOpenMode = FileOpenMode(0x02); // 写
pub const ERASE_EXISTING: FileOpenMode = FileOpenMode(0x04); // 清空
pub const APPEND: FileOpenMode = FileOpenMode(0x08); // 追加

pub fn bits(self) -> u8;
pub fn contains(self, flag: FileOpenMode) -> bool;
}

impl std::ops::BitOr for FileOpenMode { ... } // FileOpenMode::WRITE | FileOpenMode::ERASE_EXISTING

常量是 FileOpenMode 类型, 不是 u8; 组合用 |。

代码示例​

use darra_opcua::{FileOpenMode, OpcUaFile, Session};
use std::path::Path;

fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut ua = Session::new("opc.tcp://device:4840")?;
ua.connect()?;

// 1) 一键下载固件 (Drop 自动 close)
{
let mut file = OpcUaFile::new(&ua, "ns=2;s=Firmware.Image");
println!("opened = {}, handle = {}", file.is_open(), file.file_handle());

let rc = file.download_to(
Path::new(r"C:\dl\firmware.bin"),
Some(Box::new(|done, total| {
// download_to 的 total 恒为 0, 必须先判再除
if total > 0 {
print!("\r{}% ({}/{})", done * 100 / total, done, total);
} else {
print!("\r{} bytes", done);
}
})),
);
if !rc.is_good() { eprintln!("\n下载失败: {:?}", rc); }
}

// 2) 一键上传配方
{
let mut f2 = OpcUaFile::new(&ua, "ns=2;s=Recipe.Current");
let rc = f2.upload_from(Path::new(r"C:\recipes\new.csv"), None);
if !rc.is_good() { eprintln!("上传失败: {:?}", rc); }
}

// 3) 手动流式读
{
let mut f3 = OpcUaFile::new(&ua, "ns=2;s=Logs.Current");
let rc = f3.open(FileOpenMode::READ);
if !rc.is_good() { eprintln!("打开失败: {:?}", rc); }
loop {
let (r, chunk) = f3.read(4096);
if !r.is_good() || chunk.is_empty() { break; }
process_chunk(&chunk);
}
// f3 离开作用域时 Drop 自动 close
}

// 4) 组合打开模式
{
let mut f4 = OpcUaFile::new(&ua, "ns=2;s=Recipe.New");
let rc = f4.open(FileOpenMode::WRITE | FileOpenMode::ERASE_EXISTING);
if rc.is_good() {
f4.write(b"node,value\n");
let (_rc, pos) = f4.get_position();
println!("pos = {}", pos);
}
}
Ok(())
}

实现说明​

  • 块大小默认 4 KB
  • ByteString 走 Vec<u8>
  • Method NodeId 解析: 优先 TranslateBrowsePaths, fallback 类级 NodeId

最佳实践​

  • 用 RAII 管理生命周期 (Drop 自动 close)
  • 大文件分段重试
  • 不要对同一个文件节点建两个 OpcUaFile 并发读写 — 服务端句柄互不知情, 且 &mut self 只约束单个实例的借用, 不约束跨实例

跨语言对照​

C#PythonJavaC++RustC
OpcUaFileOpcUaFileOpcUaFileOpcUaFileOpcUaFileDarraUa_OpcUaFile_New / _Free
DownloadTodownload_todownloadToDownloadTodownload_toDarraUa_OpcUaFile_DownloadTo

C 的家族名是 DarraUa_OpcUaFile_*(_New / _Free / _Open / _Close / _Read / _Write / _GetPosition / _SetPosition / _Size / _OpenCount / _Writable / _UserWritable),不是 DarraUa_File_*。

下一步​