File Transfer (OpcUaFile)
Overview
OPC UA Part 5 §10 FileType (i=11575) is a standard object exposing 6 methods (Open / Read / Write / Close / GetPosition / SetPosition); the SDK wraps them as an OpcUaFile class, suitable for firmware upgrades, recipe transfer and file mirroring.
API
| Methods / Properties | Category | Reading and Writing | Note |
|---|---|---|---|
| OpcUaFile(ua, file_node_id) | Structure | — | Bound to an instance FileType (an instance object NodeId, not a type NodeId) |
| file.size | Properties | Read | File size (UInt64); Returns 0 if the read operation fails |
| file.writable | Properties | Read | Is writing allowed at the server level? Returns False on failure. |
| file.user_writable | Properties | Read | Whether the current user has write access; returns False on failure |
| file.open_count | Properties | Read | The number of currently open file handles; returns 0 on failure |
| file.is_open | Properties | Read | Is it already open locally? |
| file.file_handle | Properties | Read | The file handle assigned by the server (0 when not open) |
| file.file_node_id | Properties | Read | Bound instances FileType NodeId |
| file.open(mode) | Methods | Write | Open; If already open StatusCode.Bad, simply return without sending anything. RPC |
| file.read(length) | Methods | Read | Returns (StatusCode, bytes); b"" indicates the end |
| file.write(data) | Methods | Write | Write a byte; None/ An empty value is treated as a no-op and returns "Good" |
| file.get_position() | Methods | Read | Returns the current (StatusCode, int) read/write position |
| file.set_position(pos) | Methods | Write | Jump to Read/Write Position |
| file.close() | Methods | Write | Close; returns "Good" silently if not open |
| file.download_to(local_path, progress) | High-level | Read | Download the entire file, Returns StatusCode |
| file.upload_from(local_path, progress) | High-level | Write | Upload the entire file, then return StatusCode |
| file.dispose() | Resources | — | Close any open handles without throwing an exception |
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: ...
| Parameters | Default | Note |
|---|---|---|
| ua | — | Connected OpcUaSession; None Throw ValueError |
| file_node_id | — | FileType Instance Object NodeId; Empty string exception ValueError |
| mode | — | FileOpenMode Flags, bitwise OR |
| length | — | <= 0 Returns immediately (StatusCode.Good, b"") |
| progress | None | progress(done, total); total = 0 Indicates that the server did not provide the Size |
Related Structures:
class FileOpenMode(IntFlag):
READ = 0x01 # Read
WRITE = 0x02 # Write
ERASE_EXISTING = 0x04 # Clear (in combination WRITE with )
APPEND = 0x08 # Add
Code Example
from darra_opcua import DarraOpcUa, OpcUaFile, FileOpenMode, StatusCode
with DarraOpcUa("opc.tcp://device:4840") as ua:
ua.connect()
# 1) One-click firmware download
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) Upload recipes with one click
with OpcUaFile(ua, "ns=2;s=Recipe.Current") as f2:
rc = f2.upload_from(r"C:\recipes\new.csv")
# 3) Manual streaming read
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()
Implementation Notes
- Fixed block size 4 KB,
download_to/upload_fromall shards are configured this way - ByteString Lossless transmission, preserved 0x00—0xFF full bytes
- Method Resolution: Automatically resolves the method of a file instance; this also works when the server exposes only standard class-level FileType methods.
download_toRead the entire file in stream mode and write it to the local fileclose(); short reads are treated as such EOF, and short reads in the middle of the file will be truncated early.upload_fromUpload using the "clear and write" method (This will clear the contents of the original file on the server.), The end is certainclose()- The high-level method must be
finallyinclose(), and even if it fails midway, it will not drop any handles.
Implementation Constraints
- Returns when all methods fail
StatusCode, Do not throw exceptions; Non-enumerated status codes returned by the server are normalized (codes not in theStatusCodeenumeration are mapped toStatusCode.Bad). - No resume parameters — you'll have to resume the download yourself
get_position/set_positionKeep moving - Do not make concurrent calls to the same
OpcUaFileinstance (each instance corresponds to only one server handle).
Best Practices
- Always use the statement
with; it automatically when exitingdispose()→close(); Omitting the close statement will cause a server handle leak. - To split a large file into segments or resume an upload: Remember the position
get_position(), thenset_position(pos)resume the upload after reconnectingread/write - Do not access the same file_handle concurrently
Cross-Language Comparison
| C# | Python | Java | C++ | Rust | C |
|---|---|---|---|---|---|
| OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | OpcUaFile | DarraUa_OpcUaFile_* |
| DownloadTo | download_to | downloadTo | DownloadTo | download_to | DarraUa_OpcUaFile_DownloadTo |
| UploadFrom | upload_from | uploadFrom | UploadFrom | upload_from | DarraUa_OpcUaFile_UploadFrom |
| Open / Close | open / close | open / close | Open / Close | open / close | DarraUa_OpcUaFile_Open/_Close |
| Read / Write | read / write | read / write | Read / Write | read / write | DarraUa_OpcUaFile_Read/_Write |
| GetPosition / SetPosition | get_position / set_position | getPosition / setPosition | GetPosition / SetPosition | get_position / set_position | DarraUa_OpcUaFile_GetPosition/_SetPosition |
The two-sided patterns of progress callbacks differ: in C# IProgress<(ulong done, ulong total)>, it is, while in Python, it is a callable progress(done, total) object.