Skip to main content

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 / PropertiesCategoryReading and WritingNote
OpcUaFile(ua, file_node_id)Structure—Bound to an instance FileType (an instance object NodeId, not a type NodeId)
file.sizePropertiesReadFile size (UInt64); Returns 0 if the read operation fails
file.writablePropertiesReadIs writing allowed at the server level? Returns False on failure.
file.user_writablePropertiesReadWhether the current user has write access; returns False on failure
file.open_countPropertiesReadThe number of currently open file handles; returns 0 on failure
file.is_openPropertiesReadIs it already open locally?
file.file_handlePropertiesReadThe file handle assigned by the server (0 when not open)
file.file_node_idPropertiesReadBound instances FileType NodeId
file.open(mode)MethodsWriteOpen; If already open StatusCode.Bad, simply return without sending anything. RPC
file.read(length)MethodsReadReturns (StatusCode, bytes); b"" indicates the end
file.write(data)MethodsWriteWrite a byte; None/ An empty value is treated as a no-op and returns "Good"
file.get_position()MethodsReadReturns the current (StatusCode, int) read/write position
file.set_position(pos)MethodsWriteJump to Read/Write Position
file.close()MethodsWriteClose; returns "Good" silently if not open
file.download_to(local_path, progress)High-levelReadDownload the entire file, Returns StatusCode
file.upload_from(local_path, progress)High-levelWriteUpload 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: ...
ParametersDefaultNote
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"")
progressNoneprogress(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_from all 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_to Read the entire file in stream mode and write it to the local file close(); short reads are treated as such EOF, and short reads in the middle of the file will be truncated early.
  • upload_from Upload using the "clear and write" method (This will clear the contents of the original file on the server.), The end is certain close()
  • The high-level method must be finally in close(), 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 the StatusCode enumeration are mapped to StatusCode.Bad).
  • No resume parameters — you'll have to resume the download yourself get_position / set_position Keep moving
  • Do not make concurrent calls to the same OpcUaFile instance (each instance corresponds to only one server handle).

Best Practices​

  • Always use the statement with; it automatically when exiting dispose() → 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(), then set_position(pos) resume the upload after reconnecting read / write
  • Do not access the same file_handle concurrently

Cross-Language Comparison​

C#PythonJavaC++RustC
OpcUaFileOpcUaFileOpcUaFileOpcUaFileOpcUaFileDarraUa_OpcUaFile_*
DownloadTodownload_todownloadToDownloadTodownload_toDarraUa_OpcUaFile_DownloadTo
UploadFromupload_fromuploadFromUploadFromupload_fromDarraUa_OpcUaFile_UploadFrom
Open / Closeopen / closeopen / closeOpen / Closeopen / closeDarraUa_OpcUaFile_Open/_Close
Read / Writeread / writeread / writeRead / Writeread / writeDarraUa_OpcUaFile_Read/_Write
GetPosition / SetPositionget_position / set_positiongetPosition / setPositionGetPosition / SetPositionget_position / set_positionDarraUa_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.

Next Step​