파일 전송 (OpcUaFile)
개요
OPC UA Part 5 §10 FileType (i=11575) 표준 객체는 Open / Read / Write / Close / GetPosition / SetPosition 6개의 메서드를 노출하며, 클래스로 OpcUaFile SDK 캡슐화되어 펌웨어 업그레이드 / 레시피 전송 / 파일 이미징에 적용됩니다.
API
| 메서드 / 속성 | 분류 | 읽기 및 쓰기 | 설명 |
|---|---|---|---|
| OpcUaFile(ua, file_node_id) | 구조 | — | FileType 인스턴스에 바인딩 (인스턴스 객체 NodeId, 타입이 아님 NodeId) |
| file.size | 속성 | 읽기 | 파일 크기 (UInt64); 읽기 실패 시 0을 반환 |
| file.writable | 속성 | 읽기 | 서버 측에서 쓰기가 가능한지 여부; 실패 시 False를 반환 |
| file.user_writable | 속성 | 읽기 | 현재 사용자가 쓰기 권한이 있는지 여부; 실패 시 False를 반환합니다. |
| file.open_count | 속성 | 읽기 | 현재 열려 있는 fileHandle의 개수; 실패 시 0을 반환합니다. |
| file.is_open | 속성 | 읽기 | 이 지역이 이미 열려 있나요? |
| file.file_handle | 속성 | 읽기 | 서버 측에서 할당된 fileHandle (열리지 않은 상태에서는 0) |
| file.file_node_id | 속성 | 읽기 | 바인딩된 FileType 인스턴스 NodeId |
| file.open(mode) | 방법 | 쓰기 | 열기; 이미 열려 있는 경우 다시 호출하면 바로 반환되며 StatusCode.Bad, 전송하지 않음 RPC |
| file.read(length) | 방법 | 읽기 | 반환 (StatusCode, bytes); b"" 끝으로 이동 |
| file.write(data) | 방법 | 쓰기 | 바이트 쓰기; /비어 있으면 no-op로 None간주하여 Good을 반환 |
| file.get_position() | 방법 | 읽기 | 현재 (StatusCode, int) 읽기/쓰기 위치 반환 |
| file.set_position(pos) | 방법 | 쓰기 | 읽기/쓰기 위치로 이동 |
| file.close() | 방법 | 쓰기 | 닫기; 열리지 않은 경우 아무 메시지 없이 Good을 반환합니다. |
| file.download_to(local_path, progress) | 고층 | 읽기 | 전체 파일 다운로드, 반환 StatusCode |
| file.upload_from(local_path, progress) | 고층 | 쓰기 | 전체 파일 업로드, 반환 StatusCode |
| file.dispose() | 자료 | — | 닫히지 않은 핸들을 닫고, 예외를 발생시키지 않습니다. |
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: ...
| 매개변수 | 기본값 | 설명 |
|---|---|---|
| ua | — | 연결됨 OpcUaSession; None 던지기 ValueError |
| file_node_id | — | FileType 인스턴스 객체 NodeId; 빈 문자열 제거 ValueError |
| mode | — | FileOpenMode 플래그 비트, 비트별 논리합 연산 가능 |
| length | — | <= 0 이때 바로 반환 (StatusCode.Good, b"") |
| progress | None | progress(done, total); total = 0 서버에서 Size를 제공하지 않았음을 나타냅니다 |
관련 구조:
class FileOpenMode(IntFlag):
READ = 0x01 # 읽기
WRITE = 0x02 # 쓰기
ERASE_EXISTING = 0x04 # 비우기 (와 WRITE 조합)
APPEND = 0x08 # 추가
코드 예시
from darra_opcua import DarraOpcUa, OpcUaFile, FileOpenMode, StatusCode
with DarraOpcUa("opc.tcp://device:4840") as ua:
ua.connect()
# 1) 원클릭 펌웨어 다운로드
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) 한 번의 클릭으로 레시피 업로드
with OpcUaFile(ua, "ns=2;s=Recipe.Current") as f2:
rc = f2.upload_from(r"C:\recipes\new.csv")
# 3) 수동 스트리밍 읽기
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()
구현 설명
- 블록 크기가 고정됨 4 KB,
download_to/upload_from모두 이 방식으로 분할 - ByteString 무손실 전송, 보존 0x00-0xFF 전체 바이트
- 메서드 위치 지정: 파일 인스턴스의 메서드를 자동으로 분석함; 서버 측에서 표준 FileType 클래스 수준 메서드만 노출하는 경우에도 동일하게 사용 가능
download_to전체 파일을 스트림 방식으로 읽어 로컬에 쓰고 반드시close(); 짧은 읽기는 로컬로 간주되며 EOF, 파일 중간에서 짧은 읽기가 발생하면 조기에 중단됩니다.upload_from지운 후 쓰기 방식으로 업로드 (서버의 원본 파일 내용이 지워집니다.), 끝은 반드시close()- 고수준 방식은
finally에서 반드시close(), 도중에 실패하더라도 핸들이 누락되지 않습니다.
구현상의 제약
- 모든 방법이 실패할 경우
StatusCode,를 반환합니다. 예외를 던지지 않음; 서버에서 반환된 열거형이 아닌 상태 코드는 표준화됩니다(StatusCode열거형에 포함되지 않은 코드는 로 변환됨StatusCode.Bad). - 중단된 파일 다운로드 재개 매개변수가 없습니다 —— 다운로드를 재개하려면 직접
get_position/set_position계속 옮기세요 - 동일한 인스턴스에 대해 동시 호출을 하지
OpcUaFile마십시오 (하나의 인스턴스는 하나의 서버 핸들만 대응합니다).
모범 사례
- 항상
with문장을 사용하고, 종료 시 자동으로dispose()→close(); close를 생략하면 서버 핸들이 누수될 수 있습니다. - 대용량 파일을 여러 번에 나눠 전송하거나 이어서 전송하려면: 의 위치를
get_position()기억해 두었다가, 다시 연결한 후 에서 부터set_position(pos)이어서 전송하세요 /readwrite - 동일한 file_handle을 동시에 사용하지 마십시오.
다국어 대조
| 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 |
진행 상황 콜백의 양쪽 형태가 다릅니다. C#은 IProgress<(ulong done, ulong total)>, Python은 호출 progress(done, total) 가능한 객체입니다.