Skip to main content

File Transfer (OpcUaFile)

Overview​

OPC UA Part 5 §10 FileType (i=11575) exposes 6 methods. The SDK wraps them as an OpcUaFile type; RAII manages closing automatically.

API​

Methods / FieldsCategoryReading and WritingNote
OpcUaFile::new(&ua, file_node_id)Structure—Binding, returns Self directly (not Result)
file.is_open()MethodsReadbool
file.file_handle()MethodsReadu32
file.file_node_id()MethodsRead&str
file.open(mode)MethodsWriteReturns StatusCode
file.read(length)MethodsReadReturns a tuple (StatusCode, Vec<u8>)
file.write(bytes)MethodsWriteReturns StatusCode
file.close()MethodsWriteReturns StatusCode (Auto-Drop)
file.get_position()MethodsReadReturns (StatusCode, u64)
file.set_position(pos)MethodsWriteReturns StatusCode
file.download_to(path, progress)High-levelReadReturns StatusCode
file.upload_from(path, progress)High-levelWriteReturns StatusCode

open / close / read / write / download_to / upload_from / get_position / set_position All of them are &mut self, Must let mut file = .... Return values are either raw StatusCode or tuples, If it's not "Result," you can't add it. ?。

download_to / upload_from path is &std::path::Path (not &str), progress is Option<Box<dyn FnMut(u64, u64) + Send>> (not a bare closure).download_to The total is always 0 (The size child node requires additional wrapping; this has been simplified for now.) When calculating percentages in the callback, you must first check for validity total > 0; otherwise, dividing an integer by zero will cause a panic.

Related Structures:

pub struct FileOpenMode(pub u8);   // newtype

impl FileOpenMode {
pub const READ: FileOpenMode = FileOpenMode(0x01); // Read
pub const WRITE: FileOpenMode = FileOpenMode(0x02); // Write
pub const ERASE_EXISTING: FileOpenMode = FileOpenMode(0x04); // Clear
pub const APPEND: FileOpenMode = FileOpenMode(0x08); // Add

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

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

A constant is FileOpenMode Type, not u8; used in combinations |.

Code Example​

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) One-click firmware download (Drop automatically closes)
{
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` is always 0 — must check before dividing.
if total > 0 {
print!("\r{}% ({}/{})", done * 100 / total, done, total);
} else {
print!("\r{} bytes", done);
}
})),
);
if !rc.is_good() { eprintln!("\n下载失败: {:?}", rc); }
}

// 2) Upload recipes with one click
{
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) Manual streaming read
{
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 automatically closes when it leaves the scope
}

// 4) Combined Open Mode
{
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(())
}

Implementation Notes​

  • Default block size 4 KB
  • ByteString Go Vec<u8>
  • Method NodeId Analysis: Priority TranslateBrowsePaths, fallback at the class level NodeId

Best Practices​

  • Use Lifecycle RAII Management (Drop automatically closes)
  • Retrying in Segments for Large Files
  • Do not create two concurrent OpcUaFile read/write operations on the same file node—server handles are unaware of each other, and borrowing is restricted to a single instance &mut self only; it is not restricted across instances.

Cross-Language Comparison​

C#PythonJavaC++RustC
OpcUaFileOpcUaFileOpcUaFileOpcUaFileOpcUaFileDarraUa_OpcUaFile_New / _Free
DownloadTodownload_todownloadToDownloadTodownload_toDarraUa_OpcUaFile_DownloadTo

C's family name is DarraUa_OpcUaFile_*(_New / _Free / _Open / _Close / _Read / _Write / _GetPosition / _SetPosition / _Size / _OpenCount / _Writable / _UserWritable), not DarraUa_File_*.

Next Step​