"""Bridge-as-a-service: load one PCLA agent in the PCLA env and drive it from an external simulator that speaks a tiny socket protocol. The simulator (MetaDrive now, BeamNG later) sends a front camera + ego gps/imu/speed each step; we reply with the agent's throttle/steer/brake. Keeps the sim in its own Python env (no dependency clash with the 41 agents). Protocol (localhost TCP): 4-byte big-endian length + pickle payload. client -> {"cmd":"route","waypoints":[[lat,lon],...]} -> {"ok":True} client -> {"cmd":"step","camera":,"gps":[lat,lon,alt], "imu":[7],"speed":m/s,"dt":s} -> {"throttle","steer","brake"} client -> {"cmd":"close"} -> (server exits) """ import argparse, os, pickle, socket, struct, sys import numpy as np, cv2 _HERE = os.path.dirname(os.path.abspath(__file__)) _ROOT = os.path.dirname(os.path.dirname(_HERE)) # repo root (…/pcla_bridge/sim2sim -> repo) sys.path.insert(0, _ROOT) sys.path.insert(0, os.path.join(_ROOT, "pcla_bridge")) from pcla_bridge import PCLAAgentBridge # noqa: E402 from bridge_sample import build_sensors # noqa: E402 (front-cam marshalling) def _recvall(conn, n): buf = b"" while len(buf) < n: chunk = conn.recv(n - len(buf)) if not chunk: return None buf += chunk return buf def recv_msg(conn): hdr = _recvall(conn, 4) if not hdr: return None (n,) = struct.unpack(">I", hdr) return pickle.loads(_recvall(conn, n)) def send_msg(conn, obj): data = pickle.dumps(obj, protocol=4) conn.sendall(struct.pack(">I", len(data)) + data) def main(): ap = argparse.ArgumentParser() ap.add_argument("--agent", default="neat_aim2dsem") ap.add_argument("--host", default="127.0.0.1") ap.add_argument("--port", type=int, default=8770) a = ap.parse_args() print(f"[server] loading agent '{a.agent}' (this can take a bit) ...", flush=True) bridge = PCLAAgentBridge(a.agent) print("[server] agent expects:", sorted(bridge.sensor_layout()), flush=True) warned = set() srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) srv.bind((a.host, a.port)) srv.listen(1) print(f"[server] READY listening on {a.host}:{a.port}", flush=True) conn, _ = srv.accept() print("[server] client connected", flush=True) n = 0 try: while True: msg = recv_msg(conn) if msg is None or msg.get("cmd") == "close": break if msg["cmd"] == "route": bridge.set_route(msg["waypoints"]) send_msg(conn, {"ok": True, "n": len(msg["waypoints"])}) print(f"[server] route set: {len(msg['waypoints'])} waypoints", flush=True) continue if msg["cmd"] == "step": frame = cv2.imdecode(np.frombuffer(msg["camera"], np.uint8), cv2.IMREAD_COLOR) # BGR tele = {"gps": msg["gps"], "imu": msg["imu"], "speed": msg["speed"]} sensors = build_sensors(bridge, frame, tele, warned) # zero-fills any LiDAR lidar_bytes = msg.get("lidar") if lidar_bytes: # raw float32 Nx4 bytes cloud = np.frombuffer(lidar_bytes, np.float32).reshape(-1, 4).copy() for sid, spec in bridge.sensor_layout().items(): if spec["type"] == "sensor.lidar.ray_cast": sensors[sid] = cloud # bridge._marshal reshapes to Nx4 if "lidar_wired" not in warned: print(f"[server] wiring real LiDAR into '{sid}' ({len(cloud)} pts)", flush=True) warned.add("lidar_wired") ctrl = bridge.step(sensors, dt=msg.get("dt", 0.1)) send_msg(conn, {"throttle": float(ctrl.throttle), "steer": float(ctrl.steer), "brake": float(ctrl.brake)}) n += 1 finally: conn.close() srv.close() print(f"[server] done after {n} steps", flush=True) if __name__ == "__main__": main()