본문으로 건너뛰기

BrowseCrawler — 전체 트리 오프라인 크롤링

개요​

IDE / HMI 온라인 상태에서는 종종 AddressSpace 서브트리를 로컬로 불러와야 하며, 이후 노드 검색 시 다시 요청할 필요가 없습니다 Browse RPC.BrowseCrawler 큐를 BFS 사용하여 순회하고, 이중 보호(max_depth + max_nodes)를 통해 오류를 방지합니다.

API​

구성원분류읽기 및 쓰기설명
BrowseCrawler(ua, max_depth, max_nodes, node_class_filter)구조—크롤러 구축
await crawler.crawl(root_node_id, progress_callback)방법읽기비동기 BFS, 반환 CrawlResult
CrawlNode.node_id / display_name / browse_name / node_class / parent_node_id속성읽기개별 노드 설명
CrawlResult.all_nodes속성읽기평면 노드 목록 (List[CrawlNode], BFS 순서)
CrawlResult.children_by_parent속성읽기부모 NodeId → 자식 NodeId 목록 (Dict[str, List[str]], 실제로 자식이 있는 부모만 포함)
CrawlResult.crawled_at속성읽기크롤링을 시작한 시간 UTC (datetime)
CrawlResult.elapsed속성읽기총 소요 시간 (timedelta)
class BrowseCrawler:
def __init__(self,
ua: "OpcUaSession",
max_depth: int = 10,
max_nodes: int = 100_000,
node_class_filter: NodeClass = NodeClass.Unspecified): ...

async def crawl(self,
root_node_id: Optional[str] = None,
progress_callback: Optional[ProgressCallback] = None) -> CrawlResult: ...

# 진행 상황 콜백 서명
ProgressCallback = Callable[[int, Optional[str]], None] # progress(count, current_nid)
매개변수기본값설명
ua—연결됨 OpcUaSession; 전송 None 던지기 ValueError
max_depth10최대 재귀 깊이, <= 0 생략 ValueError
max_nodes100_000최대 노드 수, <= 0 제거 ValueError
node_class_filterNodeClass.Unspecified지정된 노드에만 NodeClass 기록합니다; Unspecified = 전체.필터링은 순회 과정에 영향을 미치지 않습니다. — BFS 여전히 모든 계층적 자식 노드를 모두 순회하지만, 결과는 기록하지 않습니다.
root_node_idNone시작점 NodeId; 비어 있으면 자동으로 ( wkn.OBJECTS_FOLDER i=85)를 사용
progress_callbackNoneprogress(count, current_nid); 100개의 노드를 기록할 때마다 한 번씩 보고하고, 크롤링이 끝날 때 마지막으로 한 번 더 보고합니다 progress(总数, None). 콜백에서 예외가 발생하더라도 무시되며, 크롤링에는 영향을 미치지 않습니다.

반환 CrawlResult.CrawlNode 필드: node_id / display_name / browse_name / node_class / parent_node_id (마지막 두 개는 다음과 같을 수 있음 None).

코드 예시​

import asyncio
from darra_opcua import DarraOpcUa, BrowseCrawler, NodeClass, wkn # 모듈명 darra_opcua

async def main():
with DarraOpcUa("opc.tcp://localhost:4840") as ua:
ua.connect()

# 1) 나무 전체를 기어오르다 ObjectsFolder
crawler = BrowseCrawler(ua, max_depth=8, max_nodes=50_000)

def on_progress(count, current_nid):
print(f"\r已抓 {count} 个, 当前 {current_nid}", end="")

result = await crawler.crawl(wkn.OBJECTS_FOLDER, progress_callback=on_progress)

print(f"\n共 {len(result.all_nodes)} 节点, 耗时 {result.elapsed.total_seconds():.1f}s")
print(f"开始于 {result.crawled_at}")

# 2) Variable 노드만 (필터링은 쓰기 작업에만 영향을 미치며, 탐색에는 영향을 미치지 않음)
c2 = BrowseCrawler(ua, node_class_filter=NodeClass.Variable)
r2 = await c2.crawl("ns=2;s=Boilers")
for n in r2.all_nodes:
print(f" {n.browse_name} ({n.node_id})")

# 3) 부자 뷰
for parent, kids in result.children_by_parent.items():
print(f"{parent} -> {len(kids)} 个子节点")

asyncio.run(main())

구현상의 제약​

  • 취소 기능이 없음 — crawl() 단 root_node_id / progress_callback 두 개의 인자만 있으며, 취소 인자는 전혀 없습니다. 크롤링이 일단 await 시작되면 자연스럽게 종료됩니다 (전체 순회 완료 / 도달 max_depth / 도달 max_nodes)."중단"을 하려면 호출 측에서 직접 판단하여 미리 해야 합니다. — return 예를 들어 를 crawl 에 넣고 asyncio.create_task, 중지하고 싶을 때 task 결과를 버리면 더 이상 되지 않습니다 await. 규모가 제한된 상황에서는 직접 max_depth / max_nodes 로 처리합니다.
  • 매번 Browse 탐색할 때 ua.browse_safe, 단일 노드에서 오류가 발생하면 해당 노드만 건너뛰고 전체 크롤링은 중단되지 않습니다.
  • 진행 상황 콜백에서 발생한 예외가 SDK 흡수되어, 크롤링에 영향을 미치지 않으며 다른 콜백에도 영향을 주지 않습니다.
  • 100개의 노드마다 한 번씩 진행 상황을 보고하며, 그 사이에는 세부적인 진행 상황 정보가 제공되지 않습니다.
  • 노드 그래프는 루프를 허용하며, ‘액세스한 노드’를 사용하여 중복을 제거합니다 set . 중복 노드는 결과에 한 번만 포함됩니다 NodeId .
  • 크롤링 작업은 스레드 풀에서 실행되므로, 호출 측의 이벤트 루프를 차단하지 않습니다.

모범 사례​

  • root로 제한하며, ( i=84 Root)에서 시작하여 전체 트리를 탐색하지 마십시오.
  • / max_depth max_nodes 크기 제한 —— 이는 크롤링을 조기에 종료할 수 있는 유일한 방법입니다 (취소 매개변수는 없습니다).
  • 시작 시 한 번만 크롤링하고, 이후에는 로컬 캐시에서 조회합니다.
  • 을 사용하여 쓰기 node_class_filter 결과의 노드 유형을 제어함으로써 메모리 사용량을 줄입니다.

다국어 대조​

C#PythonJavaC++RustC
BrowseCrawlerBrowseCrawlerBrowseCrawlerBrowseCrawlerBrowseCrawlerDarraUa_Session_CrawlAddressSpace
CrawlAsync(rootNodeId, IProgress, CancellationToken)crawl(root_node_id, progress_callback)crawlAsyncCrawlAsynccrawlDarraUa_Session_CrawlAddressSpace

C의 진입점은 단일 함수이며 DarraUa_Session_CrawlAddressSpace(session, config, on_node, ctx), 이에 수반되는 DarraUa_CrawlerConfig(DarraUa_CrawlerConfig_Init 초기화) / DarraUa_CrawlNode / DarraUa_OnCrawlNode,이 DarraUa_BrowseCrawler_* 가문은 없다; 위의 두 줄은 C 측에서 동일한 함수입니다.

취소 기능의 양쪽이 다릅니다: C#에는 CrawlAsync CancellationToken, Python에는 취소 매개변수가 전혀 crawl 없습니다..

다음 단계​