Source code for rb_sdk.base

import asyncio
import builtins
import contextlib
import functools
import inspect
import json
import os
import socket
import ssl
import sys
import threading
import urllib.error
import urllib.request
import uuid
from collections.abc import Callable
from typing import TYPE_CHECKING, Any, ClassVar, Literal, TypeVar, overload

from rb_flat_buffers.IPC.CANMessage import CANMessageT
from rb_flat_buffers.IPC.RequestCANConnect import RequestCANConnectT
from rb_flat_buffers.IPC.RequestCANDisconnect import RequestCANDisconnectT
from rb_flat_buffers.IPC.RequestCANTransmit import RequestCANTransmitT
from rb_flat_buffers.IPC.ResponseCANConnect import ResponseCANConnectT
from rb_flat_buffers.IPC.ResponseCANDisconnect import ResponseCANDisconnectT
from rb_flat_buffers.IPC.ResponseCANTransmit import ResponseCANTransmitT
from rb_flat_buffers.muscat.RB_Program_Log import RB_Program_LogT
from rb_flat_buffers.muscat.RB_Program_Log_Type import RB_Program_Log_Type
from rb_log.log import rb_log
from rb_schemas.sdk import FlowManagerArgs
from rb_utils.service_exception import ServiceException
from rb_zenoh.client import (
    FBRootReadable,
    SubscribeDictCallback,
    SubscribeObjCallback,
    SubscribeObjReadable,
    ZenohClient,
)
from rb_zenoh.exception import ZenohNoReply, ZenohTransportError
from rb_zenoh.schema import SubscribeOptions

if TYPE_CHECKING:
    pass

T = TypeVar("T", bound="RBBaseSDK")
TSubObj = TypeVar("TSubObj")
# 로봇 TLS(rb-tls) 검증용 회사 root 인증서(공개 정보). cpp/base.cpp kRobotRootCaPem 과 같아야 한다.
ROBOT_ROOT_CA_PEM = """-----BEGIN CERTIFICATE-----
MIIB8DCCAZegAwIBAgIUUMExSwOHfKJSBejoE/D3SNTwXogwCgYIKoZIzj0EAwIw
RTEZMBcGA1UECgwQUmFpbmJvdyBSb2JvdGljczEoMCYGA1UEAwwfUmFpbmJvdyBS
b2JvdGljcyBEZXZpY2UgUm9vdCBDQTAgFw0yNjExMDIwMzA2NDZaGA8yMDU2MTAy
NTAzMDY0NlowRTEZMBcGA1UECgwQUmFpbmJvdyBSb2JvdGljczEoMCYGA1UEAwwf
UmFpbmJvdyBSb2JvdGljcyBEZXZpY2UgUm9vdCBDQTBZMBMGByqGSM49AgEGCCqG
SM49AwEHA0IABFfNhuiU+XbhKhoF53nPp2hspXfrzUesRS95bBL0ubV9sMTulmFf
yjXRtYDMg2VueSP3D3dfImIQetlg3QV/oB+jYzBhMB0GA1UdDgQWBBRoT1qn57gh
9XvHG2W3JAQMZNEfFDAfBgNVHSMEGDAWgBRoT1qn57gh9XvHG2W3JAQMZNEfFDAP
BgNVHRMBAf8EBTADAQH/MA4GA1UdDwEB/wQEAwIBBjAKBggqhkjOPQQDAgNHADBE
AiA4MyvG1TtLRGN11VmUUfqQQL9k068csHHVX/5DVFOPiAIgfD4TYOq+iKvv8A6f
qSd7saqfi41FFBJt+8DLIq0eikA=
-----END CERTIFICATE-----
"""

ZENOH_ECHO_REQ_KEYEXPR = "muscat/zenoh/echo_req"
ZENOH_ECHO_RES_KEYEXPR = "muscat/zenoh/echo_res"


