파일 전송 (OpcUaFile)
개요
OPC UA Part 5 §10 FileType (i=11575) 6개의 메서드를 노출합니다.SDK OpcUaFile 유형으로 캡슐화되며, close는 자동으로 RAII 관리됩니다.
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 반환 (자동 드롭) |
| 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을 확인해야 하며, 그렇지 않으면 정수 영으로 나누어 패닉이 발생합니다.
관련 구조:
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 자동 닫기)
{
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이 자동으로 닫힘
}
// 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 관리 (드롭 시 자동 닫기)
- 대용량 파일 분할 재시도
- 동일한 파일 노드에 대해 두 개의 동시
OpcUaFile읽기/쓰기 작업을 생성하지 마십시오 — 서버 측 핸들 간에는 상호 인식이 없으며, 단일 인스턴스의 대여만&mut self제한하고 인스턴스 간 대여는 제한하지 않습니다.
다국어 대조
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | DarraUa_OpcUaFile_New / _Free |
| DownloadTo | download_to | downloadTo | DownloadTo | download_to | DarraUa_OpcUaFile_DownloadTo |
C의 성은 DarraUa_OpcUaFile_*(_New / _Free / _Open / _Close / _Read / _Write / _GetPosition / _SetPosition / _Size / _OpenCount / _Writable / _UserWritable), 아니다 DarraUa_File_*.