diff --git a/api/server.py b/api/server.py index 787c004..3a5e596 100644 --- a/api/server.py +++ b/api/server.py @@ -287,6 +287,36 @@ def agv_plan(): return {"points": pts[::step] + (pts[-1:] if pts and (len(pts) - 1) % step else [])} +# ---------- the base's settings (the Lumi app's Map SETTINGS, 2026-11-18) ---------- +class BaseSettingBody(BaseModel): + name: str = Field(examples=["max_speed_linear"], description="max_speed_linear, max_speed_angular, pose_tolerance " + "or theta_tolerance") + value: float = Field(description="m/s, rad/s, m or rad; cut to the range the base page allows") + + +@app.get("/agv/settings", tags=["base"], summary="Four of the base page's configuration settings: values now and ranges") +def agv_settings(): + from robot import base_settings + try: + now, limits = base_settings.read(), base_settings.ranges() + except (OSError, RuntimeError, ValueError) as e: + raise HTTPException(502, f"base settings not available: {e}") + return {"settings": [{"name": n, "value": now[n], "min": s[1], "max": s[2], "step": s[3], "default": s[4]} + for n, s in limits.items()]} + + +@app.post("/agv/settings", tags=["base"], summary="Save one base setting, as the base page's configuration saves it") +def agv_settings_set(body: BaseSettingBody): + from robot import base_settings + if body.name not in base_settings.SETTINGS: + raise HTTPException(400, f"unknown setting {body.name}") + try: + saved = base_settings.write(body.name, body.value) + except (OSError, RuntimeError, ValueError) as e: + raise HTTPException(502, f"base did not save it: {e}") + return {"ok": True, "name": body.name, "value": saved} + + # ---------- songs (the Lumi app's Commands, 2026-11-18) ---------- class SingBody(BaseModel): id: str | None = Field(None, description="a song id from GET /songs; empty = any of them") diff --git a/robot/agv.py b/robot/agv.py index 3ea7f42..fdb70b1 100644 --- a/robot/agv.py +++ b/robot/agv.py @@ -34,7 +34,10 @@ NOTICES_KEEP = 50 def set_max_speed(linear, angular): - """Cap navigation and joy_control at `linear` m/s, `angular` rad/s (/api/set_params, 0.1-1.0 / 0.5-3.5).""" + """Cap navigation and joy_control at `linear` m/s, `angular` rad/s (/api/set_params, 0.1-1.0 / 0.5-3.5), never + above the base's own ceiling (robot/base_settings.py, the Lumi app's Map SETTINGS).""" + from robot import base_settings + linear, angular = base_settings.capped(linear, angular) return request(f"/api/set_params?max_speed_linear={linear:g}&max_speed_angular={angular:g}") diff --git a/robot/base_settings.py b/robot/base_settings.py new file mode 100644 index 0000000..be3835d --- /dev/null +++ b/robot/base_settings.py @@ -0,0 +1,101 @@ +"""The base's own settings the Lumi app's Map SETTINGS shows and changes: four of the base page's "configuration" +(:9001 robot-user-configuration.html), saved the way that page saves them: POST :9001/api/update_user_parameters +(kept by the base over a restart), then the ROS parameter itself (used at once). + +Max speed is the base's ceiling. Lumi's own drives send their speed before every move (robot/agv.py max_speed, +tasks/fetch.py NAV_SPEED_MPS, tasks/follow.py): it is cut to that ceiling here, so a lower one holds for them too. +Their turn speed is left as they send it (follow turns at up to 1.0 rad/s, above the base's 0.7 of 2026-11-18). + + python robot/base_settings.py # print them +""" +import json +import threading +import time +import urllib.request + +from robot import rosbridge + +BASE_PAGE = "http://192.168.10.10:9001" +# name: (ROS parameter, min, max, step, the base page's default); ranges as the base page allows them +SETTINGS = { + "max_speed_linear": ("api_params/max_speed_linear", 0.1, 0.7, 0.1, 0.7), # m/s; by robot type, see below + "max_speed_angular": ("api_params/max_speed_angular", 0.1, 3.5, 0.1, 3.5), # rad/s + "pose_tolerance": ("move_base/DWAPlannerROS/xy_goal_tolerance", 0.05, 0.5, 0.01, 0.3), # m + "theta_tolerance": ("move_base/DWAPlannerROS/yaw_goal_tolerance", 0.05, 1.0, 0.01, 0.2), # rad +} +# max speed's top (and default) by the base's robot type (/robot_global robot_type), as the base page sets it; ours is +# "WT" (1.2 m/s); other types keep 0.7 +SPEED_TOP = {"WT": 1.2, "OCEAN": 0.9} +_type = {"name": None} +CAP_FRESH_S = 60.0 # the speed ceiling is read again after this long +_cap = {"t": 0.0, "linear": None} +_lock = threading.Lock() + + +def _get(param): + v = rosbridge.call_service("/rosapi/get_param", {"name": "/" + param}).get("value") + try: + return float(json.loads(v)) if v not in (None, "") else None + except (ValueError, TypeError): + return None + + +def _robot_type(): + if _type["name"] is None: + v = rosbridge.call_service("/rosapi/get_param", {"name": "/robot_global"}).get("value") + _type["name"] = (json.loads(v) or {}).get("robot_type", "") if v else "" + return _type["name"] + + +def ranges(): + """SETTINGS with max speed's top and default for this robot's type (asks the base once).""" + out = dict(SETTINGS) + top = SPEED_TOP.get(_robot_type()) + if top: + param, lo, _, step, _ = SETTINGS["max_speed_linear"] + out["max_speed_linear"] = (param, lo, top, step, top) + return out + + +def read(): + """{name: value or None} as the base has them now; raises OSError when the base does not answer.""" + return {name: _get(s[0]) for name, s in SETTINGS.items()} + + +def write(name, value): + """Save one setting (cut to its range and step); returns the value saved. Raises KeyError for an unknown name, + OSError / RuntimeError when the base does not take it.""" + param, lo, hi, step, _ = ranges()[name] + value = round(round(min(hi, max(lo, float(value))) / step) * step, 3) + req = urllib.request.Request(f"{BASE_PAGE}/api/update_user_parameters", data=json.dumps({param: value}).encode(), + headers={"Content-Type": "application/json"}, method="POST") + with urllib.request.urlopen(req, timeout=4) as r: + reply = json.loads(r.read().decode() or "{}") + if reply.get("status") != "OK": + raise RuntimeError(f"base refused {name}: {reply.get('error_message') or reply}") + rosbridge.call_service("/rosapi/set_param", {"name": "/" + param, "value": json.dumps(value)}) + with _lock: + _cap["t"] = 0.0 # read the ceiling again at the next drive + return value + + +def ceiling(): + """The max speed ceiling (m/s), None when unknown; read at most every CAP_FRESH_S, never raises.""" + with _lock: + if time.monotonic() - _cap["t"] > CAP_FRESH_S: + try: + _cap["linear"] = _get(SETTINGS["max_speed_linear"][0]) + except (OSError, RuntimeError): + _cap["linear"] = None + _cap["t"] = time.monotonic() + return _cap["linear"] + + +def capped(linear, angular): + """Lumi's own drive speed with its forward speed cut to the base's ceiling; the turn speed as it is.""" + cl = ceiling() + return (min(linear, cl) if cl else linear), angular + + +if __name__ == "__main__": + print(read()) diff --git a/tests/test_driving.py b/tests/test_driving.py index b976278..398ba23 100644 --- a/tests/test_driving.py +++ b/tests/test_driving.py @@ -105,6 +105,9 @@ assert driving.say_move("back", 0.01, True) == "Okay, moving back 1 centimetre." tmp = Path(tempfile.mkdtemp()) fetch.STATE_FILE = tmp / "lumi_task.json" # never the real /dev/shm file sent = [] +from robot import base_settings # the base's speed ceiling (Map SETTINGS): none here +real_ceiling = base_settings.ceiling +base_settings.ceiling = lambda: None real_request = fetch.agv.request fetch.agv.request = lambda cmd, timeout=3.0: sent.append(cmd) or {} f = 1.0 @@ -224,6 +227,13 @@ fetch.agv.clearance = lambda x, y: 5.0 fetch.line_hits = real_line_hits fetch.agv.request, skills.moved = real_request, real_moved +# the base's ceiling cuts Lumi's own forward speed, never raises it, leaves the turn (a missing one leaves both) +base_settings.ceiling = lambda: 0.3 +assert base_settings.capped(0.5, 1.0) == (0.3, 1.0) and base_settings.capped(0.2, 0.1) == (0.2, 0.1) +base_settings.ceiling = lambda: None +assert base_settings.capped(0.5, 0.3) == (0.5, 0.3) +base_settings.ceiling = real_ceiling + # a task (a move by voice) ends a follow that runs first: two joy_control senders must never fight from tasks import follow follow._stop.clear()