[docs] class ZenohSubscriptionDone: """zenoh 구독 콜백에서 "이제 끝났다"를 안전하게 신호하기 위한 `asyncio.Event` 드롭인. `asyncio.Event`와 똑같이 `.set()` / `await .wait()` / `.is_set()` 으로 쓰면 된다. 차이는 단 하나, **어느 이벤트 루프에서 `.set()`을 호출해도 안전**하다는 것. 왜 필요한가: zenoh 구독 콜백은 zenoh **전용 핸들러 이벤트 루프(별도 스레드)** 에서 실행되는데, `await .wait()`는 보통 다른 루프(SDK 함수가 도는 루프)에서 일어난다. 순수 `asyncio.Event`는 thread-safe하지 않아 콜백 루프에서 `set()`해도 대기 중인 루프를 깨우지 못해 `await .wait()`가 영원히 안 풀린다(=stop 시 데드락). 이 클래스는 `set()`을 대기 루프로 `call_soon_threadsafe`로 넘겨 그 함정을 자동으로 없앤다. 사용법:: done = self._zenoh_subs_done_event() # await 할 루프에서 생성 def _on_status(*, obj_payload=None, unsubscribe=None, **_): ... # 도메인 판정 if 끝남: unsubscribe() done.set() # 그냥 set 하면 됨 (cross-loop 걱정 X) sub = self.zenoh_client.subscribe(topic, _on_status, ...) try: await done.wait() finally: sub.close() """ def __init__(self) -> None: # 생성 시점의 루프(= await .wait() 할 루프)를 캡처해 둔다. self._loop = asyncio.get_running_loop() self._event = asyncio.Event()
[docs] def set(self) -> None: # 콜백이 다른 루프/스레드에서 부르더라도 대기 루프로 안전하게 전달. with contextlib.suppress(RuntimeError): # 대기 루프가 이미 닫힌 경우 self._loop.call_soon_threadsafe(self._event.set)
[docs] def is_set(self) -> bool: return self._event.is_set()
[docs] async def wait(self) -> bool: return await self._event.wait()
[docs] class RBBaseSDK: """프로세스별 싱글톤 + 공통 Zenoh/루프 관리 + 참조 카운팅""" # (pid, cls) 기준으로 인스턴스 관리 _instances: ClassVar[dict[tuple[int, type["RBBaseSDK"]], "RBBaseSDK"]] = {} # PID별 전체 SDK 참조 카운트 (모든 SDK 클래스 통합) _total_ref_counts: ClassVar[dict[int, int]] = {} # PID별 ZenohClient 인스턴스 _zenoh_clients: ClassVar[dict[int, ZenohClient]] = {} # RLock: __new__ → _refresh_zenoh_client_for_pid 재진입 가능 _lock: ClassVar[threading.RLock] = threading.RLock() @staticmethod def _is_client_session_alive(client: ZenohClient | None) -> bool: """Zenoh 세션 객체의 기본 생존 상태를 점검한다. C++ 마이그레이션 후 ZenohClient는 ._core (ZenohClientCore) 를 보유한다. close() 시 ._core 가 None 으로 설정되므로 그것을 생존 신호로 사용한다. """ if client is None: return False # C++ core 경로 (현재 구현) if getattr(client, "_core", None) is not None: return True # 레거시 python-zenoh 경로 호환 (혹시 남아 있을 경우 대비) session = getattr(client, "session", None) if session is None: return False for attr_name in ("is_closed", "closed"): attr = getattr(session, attr_name, None) if attr is None: continue try: value = attr() if callable(attr) else attr except Exception: continue if isinstance(value, bool): return not value return True @classmethod def _refresh_zenoh_client_for_pid(cls, pid: int, *, force: bool = False) -> ZenohClient: """ PID 단위 ZenohClient를 재생성/재연결한다. 기존 세션이 죽었거나 라우터 재기동 후 stale 상태일 때 사용. """ with cls._lock: current = cls._zenoh_clients.get(pid) if (not force) and cls._is_client_session_alive(current): return current # pyright: ignore[reportReturnType] # 중요: ZenohClient는 PID 싱글톤이므로 close()하면 같은 프로세스의 # router/subscriber까지 함께 undeclare 된다. # reconnect는 close 대신 connect() 재시도로 처리한다. if current is None: current = ZenohClient() cls._zenoh_clients[pid] = current if not cls._is_client_session_alive(current): with contextlib.suppress(Exception): current.connect() return current def _ensure_zenoh_client_alive(self, *, force_reconnect: bool = False) -> ZenohClient: """현재 SDK 인스턴스가 살아있는 ZenohClient를 참조하도록 보장한다.""" pid = getattr(self, "_pid", os.getpid()) client = getattr(self, "zenoh_client", None) if (not force_reconnect) and self._is_client_session_alive(client): return client # pyright: ignore[reportReturnType] refreshed = self._refresh_zenoh_client_for_pid(pid, force=force_reconnect) self.zenoh_client = refreshed return refreshed # 공통 예외 핸들링: 서브클래스 메서드 자동 래핑 def __init_subclass__(cls, **kwargs): """RBBaseSDK를 상속한 모든 클래스의 public instance method에 공통 try/except를 자동으로 씌움.""" super().__init_subclass__(**kwargs) for name, attr in list(cls.__dict__.items()): if name.startswith("_"): continue # property / classmethod / staticmethod는 따로 처리 X if isinstance(attr, property | classmethod | staticmethod): continue # 일반 함수만 래핑 if callable(attr): wrapped = cls._wrap_with_safe_handler(attr) setattr(cls, name, wrapped) @staticmethod def _wrap_with_safe_handler(fn): """sync/async 둘 다 지원하는 공통 에러 핸들러""" async def _async_wrapper(*args, **kwargs): try: if args and isinstance(args[0], RBBaseSDK): sdk_inst = args[0] # disconnect() 후 명시적 close 상태이면 auto-reconnect를 막는다. # C++ manually_closed_ 플래그를 Python facade를 통해 확인. zc = getattr(sdk_inst, "zenoh_client", None) if zc is not None and getattr(zc, "manually_closed", False) is True: raise RuntimeError( "Zenoh session was explicitly closed via disconnect(). " "Call connect() before using the SDK again." ) sdk_inst._ensure_zenoh_client_alive() return await fn(*args, **kwargs) except (TypeError, ValueError, AttributeError, KeyError) as e: print(f"[{fn.__name__}] invalid param: {e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {e}") from e except ServiceException as e: e.message = f"[{fn.__name__}] {e.message}" if e.status_code is None: e.status_code = 500 raise e except (ZenohNoReply, ZenohTransportError) as e: if args and isinstance(args[0], RBBaseSDK): sdk_self = args[0] print( f"[{fn.__name__}] zenoh error: {e} -> reconnect and retry once", flush=True ) sdk_self._ensure_zenoh_client_alive( force_reconnect=isinstance(e, ZenohTransportError) ) try: return await fn(*args, **kwargs) except (ZenohNoReply, ZenohTransportError) as retry_e: print(f"[{fn.__name__}] zenoh retry failed: {retry_e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {retry_e}") from retry_e print(f"[{fn.__name__}] zenoh error: {e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {e}") from e except asyncio.CancelledError as e: print(f"[{fn.__name__}] cancelled error: {e}", flush=True) raise RuntimeError(f"cancelled: {e}") from e except Exception as e: # noqa: BLE001 print(f"[{fn.__name__}] {e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {e}") from e def _sync_wrapper(*args, **kwargs): try: if args and isinstance(args[0], RBBaseSDK): sdk_inst = args[0] zc = getattr(sdk_inst, "zenoh_client", None) if zc is not None and getattr(zc, "manually_closed", False) is True: raise RuntimeError( "Zenoh session was explicitly closed via disconnect(). " "Call connect() before using the SDK again." ) sdk_inst._ensure_zenoh_client_alive() return fn(*args, **kwargs) except (TypeError, ValueError, AttributeError, KeyError) as e: print(f"[{fn.__name__}] invalid param: {e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {e}") from e except ServiceException as e: e.message = f"[{fn.__name__}] {e.message}" if e.status_code is None: e.status_code = 500 raise e except (ZenohNoReply, ZenohTransportError) as e: if args and isinstance(args[0], RBBaseSDK): sdk_self = args[0] print( f"[{fn.__name__}] zenoh error: {e} -> reconnect and retry once", flush=True ) sdk_self._ensure_zenoh_client_alive( force_reconnect=isinstance(e, ZenohTransportError) ) try: return fn(*args, **kwargs) except (ZenohNoReply, ZenohTransportError) as retry_e: print(f"[{fn.__name__}] zenoh retry failed: {retry_e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {retry_e}") from retry_e print(f"[{fn.__name__}] zenoh error: {e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {e}") from e except asyncio.CancelledError as e: raise RuntimeError(f"cancelled: {e}") from e except Exception as e: # noqa: BLE001 print(f"[{fn.__name__}] {e}", flush=True) raise RuntimeError(f"[{fn.__name__}] {e}") from e if asyncio.iscoroutinefunction(fn): return functools.wraps(fn)(_async_wrapper) return functools.wraps(fn)(_sync_wrapper) @classmethod def _singleton_subkey(cls, *args, **kwargs) -> Any: """싱글톤 식별에 생성 인자(config 등)를 반영하고 싶은 서브클래스용 hook. 기본은 ``()`` 이라 ``(pid, cls)`` 만으로 싱글톤이 결정된다. 서브클래스가 이 값을 다르게 돌려주면, 같은 ``(pid, cls)`` 라도 **별도 인스턴스**로 관리된다. 예) ``RBRby1SDK`` 는 endpoint/model 이 다르면 다른 로봇을 가리키므로 분리해야 한다. """ return () def __new__(cls: type[T], *args: Any, **kwargs: Any) -> T: pid = os.getpid() key = (pid, cls, cls._singleton_subkey(*args, **kwargs)) with RBBaseSDK._lock: if key not in RBBaseSDK._instances: instance = super().__new__(cls) RBBaseSDK._instances[key] = instance instance._instance_key = key instance._initialized = False instance._zenoh_subscribers = [] instance._zenoh_queryables = [] instance._pid = pid instance._closing = False instance._use_directly = False # 카운트 증가 RBBaseSDK._total_ref_counts[pid] = RBBaseSDK._total_ref_counts.get(pid, 0) + 1 # ZenohClient 생성 및 설정 if pid not in RBBaseSDK._zenoh_clients: RBBaseSDK._zenoh_clients[pid] = ZenohClient() instance.zenoh_client = RBBaseSDK._zenoh_clients[pid] if not RBBaseSDK._is_client_session_alive(instance.zenoh_client): instance.zenoh_client = RBBaseSDK._refresh_zenoh_client_for_pid(pid) return RBBaseSDK._instances[key] def __getattribute__(self, name: str): try: use_directly = super().__getattribute__("_use_directly") except AttributeError: use_directly = False if use_directly and not name.startswith("_"): directly_name = f"{name}_directly" try: return super().__getattribute__(directly_name) except AttributeError: pass return super().__getattribute__(name) def __init__( self, *, server: Literal["amr", "manipulate"] | None = None, use_directly: bool = False ): # 싱글톤이어도 use_directly는 매번 갱신 self._use_directly = use_directly # 이미 초기화 됐으면 스킵 if getattr(self, "_initialized", False): return self._is_alive = True self._pid = os.getpid() self._closing = False # 리스트 초기화 (데코레이터가 먼저 실행될 수 있음) if not hasattr(self, "_zenoh_queryables"): self._zenoh_queryables = [] if not hasattr(self, "_zenoh_subscribers"): self._zenoh_subscribers = [] # 공유 ZenohClient 사용 with RBBaseSDK._lock: self.zenoh_client = RBBaseSDK._zenoh_clients[self._pid] self._ensure_zenoh_client_alive() # Zenoh peer 연결 상태 self._peer_id: str | None = None self._peer_common_url: str | None = None self._peer_host: str | None = None self._peer_token: str | None = None self._heartbeat_task: threading.Thread | None = None self._heartbeat_stop: threading.Event = threading.Event() self._initialized = True
[docs] def register_zenoh_queryable(self, keyexpr: str, queryable): """Queryable 등록 (keyexpr와 함께 저장)""" self._zenoh_queryables.append((keyexpr, queryable)) return queryable
[docs] def register_zenoh_subscriber(self, subscriber): """Subscriber 등록 (정리를 위해)""" self._zenoh_subscribers.append(subscriber) return subscriber
@overload def zenoh_subscribe( self, topic: str, *, flatbuffer_obj_t: FBRootReadable[TSubObj], opts: SubscribeOptions | None = None, ) -> Callable[[SubscribeObjCallback[TSubObj]], SubscribeObjCallback[TSubObj]]: ... @overload def zenoh_subscribe( self, topic: str, *, flatbuffer_obj_t: None = None, opts: SubscribeOptions | None = None, ) -> Callable[[SubscribeDictCallback], SubscribeDictCallback]: ...
[docs] def zenoh_subscribe( self, topic: str, *, flatbuffer_obj_t: SubscribeObjReadable | None = None, opts: SubscribeOptions | None = None, ): """데코레이터: Subscribe 자동 등록 및 정리""" def decorator(callback: Callable): handle = self.zenoh_client.subscribe( topic=topic, callback=callback, flatbuffer_obj_t=flatbuffer_obj_t, options=opts, ) # 리스트가 없으면 생성 if not hasattr(self, "_zenoh_subscribers"): self._zenoh_subscribers = [] self._zenoh_subscribers.append(handle) return callback return decorator
[docs] def zenoh_queryable( self, keyexpr: str, *, flatbuffer_req_T_class: FBRootReadable | None = None, flatbuffer_res_buf_size: int | None = None, ): """데코레이터: Queryable 자동 등록 및 정리""" def decorator(handler: Callable): # 중복 체크 if keyexpr in self.zenoh_client._queryables: print(f"⚠️ Queryable already declared: {keyexpr}", flush=True) return handler # 중복이면 그냥 반환 # Queryable 등록 qbl = self.zenoh_client.queryable( keyexpr=keyexpr, handler=handler, flatbuffer_req_T_class=flatbuffer_req_T_class, flatbuffer_res_buf_size=flatbuffer_res_buf_size, ) # 리스트가 없으면 생성 if not hasattr(self, "_zenoh_queryables"): self._zenoh_queryables = [] self._zenoh_queryables.append((keyexpr, qbl)) return handler return decorator
def _cleanup_resources(self): """이 SDK 인스턴스의 Zenoh 리소스 정리""" print(f"[{self.__class__.__name__}] Cleaning up resources", flush=True) before_close_attr = getattr(self, "before_close", None) before_close_hook: Callable[[], object] | None = ( before_close_attr if callable(before_close_attr) else None ) if before_close_hook is not None: try: result = before_close_hook() if inspect.isawaitable(result): self._run_coro_blocking(result) except Exception as e: print(f"[SDK Base] Error in before_close: {e}", flush=True) # Queryable 정리 for keyexpr, _ in self._zenoh_queryables: try: self.zenoh_client.undeclare_queryable(keyexpr) except Exception as e: print(f"[SDK Base] Error undeclaring queryable {keyexpr}: {e}", flush=True) self._zenoh_queryables.clear() # Subscriber 정리 try: self.zenoh_client.unsubscribe_all() except Exception as e: print(f"[SDK Base] Error closing subscriber: {e}", flush=True) self._zenoh_subscribers.clear() def _run_coro_blocking(self, coro, *, timeout: float | None = None): try: asyncio.get_running_loop() # running loop가 있는 스레드 → 별도 스레드에서 새 루프로 실행 import concurrent.futures with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool: future = pool.submit(asyncio.run, coro) return future.result(timeout=timeout) except RuntimeError: # running loop 없음 → 직접 실행 if timeout is None: return asyncio.run(coro) async def _with_timeout(): return await asyncio.wait_for(coro, timeout=timeout) return asyncio.run(_with_timeout()) def _zenoh_subs_done_event(self) -> ZenohSubscriptionDone: """zenoh 구독 완료 신호용 cross-loop-safe 이벤트를 만든다. 구독을 기다리는 async 함수 안에서 호출할 것. 반환된 객체는 `asyncio.Event`처럼 `.set()` / `await .wait()` 로 쓰되, 콜백이 zenoh 전용 핸들러 루프에서 돌아도 안전하다. 자세한 내용은 `ZenohSubscriptionDone` 참고. """ return ZenohSubscriptionDone() @contextlib.asynccontextmanager async def _zenoh_sub_with_close(self, topic: str, callback, **subscribe_kwargs): """zenoh 구독을 만들고, 블록을 벗어나면 자동으로 close하는 async 컨텍스트매니저. 도메인 지식 없음 — 그냥 구독 lifecycle만 책임진다. 구독이 여러 개여도 깔끔하게 example: done = self._zenoh_subs_done_event() async with self._zenoh_sub_with_close(t1, cb1, flatbuffer_obj_t=..., options=...), \\ self._zenoh_sub_with_close(t2, cb2, options=...): await done.wait() # 여기서 t1, t2 둘 다 자동 close ANY/ALL 합성은 표준 asyncio로:: await asyncio.wait({a.wait(), b.wait()}, return_when=asyncio.FIRST_COMPLETED) await asyncio.gather(a.wait(), b.wait()) """ handle = self.zenoh_client.subscribe(topic, callback, **subscribe_kwargs) try: yield handle finally: handle.close() @staticmethod def _detect_local_ip(host: str) -> str: """host 방향의 라우팅 인터페이스 IP를 반환한다. UDP 소켓을 사용해 실제로 패킷을 보내지 않고 OS 라우팅 테이블만 조회한다. """ with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: s.connect((host, 80)) return s.getsockname()[0] @staticmethod def _find_free_port() -> int: """OS가 임시로 배정한 사용 가능한 TCP 포트 번호를 반환한다.""" with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s: s.bind(("", 0)) return s.getsockname()[1] @staticmethod def _split_endpoint_env(value: str | None) -> list[str]: if not value: return [] normalized = value.replace("\n", ",") return [endpoint.strip() for endpoint in normalized.split(",") if endpoint.strip()] @staticmethod def _merge_endpoint_env(name: str, endpoint: str) -> None: endpoints = RBBaseSDK._split_endpoint_env(os.getenv(name)) if endpoint not in endpoints: endpoints.append(endpoint) os.environ[name] = ",".join(endpoints) def _reconnect_shared_zenoh_for_remote_peer( self, *, listen_port: int, ) -> None: """Make the SDK's real query session reachable from remote common. ``connect()`` used to open a separate raw Zenoh session for peer tracking, but SDK calls such as ``move_j`` use the process-wide ``ZenohClient``. The shared client must therefore own the externally reachable listen endpoint that common connects to. """ self._merge_endpoint_env("ZENOH_PEER_LISTEN_ENDPOINTS", f"tcp/0.0.0.0:{listen_port}") # connect() 명시 호출: manually_closed 상태이더라도 재연결을 허용한다. # dict에 기존 client가 있으면 그대로 쓰고, 없으면 새로 만든다. with RBBaseSDK._lock: zenoh_client = RBBaseSDK._zenoh_clients.get(self._pid) if zenoh_client is None: zenoh_client = ZenohClient() RBBaseSDK._zenoh_clients[self._pid] = zenoh_client self.zenoh_client = zenoh_client with contextlib.suppress(Exception): zenoh_client.close() zenoh_client.connect() # C++ connect() resets manually_closed_ async def _wait_for_zenoh_echo( self, *, req_keyexpr: str, res_keyexpr: str, timeout: float | None, probe_timeout: float, interval: float, ) -> bool: """bridge ↔ 내부 mesh 의 양방향 pub/sub propagation이 settled 되었는지 검증한다. unique nonce를 echo_req에 publish하고 echo_res로 동일 nonce가 돌아올 때까지 대기한다. queryable probe와 달리 양방향 subscription declaration이 모두 전파되어야만 성공하므로 실제 pub/sub 경로가 동작함을 보장한다. """ loop = asyncio.get_running_loop() deadline = None if timeout is None else loop.time() + timeout expected: set[str] = set() received: asyncio.Event = asyncio.Event() matched: dict[str, str] = {} def _cb(*, mv: memoryview, **kwargs): try: n = bytes(mv).decode("utf-8", "ignore") except Exception: return if n in expected: matched["nonce"] = n loop.call_soon_threadsafe(received.set) handle = self.zenoh_client.subscribe( res_keyexpr, _cb, options=SubscribeOptions(parse_dict_payload=False, allowed_same_sender=True), ) try: while True: nonce = uuid.uuid4().hex expected.add(nonce) received.clear() matched.pop("nonce", None) with contextlib.suppress(Exception): self.zenoh_client.publish(req_keyexpr, payload=nonce.encode()) try: await asyncio.wait_for(received.wait(), timeout=probe_timeout) if matched.get("nonce") == nonce: print( f"[SDK] zenoh echo verified: {req_keyexpr} → {res_keyexpr}", flush=True, ) return True except TimeoutError: pass if deadline is None: await asyncio.sleep(interval) continue remaining = deadline - loop.time() if remaining <= 0: print( f"[SDK] zenoh echo still warming up: no matching reply on " f"{res_keyexpr!r} within {timeout:.1f}s", flush=True, ) return False await asyncio.sleep(min(interval, remaining)) finally: with contextlib.suppress(Exception): handle.close() with contextlib.suppress(Exception): self.zenoh_client.unsubscribe_topic(res_keyexpr) @staticmethod def _http_json( method: str, url: str, data: dict | None, headers: dict, timeout: float = 10.0, ) -> dict: """블로킹 HTTP 요청 (stdlib urllib). asyncio.to_thread로 감싸서 사용한다.""" body = json.dumps(data).encode() if data is not None else None req = urllib.request.Request( url, data=body, headers={**headers, "Content-Type": "application/json"}, method=method, ) try: context = RBBaseSDK._robot_ssl_context() if url.startswith("https://") else None with urllib.request.urlopen(req, timeout=timeout, context=context) as resp: return json.loads(resp.read()) except urllib.error.HTTPError as e: raise RuntimeError(f"HTTP {e.code} {method} {url}: {e.read().decode()}") from e except (urllib.error.URLError, TimeoutError, OSError) as e: raise RuntimeError(f"connect failed {method} {url}: {e}") from e @staticmethod def _robot_ssl_context() -> ssl.SSLContext: """발급자는 검증하고 호스트 이름 검사는 끈다 — 사용자는 IP 로 접속하는데 로봇 인증서에는 .local 이름만 있다.""" context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) context.check_hostname = False context.verify_mode = ssl.CERT_REQUIRED ca_file = os.environ.get("RB_SDK_CA_FILE") if ca_file: context.load_verify_locations(cafile=ca_file) else: context.load_verify_locations(cadata=ROBOT_ROOT_CA_PEM) return context @staticmethod def _peer_url_candidates(host: str) -> list[str]: """RB_SDK_TLS: auto(기본, https 실패 시 평문 8000) | required(https 만) | off(평문만)""" mode = os.environ.get("RB_SDK_TLS", "auto") https, http = f"https://{host}:13000/common", f"http://{host}:8000" if mode == "off": return [http] if mode == "required": return [https] return [https, http] def _register_peer(self, host: str, payload: dict, headers: dict, timeout: float) -> dict: """https → http 순으로 등록한다. 전송 실패만 폴백하고, HTTP 오류 응답은 그대로 올린다.""" candidates = self._peer_url_candidates(host) for i, url in enumerate(candidates): has_fallback = i + 1 < len(candidates) self._peer_common_url = url try: return self._http_json( "POST", f"{url}/zenoh/peer", payload, headers, min(timeout, 3.0) if has_fallback else timeout ) except RuntimeError as e: if not has_fallback or not str(e).startswith("connect failed"): raise print(f"[SDK] {url} unreachable ({e}), falling back to {candidates[i + 1]}", flush=True) raise RuntimeError("no peer url candidates") def _is_same_host(self, host: str) -> bool: """host가 이 머신과 동일한 PC인지 확인한다.""" if host in ("127.0.0.1", "localhost", "::1"): return True try: my_ip = self._detect_local_ip(host) target_ip = socket.gethostbyname(host) return my_ip == target_ip except Exception: return False # mesh 형성 대기 상한. 넘어가도 실패가 아니라 그냥 진행한다. _MESH_WAIT_TIMEOUT = 5.0 _MESH_PROBE_TIMEOUT = 1.0 _MESH_PROBE_INTERVAL = 0.5
[docs] async def connect( self, *, token: str, host: str, zenoh_port: int | None = None, ttl: int = 30, heartbeat: float | None = None, ) -> str | None: """common 서비스에 외부 Zenoh peer로 등록하고 백그라운드 유지 스레드를 시작한다. 등록 성공/실패와 무관하게 즉시 반환한다. 실패하면 유지 스레드가 계속 재시도하고, 중간에 common 이 재시작해 peer 가 사라져도 자동으로 재등록한다. 붙기 전 SDK 호출은 no-reply 로 실패한다. common과 같은 PC에서 실행 중이라면 이미 Zenoh 메시가 형성되어 있으므로 아무것도 하지 않고 ``None`` 을 반환한다. 내부적으로 SDK 호출이 사용하는 공유 Zenoh 세션을 외부 listen 포트로 재연결한다. ``zenoh_port`` 를 생략하면 OS가 빈 포트를 자동으로 배정하므로 충돌이 없다. Args: token: common 서비스 Bearer 토큰. host: common 서비스가 실행 중인 PC의 IP (예: ``"192.168.1.100"``). zenoh_port: 이 머신의 Zenoh listen 포트. ``None`` 이면 OS가 자동 배정. ttl: common 측 브리지 세션 TTL(초). heartbeat를 보내지 않으면 이 시간 후 자동 해제. heartbeat: heartbeat 전송 주기(초). None 이면 ``ttl / 2`` 사용. Returns: common이 발급한 peer_id. 같은 PC라 불필요하거나 아직 등록 전이면 ``None``. """ # 같은 PC면 이미 127.0.0.1:7447로 Zenoh 연결이 형성되어 있으므로 불필요 if self._is_same_host(host): print( "[SDK] connect() skipped: common is on the same host, already in the mesh", flush=True, ) return None if self._peer_id is not None: print(f"[SDK] already connected as peer {self._peer_id}, disconnect first", flush=True) return self._peer_id url = self._peer_url_candidates(host)[0] my_ip = self._detect_local_ip(host) free_port = zenoh_port if zenoh_port is not None else self._find_free_port() print(f"[SDK] local IP={my_ip}, zenoh port={free_port}", flush=True) self._reconnect_shared_zenoh_for_remote_peer(listen_port=free_port) headers = {"Authorization": f"Bearer {token}"} payload = {"ip": my_ip, "port": free_port, "ttl": ttl} peer_id: str | None try: resp_data = await asyncio.to_thread(self._register_peer, host, payload, headers, 10.0) peer_id = resp_data["peer_id"] except Exception as e: # 로봇이 아직 안 떴을 수 있다. 등록은 유지 스레드에 넘기고 호출자는 진행시킨다. print(f"[SDK] registration to {host} failed, retrying in background: {e}", flush=True) peer_id = None url = self._peer_common_url or url self._peer_id = peer_id self._peer_common_url = url self._peer_host = host self._peer_token = token interval = heartbeat if heartbeat is not None else max(1.0, ttl / 2) self._heartbeat_stop = threading.Event() hb_thread = threading.Thread( target=self._maintain_peer_loop, args=(peer_id,), kwargs={"ttl": ttl, "interval": interval, "payload": payload}, daemon=True, name=f"sdk-peer-{(peer_id or 'pending')[:8]}", ) hb_thread.start() self._heartbeat_task = hb_thread if peer_id is None: # 아직 등록 전. mesh 대기는 의미가 없고, 유지 스레드가 붙이면 된다. return peer_id # mesh 형성은 보통 1초 안에 끝난다. 그때까지만 기다려주고 안 되면 그냥 진행한다 # (유지 스레드가 계속 붙이므로, 여기서 무한정 잡고 있을 이유가 없다). try: await self._wait_for_zenoh_echo( req_keyexpr=ZENOH_ECHO_REQ_KEYEXPR, res_keyexpr=ZENOH_ECHO_RES_KEYEXPR, timeout=self._MESH_WAIT_TIMEOUT, probe_timeout=self._MESH_PROBE_TIMEOUT, interval=self._MESH_PROBE_INTERVAL, ) except BaseException: self._heartbeat_stop.set() self._heartbeat_task = None self._peer_id = None self._peer_common_url = None self._peer_token = None with contextlib.suppress(Exception): await asyncio.to_thread( self._http_json, "DELETE", f"{url}/zenoh/peer/{peer_id}", None, headers, 5.0 ) raise print( f"[SDK] connected as zenoh peer {peer_id} → {url} my={my_ip}:{free_port} ttl={ttl}s hb={interval}s", flush=True, ) return peer_id
[docs] async def disconnect(self) -> bool: """common 서비스에 등록된 외부 Zenoh peer 연결을 해제하고 heartbeat를 중단한다.""" if self._peer_id is None and self._heartbeat_task is None: return False # 유지 스레드 중단. 등록 대기 중(peer_id=None)이어도 멈춰야 뒤늦게 재등록하지 않는다. if hasattr(self, "_heartbeat_stop"): self._heartbeat_stop.set() if self._heartbeat_task and self._heartbeat_task.is_alive(): self._heartbeat_task.join(timeout=2.0) self._heartbeat_task = None # 스레드가 멈춘 뒤에 읽는다 — 그 사이 등록이 끝났을 수 있다. peer_id = self._peer_id url = self._peer_common_url token = self._peer_token self._peer_id = None self._peer_common_url = None self._peer_token = None if peer_id and url and token: headers = {"Authorization": f"Bearer {token}"} with contextlib.suppress(Exception): await asyncio.to_thread( self._http_json, "DELETE", f"{url}/zenoh/peer/{peer_id}", None, headers, 5.0 ) print(f"[SDK] disconnected zenoh peer {peer_id or '(not registered)'}", flush=True) # peer 해제 후 Zenoh 세션도 닫아 gossip/multihop 경로까지 완전히 차단. # 주의: dict에서 pop하지 않고 close()만 한다. # → _zenoh_clients에 manually_closed 상태의 client가 남아있게 되어 # _refresh_zenoh_client_for_pid 에서 auto-reconnect를 막을 수 있다. self._cleanup_resources() pid = getattr(self, "_pid", None) if pid is not None: with RBBaseSDK._lock: zenoh_client = RBBaseSDK._zenoh_clients.get(pid) if zenoh_client is not None: with contextlib.suppress(Exception): zenoh_client.close() return True
_PEER_RETRY_MIN = 2.0 _PEER_RETRY_MAX = 30.0 def _maintain_peer_loop( self, peer_id: str | None, *, ttl: int, interval: float, payload: dict ) -> None: """peer 등록 상태를 유지한다. asyncio 이벤트 루프와 무관하게 별도 스레드에서 돈다. 등록·heartbeat·재등록을 한 루프에서 처리한다. ``peer_id`` 가 None 이면 등록부터 시작하고, heartbeat 이 거부되면(common 재시작 등으로 peer 소멸) None 으로 되돌려 재등록한다. zenoh 세션의 listen 포트는 그대로이므로 재등록만으로 다시 붙는다. """ stop: threading.Event = getattr(self, "_heartbeat_stop", threading.Event()) backoff = self._PEER_RETRY_MIN while True: # 등록됐으면 heartbeat 주기로, 등록 전이면 backoff 로 쉰다. if stop.wait(timeout=interval if peer_id is not None else backoff): return if self._peer_common_url is None or self._peer_token is None: return url = self._peer_common_url headers = {"Authorization": f"Bearer {self._peer_token}"} try: if peer_id is None: # 로봇 쪽 TLS 상태가 바뀌었을 수 있어 다시 고른다 resp_data = self._register_peer(self._peer_host or "", payload, headers, 10.0) url = self._peer_common_url or url peer_id = resp_data["peer_id"] self._peer_id = peer_id backoff = self._PEER_RETRY_MIN print(f"[SDK] zenoh peer registered: {peer_id} -> {url}", flush=True) continue resp_data = self._http_json( "POST", f"{url}/zenoh/peer/{peer_id}/heartbeat", {"ttl": ttl}, headers, 5.0 ) if not resp_data.get("ok"): print(f"[SDK] heartbeat rejected for peer {peer_id}, re-registering", flush=True) peer_id = None self._peer_id = None except Exception as e: print(f"[SDK] peer keepalive failed: {e}", flush=True) if peer_id is None: backoff = min(backoff * 2, self._PEER_RETRY_MAX)
[docs] def log( self, *, content: str, robot_model: str, level: Literal["INFO", "WARNING", "ERROR", "USER", "DEBUG", "GENERAL"], disable_db: bool = False, flow_manager_args: FlowManagerArgs | None = None, ): """프로그램 로그 발생""" req = RB_Program_LogT() req.content = content req.robotModel = robot_model if level == "INFO": req.type = RB_Program_Log_Type.INFO elif level == "WARNING": req.type = RB_Program_Log_Type.WARNING elif level == "ERROR": req.type = RB_Program_Log_Type.ERROR elif level == "USER": req.type = RB_Program_Log_Type.USER elif level == "DEBUG": req.type = RB_Program_Log_Type.DEBUG elif level == "GENERAL": req.type = RB_Program_Log_Type.GENERAL self.zenoh_client.publish( "muscat/program/log", flatbuffer_req_obj=req, flatbuffer_buf_size=256, ) if flow_manager_args is not None: flow_manager_args.done()
[docs] def manipulate_return_value( self, func_name: str, obj_payload: object, flow_manager_args: FlowManagerArgs | None = None ): """ PyFM이 실행할 경우 obj_payload에 returnValue 필드가 있고, 0이 아니면 에러로 간주해서 로그 남기고 예외를 던진다. Args: func_name: 함수 이름 (로그용) obj_payload: 반환된 객체 (returnValue 필드가 있는지 확인) flow_manager_args: Flow Manager 인자 (done 콜백 호출 여부 결정) """ if ( flow_manager_args is not None and hasattr(obj_payload, "returnValue") and obj_payload.returnValue != 0 ): error_msg = f"[{func_name}] return value is {obj_payload.returnValue}" rb_log.error(error_msg) raise RuntimeError(error_msg)
[docs] def close(self): """SDK 종료 (전체 참조 카운트 기반으로 ZenohClient 정리 여부 결정)""" if os.getpid() != getattr(self, "_pid", os.getpid()): return pid = self._pid key = getattr(self, "_instance_key", (pid, self.__class__)) should_close_zenoh = False should_cleanup_resources = False with RBBaseSDK._lock: # 중복 close 방지 if getattr(self, "_closing", False): # self.log(content=f"[SDK Base] {self.__class__.__name__} (PID {pid}) close already in progress", robot_model="RRS", level="DEBUG") return # 이미 제거된 인스턴스는 건너뜀 (카운트 감소 X) if key not in RBBaseSDK._instances: # self.log(content=f"[SDK Base] {self.__class__.__name__} (PID {pid}) already removed, skipping", robot_model="RRS", level="DEBUG") return self._closing = True # 전체 참조 카운트 감소 if pid in RBBaseSDK._total_ref_counts: RBBaseSDK._total_ref_counts[pid] -= 1 remaining = RBBaseSDK._total_ref_counts[pid] # self.log(content=f"[SDK Base] Closing {self.__class__.__name__} (PID {pid}), remaining SDKs: {remaining}", robot_model="RRS", level="DEBUG") # 이 클래스의 인스턴스가 정리될 때 리소스 정리 if key in RBBaseSDK._instances: should_cleanup_resources = True RBBaseSDK._instances.pop(key, None) # 모든 SDK가 정리되었으면 ZenohClient도 닫기 if remaining <= 0: should_close_zenoh = True RBBaseSDK._total_ref_counts.pop(pid, None) # self.log(content=f"[SDK Base] ✅ All SDKs closed for PID {pid}, will close ZenohClient", robot_model="RRS", level="DEBUG") # Lock 밖에서 리소스 정리 (deadlock 방지) if should_cleanup_resources: # Zenoh peer 연결 해제 (heartbeat task 포함) if getattr(self, "_peer_id", None) is not None: self._run_coro_blocking(self.disconnect(), timeout=5) try: self._cleanup_resources() # self.log(content=f"[SDK Base] ✅ Resources cleaned for {self.__class__.__name__}", robot_model="RRS", level="DEBUG") except Exception as e: self.log( content=f"[SDK Base] Error cleaning up resources: {e}", robot_model="RRS", level="ERROR", ) # Lock 밖에서 ZenohClient 정리 (deadlock 방지) if should_close_zenoh: try: with RBBaseSDK._lock: zenoh_client = RBBaseSDK._zenoh_clients.pop(pid, None) if zenoh_client is not None: # self.log(content=f"[SDK Base] ✅ ZenohClient closed for PID {pid}", robot_model="RRS", level="DEBUG") with contextlib.suppress(Exception, TimeoutError): zenoh_client.close() except Exception as e: print(f"[SDK Base] Error closing ZenohClient: {e}", flush=True) self._is_alive = False self._closing = False
def __del__(self): """GC 시 안전 종료 (파이썬 종료 중이면 무시)""" if getattr(sys, "is_finalizing", lambda: False)(): return if os.getpid() == getattr(self, "_pid", None): with contextlib.suppress(builtins.BaseException): self.close()
[docs] @classmethod def close_all_for_pid(cls, pid: int | None = None) -> int: """ 주어진 pid(기본: 현재 프로세스)에 등록된 모든 RBBaseSDK 서브클래스 인스턴스를 한 번에 close 한다. ref-count가 항상 0까지 떨어지므로 ZenohClient도 정리된다. 부모 SDK가 자식 SDK 여러 개를 자동 instantiate 하는 구조에서, 부모 close만 호출하면 자식들이 leak되어 ref-count가 0에 도달하지 못하는 문제를 회피한다. Returns: close 시도된 인스턴스 수 """ target_pid = pid if pid is not None else os.getpid() with cls._lock: keys = [k for k in list(cls._instances.keys()) if k[0] == target_pid] instances = [cls._instances.get(k) for k in keys] closed = 0 for inst in instances: if inst is None: continue try: inst.close() closed += 1 except Exception as e: # noqa: BLE001 print( f"[SDK Base] close_all_for_pid error on {type(inst).__name__}: {e}", flush=True, ) return closed
[docs] def connect_can( self, *, channel: str, bitrate: int, clientId: str, fd: bool = False, dataBitrate: int = 0, receiveOwnMessages: int = 0, interface: str = "pcan", flow_manager_args: FlowManagerArgs | None = None ) -> ResponseCANConnectT: """ [CAN Connect 요청] - channel : 연결할 CAN 채널/디바이스 식별자 (ex : PCAN_USBBUS1, /dev/pcanusb32) - bitrate : CAN Nominal Bitrate (ex : 5000000, 1000000) - clientId : 연결을 요청한 클라이언트 식별자 (필수, 재시작해도 바뀌지 않는 값. ex : 플러그인 ID) 같은 채널을 여러 클라이언트가 함께 쓸 수 있고, 채널은 마지막 클라이언트가 해제할 때 닫힌다. socketcan은 인터페이스에 설정된 bitrate와 다르면 Host가 거절한다. - fd : CAN FD(Flexible Data-rate) 사용 여부 - dataBitrate : CAN Data Phase Bitrate (fd True일때 사용) - receiveOwnMessage : 자기가 송신한 TX 프레임을 RX로 수신할 지 여부 (기본 : 수신안함 0) - interface: 사용할 CAN 인터페이스/드라이버 종류 (ex : pcan, socketcan) """ print(f">>>>>>>>>>>>>>>>>> Connect Can !!!! {channel}") req = RequestCANConnectT() req.interface = interface req.bitrate = bitrate req.channel = channel req.dataBitrate = dataBitrate req.fd = fd req.receiveOwnMessages = receiveOwnMessages req.clientId = clientId topic = "muscat/can/connect" result = self.zenoh_client.query_one( topic, flatbuffer_req_obj=req, flatbuffer_res_T_class=ResponseCANConnectT, flatbuffer_buf_size=2048 ) if result.get("obj_payload") is None: raise RuntimeError(f"Call {topic} failed: obj_payload is None") print(f">>>>>>>>>>>>>>>>>> Connect Can Response !!!! {result.get("dict_payload").get("success")}") if flow_manager_args is not None: if result.get("dict_payload").get("success") is True: flow_manager_args.done() else: raise RuntimeError(result.get("dict_payload").get("message")) return result["obj_payload"]
[docs] def disconnect_can( self, *, channel: str, clientId: str, flow_manager_args: FlowManagerArgs | None = None ) -> ResponseCANDisconnectT: """ [CAN Disconnect 요청] - channel : 연결할 CAN 채널/디바이스 식별자 (ex : PCAN_USBBUS1, /dev/pcanusb32) - clientId : connect_can에 넘긴 클라이언트 식별자 (필수) 이 클라이언트의 사용만 해제한다. 다른 클라이언트가 남아 있으면 채널은 열린 채로 남는다. """ req = RequestCANDisconnectT() req.channel = channel req.clientId = clientId topic = "muscat/can/disconnect" result = self.zenoh_client.query_one( topic, flatbuffer_req_obj=req, flatbuffer_res_T_class=ResponseCANDisconnectT, flatbuffer_buf_size=100 ) if result.get("obj_payload") is None: raise RuntimeError(f"Call {topic} failed: obj_payload is None") if flow_manager_args is not None: if result.get("dict_payload").get("success") is True: flow_manager_args.done() else: raise RuntimeError(result.get("dict_payload").get("message")) return result["obj_payload"]
[docs] def transmit_can( self, *, channel: str, arbitrationId: int, data: list[int] | None = None, dlc: int = 0, isExtendedId: bool = False, isRemoteFrame: bool = False, isFd: bool = False, bitrateSwitch: bool = False, isErrorFrame: bool = False, errorStateIndicator: bool = False, timestamp: float = 0, flow_manager_args: FlowManagerArgs | None = None ) -> ResponseCANTransmitT: """ [CAN Transmit 요청] - channel : 연결할 CAN 채널/디바이스 식별자 (ex : PCAN_USBBUS1, /dev/pcanusb32) - arbitrationId : 메시지 CAN ID - data : 송신할 데이터 바이트 배열 - dlc : data length code. 프레임 데이터 길이 정보 - isExtendedId : 확장ID 사용 여부 (기본 False) - isRemoteFrame : RTR 여부 (기본 False) - isFd : CAN FD 프레임 여부 (기본 False) - bitrateSwitch : CAN FD BRS 여부 (기본 False) - isErrorFrame : Error Frame 여부 (기본 False) - errorStateIndicator : CAN FD의 ESI(Error State Indicator) 비트 (기본 False) - timestamp : 송신 시각 혹은 프레임 생성 시각 """ req = RequestCANTransmitT() req.channel = channel message = CANMessageT() message.arbitrationId = arbitrationId message.data = data message.dlc = dlc message.isExtendedId = isExtendedId message.isRemoteFrame = isRemoteFrame message.isFd = isFd message.bitrateSwitch = bitrateSwitch message.isErrorFrame = isErrorFrame message.errorStateIndicator = errorStateIndicator message.timestamp = timestamp req.message = message topic = "muscat/can/transmit" result = self.zenoh_client.query_one( topic, flatbuffer_req_obj=req, flatbuffer_res_T_class=ResponseCANTransmitT, flatbuffer_buf_size=100 ) if result.get("obj_payload") is None: raise RuntimeError(f"Call {topic} failed: obj_payload is None") if flow_manager_args is not None: if result.get("dict_payload").get("success") is True: flow_manager_args.done() else: raise RuntimeError(result.get("dict_payload").get("message")) return result["obj_payload"]