ファイル転送 (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、フォールバック(クラスレベル) 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_*。