import asyncio
import uuid
from contextlib import suppress
from time import time
from typing import Any
from rb_flat_buffers.SLAMNAV.RequestLiftPower import RequestLiftPowerT
from rb_flat_buffers.SLAMNAV.ResponseLiftPower import ResponseLiftPowerT
from rb_schemas.sdk import FlowManagerArgs
from rb_utils.parser import t_to_dict
from rb_sdk.base import RBBaseSDK
[docs]
class RBAmrAccessorySDK(RBBaseSDK):
""" Rainbow Robotics AMR Accessory SDK """
async def _accessory_flow_manager_solver(self, robot_model: str, req_id: str, flow_manager_args: FlowManagerArgs | None = None):
"""
Accessory flow manager solver for AMR.
"""
if flow_manager_args is None:
return None
done_event = self._zenoh_subs_done_event()
state: dict[str, Any] = {
"finished": False,
"error": "",
"last_seen": time.monotonic(),
}
def all_stop(*, flow_manager_args: FlowManagerArgs | None = None):
"""모든 프로세스 정지"""
with suppress(Exception):
self.zenoh_client.query_one("muscat/stop", payload={}, timeout=10)
if flow_manager_args is not None:
flow_manager_args.done()
async def _on_status(*, obj_payload=None, unsubscribe=None, **_):
if state["finished"] or obj_payload is None:
return
try:
flow_manager_args.ctx.check_stop()
state["last_seen"] = time.monotonic()
obj = t_to_dict(obj_payload)
print(f"FLOW MANAGER ACCESSORY STATUS >>>>>>>>>>> {obj.get('mapState').get('mapId')} {req_id} {obj.get('mapState').get('mapResult')} ", flush=True)
# if obj.get("mapState").get("mapId") != req_id:
# raise RuntimeError("Map ID Mismatch")
# if obj.get("mapState").get("mapResult") == "success":
# print("Map Flow Manager SOLVER DONE", flush=True)
# flow_manager_args.done()
# state["finished"] = True
# if unsubscribe is not None:
# unsubscribe()
# done_event.set()
# elif obj.get("mapState").get("mapResult") == "fail":
# raise RuntimeError("Map Load Fail")
# elif obj.get("mapState").get("mapResult") == "cancel":
# raise RuntimeError("Map Load Cancel")
except Exception as e:
state["finished"] = True
state["error"] = str(e)
# if unsubscribe is not None:
# unsubscribe()
done_event.set()
async def _watchdog():
timeout_sec = 2.0
interval_sec = 0.5
while not state["finished"]:
await asyncio.sleep(interval_sec)
if state["finished"]:
return
if time.monotonic() - state["last_seen"] > timeout_sec:
state["finished"] = True
state["error"] = "Map Load Fail (Timeout)"
done_event.set()
return
# sub_handle = self.zenoh_client.subscribe(
# f"amr/{robot_model}/status",
# _on_status,
# flatbuffer_obj_t=StatusT,
# options=SubscribeOptions(
# dispatch="queue",
# overflow=OverflowPolicy.LATEST_ONLY,
# parse_dict_payload=False,
# ),
# )
watchdog_task = asyncio.create_task(_watchdog())
try:
await done_event.wait()
if state["error"] != "":
raise RuntimeError(state["error"])
except asyncio.CancelledError:
pass
except Exception as e:
all_stop(flow_manager_args=flow_manager_args)
raise RuntimeError(str(e)) from e
finally:
watchdog_task.cancel()
try:
await watchdog_task
except asyncio.CancelledError:
print("WATCHDOG CANCELLED", flush=True)
# sub_handle.close()
return None
[docs]
def set_lift_power(self, robot_model: str, switch: bool, req_id: str | None = None, flow_manager_args: FlowManagerArgs | None = None) -> ResponseLiftPowerT:
"""
[Lift 전원 제어]
- robot_model: 로봇 모델
- switch: 리프트 전원 스위치 (True: ON, False: OFF)
- req_id: 요청 ID (선택 사항)
- flow_manager_args: 플로우 매니저 인자 (선택 사항)
"""
if req_id is None:
req_id = str(uuid.uuid4())
# 1) RequestLiftPower 객체 생성
req = RequestLiftPowerT()
req.id = req_id
req.switch = switch
# 2) 요청 전송
result = self.zenoh_client.query_one(
f"amr/{robot_model}/accessory/lift",
flatbuffer_req_obj=req,
flatbuffer_res_T_class=ResponseLiftPowerT,
flatbuffer_buf_size=2048,
timeout=10,
)
# 3) 결과 처리 및 반환
if result.get("obj_payload") is None:
raise RuntimeError("Call Lift Power failed: obj_payload is None")
if flow_manager_args is not None:
print(result["dict_payload"].get("result"))
if result["dict_payload"].get("result") == "reject":
raise RuntimeError(result["dict_payload"].get("message"))
self._run_coro_blocking(
self._accessory_flow_manager_solver(
robot_model=robot_model,
req_id=req_id,
flow_manager_args=flow_manager_args,
)
)
return result["obj_payload"]
# def set_foot_pose(self, robot_model: str, foot_pose: FootPoseT, req_id: str | None = None, flow_manager_args: FlowManagerArgs | None = None) -> ResponseFootPoseT:
# """
# [Foot Pose 제어]
# - robot_model: 로봇 모델
# - foot_pose: 발 포즈 정보
# - req_id: 요청 ID (선택 사항)
# - flow_manager_args: 플로우 매니저 인자 (선택 사항)
# """
# if req_id is None:
# req_id = str(uuid.uuid4())
# # 1) RequestFootMove 객체 생성
# req = RequestFootMoveT()
# req.id = req_id
# req.pose = foot_pose
# # 2) 요청 전송
# result = self.zenoh_client.query_one(
# f"amr/{robot_model}/accessory/foot",
# flatbuffer_req_obj=req,
# flatbuffer_res_T_class=ResponseFootMoveT,
# flatbuffer_buf_size=2048,
# )
# # 3) 결과 처리 및 반환
# if result.get("obj_payload") is None:
# raise RuntimeError("Call Foot Pose failed: obj_payload is None")
# if flow_manager_args is not None:
# print(result["dict_payload"].get("result"))
# if result["dict_payload"].get("result") == "reject":
# raise RuntimeError(result["dict_payload"].get("message"))
# self._run_coro_blocking(
# self._accessory_flow_manager_solver(
# robot_model=robot_model,
# req_id=req_id,
# flow_manager_args=flow_manager_args,
# )
# )
# return result["obj_payload"]