|
| 1 | +"""Lekiwi host but for simulation""" |
| 2 | + |
| 3 | +#!/usr/bin/env python |
| 4 | + |
| 5 | +# Copyright 2024 The HuggingFace Inc. team. All rights reserved. |
| 6 | +# |
| 7 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | +# you may not use this file except in compliance with the License. |
| 9 | +# You may obtain a copy of the License at |
| 10 | +# |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +# |
| 13 | +# Unless required by applicable law or agreed to in writing, software |
| 14 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | +# See the License for the specific language governing permissions and |
| 17 | +# limitations under the License. |
| 18 | + |
| 19 | +import argparse |
| 20 | +import json |
| 21 | +import logging |
| 22 | +import time |
| 23 | + |
| 24 | +# import cv2 |
| 25 | +import zmq |
| 26 | +from lerobot.robots.lekiwi.config_lekiwi import LeKiwiHostConfig |
| 27 | + |
| 28 | +from .robot import LeKiwiMujoco, LeKiwiMujocoConfig |
| 29 | + |
| 30 | + |
| 31 | +class ZMQHandler: |
| 32 | + """LeKiwi Host agent for simulation.""" |
| 33 | + |
| 34 | + def __init__(self, config: LeKiwiHostConfig): |
| 35 | + """Initialize the LeKiwi Host agent for simulation.""" |
| 36 | + self.zmq_context = zmq.Context() |
| 37 | + self.zmq_cmd_socket = self.zmq_context.socket(zmq.PULL) |
| 38 | + self.zmq_cmd_socket.setsockopt(zmq.CONFLATE, 1) |
| 39 | + self.zmq_cmd_socket.bind(f"tcp://*:{config.port_zmq_cmd}") |
| 40 | + |
| 41 | + self.zmq_observation_socket = self.zmq_context.socket(zmq.PUSH) |
| 42 | + self.zmq_observation_socket.setsockopt(zmq.CONFLATE, 1) |
| 43 | + self.zmq_observation_socket.bind(f"tcp://*:{config.port_zmq_observations}") |
| 44 | + |
| 45 | + self.connection_time_s = config.connection_time_s |
| 46 | + self.watchdog_timeout_ms = config.watchdog_timeout_ms |
| 47 | + self.max_loop_freq_hz = config.max_loop_freq_hz |
| 48 | + |
| 49 | + def disconnect(self) -> None: |
| 50 | + """Disconnect the ZMQ sockets and context.""" |
| 51 | + self.zmq_observation_socket.close() |
| 52 | + self.zmq_cmd_socket.close() |
| 53 | + self.zmq_context.term() |
| 54 | + |
| 55 | + |
| 56 | +def main() -> None: |
| 57 | + """Main function to run the LeKiwi simulation host.""" |
| 58 | + parser = argparse.ArgumentParser( |
| 59 | + description="Run the LeKiwi simulation host to be accessed via lerobot.robot.LekiwiClient." |
| 60 | + ) |
| 61 | + |
| 62 | + parser.add_argument( |
| 63 | + "-l", |
| 64 | + "--level", |
| 65 | + choices=["DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL"], |
| 66 | + default="INFO", |
| 67 | + help="Set the logging level (default: INFO). Case-insensitive.", |
| 68 | + ) |
| 69 | + args = parser.parse_args() |
| 70 | + log_level = args.level.upper() |
| 71 | + logging.basicConfig( |
| 72 | + level=log_level, format="%(asctime)s | %(levelname)-8s | %(message)s", datefmt="%Y-%m-%d %H:%M:%S" |
| 73 | + ) |
| 74 | + logging.info("Configuring LeKiwi") |
| 75 | + robot_config = LeKiwiMujocoConfig() |
| 76 | + robot = LeKiwiMujoco(robot_config) |
| 77 | + |
| 78 | + logging.info("Connecting LeKiwi") |
| 79 | + robot.connect() |
| 80 | + |
| 81 | + logging.info("Starting HostAgent") |
| 82 | + host_config = LeKiwiHostConfig() |
| 83 | + host = ZMQHandler(host_config) |
| 84 | + |
| 85 | + last_cmd_time = time.time() |
| 86 | + watchdog_active = False |
| 87 | + logging.info("Waiting for commands...") |
| 88 | + try: |
| 89 | + # Business logic |
| 90 | + start = time.perf_counter() |
| 91 | + while robot.is_connected: |
| 92 | + # while duration < host.connection_time_s: |
| 93 | + loop_start_time = time.time() |
| 94 | + try: |
| 95 | + msg = host.zmq_cmd_socket.recv_string(zmq.NOBLOCK) |
| 96 | + data = dict(json.loads(msg)) |
| 97 | + logging.debug("Received command: %s", data) |
| 98 | + _action_sent = robot.send_action(data) |
| 99 | + last_cmd_time = time.time() |
| 100 | + watchdog_active = False |
| 101 | + except zmq.Again: |
| 102 | + if not watchdog_active: |
| 103 | + logging.warning("No command available") |
| 104 | + except Exception as e: |
| 105 | + logging.error("Message fetching failed: %s", e) |
| 106 | + |
| 107 | + now = time.time() |
| 108 | + if (now - last_cmd_time > host.watchdog_timeout_ms / 1000) and not watchdog_active: |
| 109 | + logging.warning( |
| 110 | + f"Command not received for more than {host.watchdog_timeout_ms} milliseconds. Stopping the base." |
| 111 | + ) |
| 112 | + watchdog_active = True |
| 113 | + robot.stop_base() |
| 114 | + |
| 115 | + last_observation = robot.get_observation() |
| 116 | + |
| 117 | + # # Encode ndarrays to base64 strings |
| 118 | + # for cam_key, _ in robot.cameras.items(): |
| 119 | + # ret, buffer = cv2.imencode( |
| 120 | + # ".jpg", last_observation[cam_key], [int(cv2.IMWRITE_JPEG_QUALITY), 90] |
| 121 | + # ) |
| 122 | + # if ret: |
| 123 | + # last_observation[cam_key] = base64.b64encode(buffer).decode("utf-8") |
| 124 | + # else: |
| 125 | + # last_observation[cam_key] = "" |
| 126 | + |
| 127 | + # Send the observation to the remote agent |
| 128 | + try: |
| 129 | + host.zmq_observation_socket.send_string(json.dumps(last_observation), flags=zmq.NOBLOCK) |
| 130 | + except zmq.Again: |
| 131 | + logging.debug("Dropping observation, no client connected") |
| 132 | + |
| 133 | + # Ensure a short sleep to avoid overloading the CPU. |
| 134 | + elapsed = time.time() - loop_start_time |
| 135 | + |
| 136 | + time.sleep(max(1 / host.max_loop_freq_hz - elapsed, 0)) |
| 137 | + time.perf_counter() - start |
| 138 | + print("Cycle time reached.") |
| 139 | + |
| 140 | + except KeyboardInterrupt: |
| 141 | + print("Keyboard interrupt received. Exiting...") |
| 142 | + finally: |
| 143 | + print("Shutting down Lekiwi Host.") |
| 144 | + robot.disconnect() |
| 145 | + host.disconnect() |
| 146 | + |
| 147 | + logging.info("Finished LeKiwi cleanly") |
| 148 | + |
| 149 | + |
| 150 | +if __name__ == "__main__": |
| 151 | + main() |
0 commit comments