diff --git a/.gitignore b/.gitignore index 8b0ab3b1..3e5e4b88 100644 --- a/.gitignore +++ b/.gitignore @@ -47,6 +47,9 @@ ros2_aruco/ *.exe *.out *.app +# The launcher bundle is source, not a build result. +!packaging/macos/*.app +!packaging/macos/*.app/** ## Ignore Visual Studio temporary files, build results, and ## files generated by popular Visual Studio add-ons. diff --git a/compose.yaml b/compose.yaml index e15d0c3b..799227b0 100644 --- a/compose.yaml +++ b/compose.yaml @@ -191,3 +191,33 @@ services: - joy_source:=udp - joy_udp_bind:=0.0.0.0 - autoplay:=true + + # The real arm from Windows. The carrier relay (waybionic_teleop.carrier_relay) runs on + # Windows and the drive node connects out to it, so the carrier needs no published port. + # arm_profile_bench.yaml says the arm has no tool drive; closing RViz ends the station. + # Launching the arm shouldn't depend on the unit tests passing on this machine, which are + # timing-sensitive, so this image stops at the build stage; CI has run the tests. + wslg-arm: + <<: *wslg + profiles: [wslg-arm] + image: waybionic_ground_station:arm + build: + context: . + dockerfile: docker/Dockerfile + target: build + cache_from: + - ghcr.io/waybionic/waybionic_ground_station:jazzy + ports: + - 127.0.0.1:47300:47300/udp + command: + - ros2 + - launch + - waybionic_bringup + - ground_station.launch.py + - teleop:=true + - joy_source:=udp + - joy_udp_bind:=0.0.0.0 + - drive_interface:=slcan + - drive_channel:=socket://host.docker.internal:47320 + - arm_profile:=/waybionic_ws/install/waybionic_teleop/share/waybionic_teleop/config/arm_profile_bench.yaml + - exit_with_rviz:=true diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 599be972..14fa9e08 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -300,12 +300,12 @@ bridge needs `python3-opencv`. The controller plugs into the computer, not the Arduino. The computer runs teleop, the Cartesian moves, the joint limits and collision checks, the RViz twin and the -monitor, then sends MKS frames through the carrier board: a UNO R4 WiFi with a -TJA1051T transceiver running `waybionic_can/arduino/carrier_bridge`. The carrier -only passes frames between USB and the CAN bus, and reports its own status. +monitor, then sends MKS frames through the carrier board: a UNO R4 with an MCP2515 CAN +module running `waybionic_can/arduino/carrier_bridge_mcp2515`. The carrier only passes +frames between USB and the CAN bus, and reports its own status. ```text -controller -> computer (ROS 2) -> USB, 1 Mbaud -> carrier -> CAN, 1 Mbit/s -> 5 MKS drives +controller -> computer (ROS 2) -> USB -> carrier -> CAN, 500 kbit/s -> 5 MKS drives ``` `waybionic_teleop/config/arm_drives.yaml` maps the joints to the drives: CAN IDs 1 @@ -323,8 +323,9 @@ unloaded, and keep the E-stop within reach. The computer running ROS needs the carrier or a USB CAN adapter. Docker Desktop on Windows and macOS can't reach USB devices, so use native ROS on macOS -([RoboStack](../BuildInstructions.md#macos-native-ros-with-robostack)) or Linux, or -Docker on Linux with `--network host` for a SocketCAN adapter. +([RoboStack](../BuildInstructions.md#macos-native-ros-with-robostack)), the +[carrier relay on Windows](#on-windows) or Linux, or Docker on Linux with +`--network host` for a SocketCAN adapter. ### On a Mac @@ -344,14 +345,12 @@ then run these from the repository root. ``` 2. **Set up each drive once,** alone on the bus: give it its CAN ID (they all ship - as 1), then switch it to 1 Mbit/s. The carrier keeps its first bit rate until it - resets, so replug it, connect every drive, and check they all answer. + as 1). Leave them at the factory 500 kbit/s, the most the arm's MCP2515 carrier + runs. Then connect every drive and check they all answer. ```bash ./scripts/macos.sh drives set-id 1 3 # for example the elbow - ./scripts/macos.sh drives set-bitrate 3 1000000 - # after every drive is switched: replug the carrier - ./scripts/macos.sh drives --bitrate 1000000 scan + ./scripts/macos.sh drives scan --ids 1 2 3 4 5 ``` 3. **Start the ground station.** With `tool` removed from `drives` in @@ -380,6 +379,35 @@ then run these from the repository root. each joint a known angle, such as 10 degrees in RViz, and measure it on the arm; a different angle means its `gear_ratio` is wrong. +### Starting by double-click (Mac) + +After the [macOS setup](../BuildInstructions.md#macos-native-ros-with-robostack), install +the app once from the repository root: + +```bash +./scripts/macos.sh app +``` + +This puts **WayBionic Ground Station** in `~/Applications`; drag it to the Dock. The +copy in `packaging/macos/` also opens in place. Then, to start the arm: + +1. Plug in the carrier, the controller (USB or Bluetooth) and power the drives. +2. Double-click the app. The first time, it offers to run the setup in Terminal, which + takes 30 to 60 minutes; open the app again when that finishes. +3. If the carrier is not plugged in, a dialog says so: plug it in and choose *Try again*, + or choose *Without the arm* to run the simulation. With several USB serial devices + connected, it asks which one is the carrier. +4. It then starts the station exactly as `./scripts/macos.sh arm` does (the arm profile + and the saved zero included), with RViz filling the screen. The Arm setup panel there + walks through what is left: the controller, the zero pose, Start. + +Closing the RViz window, or quitting the app from the Dock, stops the station the way +Ctrl+C does, so each drive gets its stop first. The station's output goes to +`~/Library/Logs/WayBionic/` (the last 10 sessions are kept), and if it stops unexpectedly +the app offers to open the log. The app is not signed: if you download the repository as +a zip instead of cloning it, macOS asks you to confirm opening it once (right-click, then +Open). + ### Remote operator The controller can stay with an operator on another computer. On the operator's @@ -399,6 +427,67 @@ On the Mac, listen on the network: The receiver takes controller packets from any computer that can reach its port, so do this only on a private network. +### On Windows + +Docker Desktop can't open COM ports, so a small program on Windows, `carrier_relay`, +passes the carrier's port through `127.0.0.1:47320`, and the drive node in the container +connects to it as `socket://host.docker.internal:47320`. Besides +[Docker Desktop with WSLg](../BuildInstructions.md#windows-wslg), as for the other Windows +demos, it needs Python 3 on Windows and pyserial: + +```powershell +python -m pip install pyserial +``` + +Flash the carrier first, as in step 1 of [On a Mac](#on-a-mac) (from a Mac, or with the +Arduino IDE). + +**In one step:** plug in only the carrier, connect an Xbox controller and double-click +`scripts\windows-arm.cmd`. It starts Docker Desktop, the carrier bridge and the controller +bridge, then the ground station with `waybionic_teleop/config/arm_profile_bench.yaml` +(J1 to J5 driven, no tool). The first start builds the image, which takes a while. The Arm +setup panel in RViz then walks through what is left: put the arm in its zero pose, press +**Zero the arm**, then press Start on the controller. The zero is not kept between runs on +Windows, so do this every time. Closing RViz, or Ctrl+C in the script's window, stops the +ground station first, so each drive gets its stop, then the bridges. + +**Step by step,** from the repository root. The bridge serves one connection at a time, so +let each command finish before the next. If `docker` is not recognized, see +[its troubleshooting](../BuildInstructions.md#docker-is-not-recognized-on-windows). + +1. Start the bridge in its own PowerShell window and leave it running. It looks for the + Arduino's COM port each time it opens the carrier, so plugging the carrier in after it + starts, or replugging it under another COM number, is fine; with several Arduinos plugged + in, pass `--port COM5`. Wait for `Carrier open; waiting for the ground station`: the + drive node stops at start-up if nothing is listening. + + ```powershell + cd waybionic_teleop + python -m waybionic_teleop.carrier_relay + ``` + +2. Scan the drives from a second window: + + ```powershell + docker compose run --rm --build wslg-arm ros2 run waybionic_teleop mks_setup --channel socket://host.docker.internal:47320 scan --ids 1 2 3 4 5 + ``` + +3. Start the controller bridge in a third window, then the ground station: + + ```powershell + cd waybionic_teleop + python -m waybionic_teleop.xinput_bridge + ``` + + ```powershell + docker compose run --rm --build --service-ports wslg-arm + ``` + +Stopping the bridge or unplugging the carrier closes the connection, so the drive node +loses the carrier as it does when the USB cable is pulled on a Mac: every drive stops and +the arm must be zeroed again. The bridge listens only on `127.0.0.1`; keep it local, +because anything that connects to it can drive the arm. + ### On Linux With the carrier, set up the drives as in step 2 above, with `mks_setup`, then @@ -431,7 +520,8 @@ and zero as below. CI runs `waybionic_teleop/test/test_can_drives.py` over `vcan The encoders count from where the drives were powered on, so the host publishes no joint states and moves nothing until the arm is zeroed. Put the arm in the zero pose -(the pose RViz shows before anything moves), leave teleop disabled, and run: +(the pose RViz shows before anything moves), leave teleop disabled, and press **Zero the +arm** in the Arm setup panel (see [Start-up guide](#start-up-guide)), or run: ```bash ros2 service call /sim_arm_drives/zero std_srvs/srv/Trigger @@ -490,6 +580,78 @@ service waits. A refused stop frame is sent again on every tick, and Start is refused until it has gone out. After any stop, disable teleop and press Start again. +### Start-up guide + +The **Arm setup** panel (top of RViz's right-hand dock) lists what is left to do before the +arm can be operated, one thing at a time. The `setup_guide` node builds the list from the +same diagnostics the station already publishes, and also says each change in the terminal. + +| Step | Done when | If it isn't | +| --- | --- | --- | +| Carrier | the carrier reports on USB and its E-stop is not pressed | plug in its USB-C cable; if it is plugged in but silent, replug it or flash it | +| Drives | every drive that is switched on answers and passes its health check | the panel names the drive and what is wrong: no answer (with its CAN ID, so check its power and wiring, or switch its joint off, below), a failed move, or the health check, such as `following error: 6.3 deg off its target` | +| Controller | `/joy` input is arriving | connect an Xbox controller (USB or Bluetooth) and press a button | +| Zero | every drive that is switched on is zeroed or kept its saved zero | put the arm in its zero pose and press **Zero the arm** (it asks you to confirm) | +| Ready | teleop is enabled | press Start (the Menu button) on the controller | + +The controller needs no other step: the guide shows it as connected once input arrives. Once +every step is done, including Start, and the arm has stayed ready for four seconds, the panel +closes so the other panels get its room. It opens again when something needs you: a step +before Ready is to do or blocked, such as the controller dropping out, a drive losing its zero +or the carrier being unplugged, or Ready is blocked because the drives stopped the arm. A step +that is only being checked does not open it, and neither does stopping teleop (B or Start), +which leaves only Start to press. The panel's close button, or Panels > SetupPanel, shows or +hides it by hand, and it is not hidden again until the arm next becomes ready. + +If the guide itself is not running, the panel says so. A station started without the arm, such +as the plain `wslg` viewer, has no guide: the arm launchers (`scripts\windows-arm.cmd`, +`./scripts/macos.sh arm`) start it with `teleop:=true`. Nothing in the panel moves the arm. + +### Switching joints off + +The **Joint control** panel, below Arm setup, has a checkbox for each joint (J1 to J5 and the +tool). Unchecking one switches that joint off: + +- The drive stays powered and holds where it is. It is not released, so the joint does not + fall or move by itself. +- The sticks and triggers that were mapped to it do nothing, so the controller no longer + vibrates when you push a stick that needs a joint you don't want. The Cartesian and + incision groups need every joint, so they are left out of the group cycle while any joint + is off or unfitted. +- A drive whose joints are all off may be faulty or missing: it no longer stops the arm, + keeps the zero service from succeeding or keeps the arm from being enabled. The two wrist + drives move both wrist joints together, so switching off only J4 or only J5 still needs both + drives, which then hold that joint; switch off both to ignore a wrist drive. + +A change is only taken while teleop is stopped and no joint command has arrived for a second, +as for zeroing. Otherwise the panel shows why, and the box stays as it was. Turning a joint +back on needs its drive answering and zeroed before the arm can be enabled again, so after +fitting or repairing a drive, put the arm in the zero pose and zero it. + +The state is not saved: after a restart every fitted joint is on. A joint that has no drive +at all, such as the tool on the bench arm, is shown as *no drive* and cannot be switched +here. It comes from the arm profile (`~/.waybionic/arm_profile.yaml` on a Mac, +`waybionic_teleop/config/arm_profile_bench.yaml` for the Windows launcher): + +```yaml +# Bench arm: J1 to J5 have a drive (CAN IDs 1 to 5), and there is no tool. +fitted_drives: [base_yaw, shoulder, elbow, wrist_left, wrist_right] +locked_joints: {tool_grip: 0.0} +``` + +To fit another drive later, give it its CAN ID (`./scripts/macos.sh drives set-id 1 6` with +only that drive on the bus), add it to `fitted_drives`, delete its joint from +`locked_joints`, restart the station and zero. Its joint then has a checkbox like the +others. A drive that isn't wired is left out of `fitted_drives` and its joints are locked, as +the shoulder's were before it was wired: `locked_joints: {joint_2: 0.0, tool_grip: 0.0}`. + +Without the panel, from a terminal: + +```bash +ros2 service call /arm/joint_3/set_enabled std_srvs/srv/SetBool "{data: false}" +ros2 topic echo /arm/joint_control +``` + ### Powered hand-guiding Powered hand-guiding is not enabled yet. A stopped drive holds position; disabling diff --git a/packaging/macos/WayBionic Ground Station.app/Contents/Info.plist b/packaging/macos/WayBionic Ground Station.app/Contents/Info.plist new file mode 100644 index 00000000..0077ce83 --- /dev/null +++ b/packaging/macos/WayBionic Ground Station.app/Contents/Info.plist @@ -0,0 +1,24 @@ + + + + + CFBundleName + WayBionic Ground Station + CFBundleDisplayName + WayBionic Ground Station + CFBundleIdentifier + org.waybionic.groundstation + CFBundleExecutable + WayBionicGroundStation + CFBundlePackageType + APPL + CFBundleShortVersionString + 0.1 + CFBundleVersion + 1 + LSMinimumSystemVersion + 13.0 + NSHighResolutionCapable + + + diff --git a/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation b/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation new file mode 100755 index 00000000..33900a7e --- /dev/null +++ b/packaging/macos/WayBionic Ground Station.app/Contents/MacOS/WayBionicGroundStation @@ -0,0 +1,193 @@ +#!/bin/bash +# Double-click launcher for the WayBionic ground station on a Mac. +# +# It checks that the station is set up and that the carrier is plugged in, then starts the +# station for the real arm (scripts/macos.sh arm). Whatever it cannot fix itself becomes a +# dialog that says what to do. The station's output goes to ~/Library/Logs/WayBionic. See the +# operator guide, "Starting the station by double-click". +# +# Without a screen: WAYBIONIC_APP_DRY_RUN=1 prints the command instead of running it, and +# WAYBIONIC_APP_ANSWER is the answer every dialog gets. + +set -u + +TITLE="WayBionic Ground Station" +APP="$(cd "$(dirname "$0")/../.." && pwd)" +LOG_DIR="$HOME/Library/Logs/WayBionic" +KEEP_LOGS=10 + +# Finder starts apps with a bare PATH, without Homebrew or Miniforge. +export PATH="/opt/homebrew/bin:/opt/homebrew/Caskroom/miniforge/base/bin:/usr/local/bin:$PATH" + +# ask TEXT BUTTON...: show a dialog, print the button that was pressed (nothing if it was closed). +ask() { + if [[ -n "${WAYBIONIC_APP_ANSWER:-}" ]]; then + printf '%s\n' "$WAYBIONIC_APP_ANSWER" + return + fi + osascript - "$TITLE" "$@" <<'APPLESCRIPT' 2>/dev/null +on run argv + set theTitle to item 1 of argv + set theText to item 2 of argv + set theButtons to items 3 thru -1 of argv + try + set answer to display dialog theText with title theTitle buttons theButtons default button (last item of theButtons) with icon note + return button returned of answer + on error + return "" + end try +end run +APPLESCRIPT +} + +# pick TEXT ITEM...: show a list, print the item that was chosen (nothing if it was closed). +pick() { + if [[ -n "${WAYBIONIC_APP_ANSWER:-}" ]]; then + printf '%s\n' "$WAYBIONIC_APP_ANSWER" + return + fi + osascript - "$TITLE" "$@" <<'APPLESCRIPT' 2>/dev/null +on run argv + set theTitle to item 1 of argv + set theText to item 2 of argv + set theItems to items 3 thru -1 of argv + set chosen to choose from list theItems with title theTitle with prompt theText + if chosen is false then return "" + return item 1 of chosen +end run +APPLESCRIPT +} + +find_root() { + local saved="$APP/Contents/Resources/repo_root" + if [[ -r "$saved" ]]; then + tr -d '\n' <"$saved" + else + # Opened from packaging/macos inside the repository. + (cd "$APP/../../.." 2>/dev/null && pwd) + fi +} + +in_terminal() { + osascript -e 'on run argv + tell application "Terminal" + activate + do script (item 1 of argv) + end tell + end run' "$1" >/dev/null 2>&1 +} + +# descendants PID: print the process IDs below a process. +# shellcheck disable=SC2329 # called by stop_station, which is called from a trap +descendants() { + local child + for child in $(pgrep -P "$1" 2>/dev/null); do + echo "$child" + descendants "$child" + done +} + +# Ask the station to shut down as Ctrl+C in Terminal would: the drives are stopped first. +# shellcheck disable=SC2329 # called from a trap +stop_station() { + local pid sent="" + for pid in $(descendants "$child"); do + if ps -o command= -p "$pid" 2>/dev/null | grep -q 'ros2 launch'; then + kill -INT "$pid" 2>/dev/null + sent=1 + fi + done + if [[ -z "$sent" ]]; then + # Still setting itself up: nothing to shut down gracefully yet, and a background job of + # this script ignores SIGINT, so end it with TERM. + for pid in $(descendants "$child") "$child"; do + kill -TERM "$pid" 2>/dev/null + done + fi +} + +carrier_ports() { + compgen -G "${WAYBIONIC_APP_PORT_GLOB:-/dev/cu.usbmodem*}" || true +} + +ROOT="$(find_root)" +if [[ -z "$ROOT" || ! -x "$ROOT/scripts/macos.sh" ]]; then + ask "I can't find the WayBionic folder. Run ./scripts/macos.sh app from inside it to set this app up again." "Quit" >/dev/null + exit 1 +fi + +if [[ ! -f "$ROOT/install/setup.bash" ]]; then + answer="$(ask "WayBionic has not been set up on this Mac yet. Setting up downloads a few GB and takes 30 to 60 minutes. Terminal shows its progress; open this app again when it finishes." "Not now" "Set up")" + if [[ "$answer" == "Set up" ]]; then + if [[ -n "${WAYBIONIC_APP_DRY_RUN:-}" ]]; then + echo "would run in a Terminal: cd $ROOT && ./scripts/macos.sh setup" + else + in_terminal "cd $(printf '%q' "$ROOT") && ./scripts/macos.sh setup" + fi + fi + exit 0 +fi + +command=("$ROOT/scripts/macos.sh" arm) +while [[ -z "${WAYBIONIC_CARRIER:-}" ]]; do + ports=() + while IFS= read -r port; do + [[ -n "$port" ]] && ports+=("$port") + done < <(carrier_ports) + case "${#ports[@]}" in + 1) + export WAYBIONIC_CARRIER="${ports[0]}" + ;; + 0) + answer="$(ask "The carrier is not plugged in. Connect the Arduino's USB-C cable to this Mac, then choose Try again." "Quit" "Without the arm" "Try again")" + case "$answer" in + "Try again") ;; + "Without the arm") + command=("$ROOT/scripts/macos.sh" launch teleop:=true) + break + ;; + *) exit 0 ;; + esac + ;; + *) + choice="$(pick "Several USB serial devices are connected. Which one is the carrier?" "${ports[@]}")" + [[ -n "$choice" ]] || exit 0 + export WAYBIONIC_CARRIER="$choice" + ;; + esac +done + +if [[ -n "${WAYBIONIC_APP_DRY_RUN:-}" ]]; then + echo "would run in $ROOT: ${command[*]} (carrier: ${WAYBIONIC_CARRIER:-none})" + exit 0 +fi + +mkdir -p "$LOG_DIR" +log="$LOG_DIR/station-$(date +%Y-%m-%d-%H%M%S).log" +# shellcheck disable=SC2012 +for old in $(ls -1t "$LOG_DIR"/station-*.log 2>/dev/null | tail -n +"$((KEEP_LOGS + 1))"); do + rm -f "$old" +done + +cd "$ROOT" || exit 1 +# The trap comes first so that a quit during start-up is not lost; one that arrives before the +# station has a process ID is carried out right after it is started. +child="" +stopping="" +trap 'stopping=1; [[ -n "$child" ]] && stop_station' TERM INT HUP +"${command[@]}" exit_with_rviz:=true >"$log" 2>&1 & +child=$! +[[ -z "$stopping" ]] || stop_station +status=0 +while kill -0 "$child" 2>/dev/null; do + wait "$child" + status=$? +done +trap - TERM INT HUP + +# Closing the window or Ctrl+C ends with 0 or 130; anything else is worth a look. +if [[ -z "$stopping" ]] && ((status != 0 && status != 130)); then + answer="$(ask "The ground station stopped (code $status). The log says why." "Close" "Show the log")" + [[ "$answer" == "Show the log" ]] && open "$log" +fi +exit 0 diff --git a/scripts/macos.sh b/scripts/macos.sh index 9ef21c7e..06035273 100755 --- a/scripts/macos.sh +++ b/scripts/macos.sh @@ -7,6 +7,9 @@ ENV_FILE="$ROOT/robostack.yaml" MANAGER="" ENV_EXISTS=false +# Finder, cron and other bare environments have no Homebrew or Miniforge on the PATH. +export PATH="$PATH:/opt/homebrew/bin:/opt/homebrew/Caskroom/miniforge/base/bin:/usr/local/bin" + fail() { echo "error: $*" >&2 exit 1 @@ -25,6 +28,8 @@ Commands: (the R4's own CAN with a TJA1051T transceiver) drives Set up the MKS drives through the carrier, e.g. drives scan (see mks_setup) arm Drive the real arm: controller on this Mac, carrier on USB + app Install "WayBionic Ground Station.app" in ~/Applications (or the folder given), to + start the station by double-click run Run any command inside the ROS workspace The carrier is found as the only /dev/cu.usbmodem* port; set WAYBIONIC_CARRIER to choose. @@ -218,6 +223,21 @@ flash_carrier() { echo "Flashed $name" } +install_app() { + local source="$ROOT/packaging/macos/WayBionic Ground Station.app" + local destination="${1:-$HOME/Applications}/WayBionic Ground Station.app" + + [[ -d "$source" ]] || fail "the app bundle is missing: $source" + mkdir -p "$(dirname "$destination")" + rm -rf "$destination" + cp -R "$source" "$destination" + # The copy can live anywhere, so it is told where this folder is. + mkdir -p "$destination/Contents/Resources" + printf '%s\n' "$ROOT" > "$destination/Contents/Resources/repo_root" + echo "Installed $destination" + echo "Double-click it, or drag it to the Dock." +} + command_name="${1:-help}" if [[ $# -gt 0 ]]; then shift @@ -271,6 +291,9 @@ case "$command_name" in joy_source:=device drive_interface:=slcan drive_channel:="$CARRIER" \ arm_profile:="$profile" drive_zero_state:="$zero_state" "$@" ;; + app) + install_app "$@" + ;; run) [[ $# -gt 0 ]] || fail "run requires a command" prepare diff --git a/scripts/windows-arm.cmd b/scripts/windows-arm.cmd new file mode 100644 index 00000000..c04c8a63 --- /dev/null +++ b/scripts/windows-arm.cmd @@ -0,0 +1,3 @@ +@echo off +rem Drives the real arm from Windows. Plug in the carrier, then double-click this file or run it from a terminal. +powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0windows-arm.ps1" \ No newline at end of file diff --git a/scripts/windows-arm.ps1 b/scripts/windows-arm.ps1 new file mode 100644 index 00000000..23b64d4e --- /dev/null +++ b/scripts/windows-arm.ps1 @@ -0,0 +1,105 @@ +# Drives the real arm from Windows in one step: Docker Desktop, the carrier bridge, the +# controller bridge and the ground station. Docker Desktop cannot open COM ports, so the +# carrier bridge relays the carrier's port to 127.0.0.1:47320 and the drive node connects to it. +# Run windows-arm.cmd, or: powershell -ExecutionPolicy Bypass -File scripts\windows-arm.ps1 + +$root = Split-Path -Parent $PSScriptRoot +$teleop = Join-Path $root 'waybionic_teleop' +$carrierPort = 47320 + +$docker = Join-Path $env:LOCALAPPDATA 'Programs\DockerDesktop\resources\bin\docker.exe' +if (-not (Test-Path $docker)) { + $command = Get-Command docker -ErrorAction SilentlyContinue + if (-not $command) { + Write-Error 'Docker Desktop is not installed; see BuildInstructions.md.' + exit 1 + } + $docker = $command.Source +} + +& $docker info *> $null +if ($LASTEXITCODE -ne 0) { + $app = @( + (Join-Path $env:LOCALAPPDATA 'Programs\DockerDesktop\Docker Desktop.exe'), + (Join-Path $env:ProgramFiles 'Docker\Docker\Docker Desktop.exe') + ) | Where-Object { Test-Path $_ } | Select-Object -First 1 + if (-not $app) { + Write-Error 'Docker is not running and Docker Desktop was not found.' + exit 1 + } + Write-Host 'Starting Docker Desktop...' + Start-Process $app + $deadline = (Get-Date).AddMinutes(3) + do { + Start-Sleep -Seconds 3 + & $docker info *> $null + } until ($LASTEXITCODE -eq 0 -or (Get-Date) -gt $deadline) + if ($LASTEXITCODE -ne 0) { + Write-Error 'Docker Desktop did not start within 3 minutes.' + exit 1 + } +} + +$python = $null +$pythonArguments = @() +foreach ($name in 'python', 'python3', 'py') { + $command = Get-Command $name -ErrorAction SilentlyContinue + if (-not $command) { + continue + } + $prefix = if ($command.Name -eq 'py.exe') { @('-3') } else { @() } + & $command.Source @prefix -c 'import sys; sys.exit(sys.version_info[0] != 3)' *> $null + if ($LASTEXITCODE -eq 0) { + $python, $pythonArguments = $command, $prefix + break + } +} +if (-not $python) { + Write-Error 'The real arm needs Python 3 on Windows for the carrier bridge.' + exit 1 +} +& $python.Source @pythonArguments -c 'import serial' *> $null +if ($LASTEXITCODE -ne 0) { + Write-Error 'The carrier bridge needs pyserial: python -m pip install pyserial' + exit 1 +} + +$carrier = $null +$controller = $null +try { + $carrier = Start-Process -FilePath $python.Source -PassThru -WorkingDirectory $teleop ` + -ArgumentList ($pythonArguments + @('-m', 'waybionic_teleop.carrier_relay')) + + Write-Host ('Waiting for the carrier (up to a minute): plug it in if you have not; the ' + + 'bridge window says what it sees...') + $deadline = (Get-Date).AddSeconds(60) + do { + Start-Sleep -Milliseconds 500 + $listening = Get-NetTCPConnection -LocalPort $carrierPort -State Listen ` + -ErrorAction SilentlyContinue + } until ($listening -or $carrier.HasExited -or (Get-Date) -gt $deadline) + if (-not $listening) { + Write-Error ('The carrier bridge is not ready. Plug in only the carrier, or run ' + + 'python -m waybionic_teleop.carrier_relay from waybionic_teleop to see why.') + exit 1 + } + + $controller = Start-Process -FilePath $python.Source -PassThru -WorkingDirectory $teleop ` + -ArgumentList ($pythonArguments + @('-m', 'waybionic_teleop.xinput_bridge')) + + Push-Location $root + try { + Write-Host 'Starting the ground station; press Ctrl+C here to stop.' + Write-Host ('When RViz opens, follow its Arm setup panel: put the arm in its zero pose, ' + + 'press Zero the arm, then press Start (Menu) on the controller. Close RViz to stop.') + & $docker compose run --rm --build --service-ports wslg-arm + } finally { + Pop-Location + } +} finally { + foreach ($process in $controller, $carrier) { + if ($process -and -not $process.HasExited) { + Stop-Process -Id $process.Id + } + } +} \ No newline at end of file diff --git a/waybionic_bringup/launch/ground_station.launch.py b/waybionic_bringup/launch/ground_station.launch.py index 10134382..56b875b8 100644 --- a/waybionic_bringup/launch/ground_station.launch.py +++ b/waybionic_bringup/launch/ground_station.launch.py @@ -5,10 +5,11 @@ from launch import LaunchDescription from launch.actions import ( - DeclareLaunchArgument, IncludeLaunchDescription, LogInfo, OpaqueFunction, + DeclareLaunchArgument, EmitEvent, IncludeLaunchDescription, LogInfo, OpaqueFunction, RegisterEventHandler) from launch.conditions import IfCondition -from launch.event_handlers import OnShutdown +from launch.event_handlers import OnProcessExit, OnShutdown +from launch.events import Shutdown from launch.launch_description_sources import PythonLaunchDescriptionSource from launch.substitutions import ( AndSubstitution, Command, EqualsSubstitution, IfElseSubstitution, LaunchConfiguration, @@ -26,6 +27,7 @@ BOOLEAN_OPTIONS = { 'launch_rviz': 'true', 'rviz_maximized': 'true', + 'exit_with_rviz': 'false', 'use_joint_state_publisher_gui': 'true', 'use_diagnostics': 'true', 'use_mock_diagnostics': 'true', @@ -131,7 +133,7 @@ def _launch_rviz(context): live_diagnostics = OrSubstitution( OrSubstitution(LaunchConfiguration('demo_mode'), LaunchConfiguration('teleop')), LaunchConfiguration('camera')) - return [Node( + rviz = Node( package='waybionic_rviz_plugins' if maximized else 'rviz2', executable='ground_station_rviz' if maximized else 'rviz2', name='rviz2', output='screen', @@ -144,7 +146,14 @@ def _launch_rviz(context): NotSubstitution(live_diagnostics))}, {'diagnostics_topic': LaunchConfiguration('diagnostics_topic')} ] - )] + ) + actions = [rviz] + if IfCondition(LaunchConfiguration('exit_with_rviz')).evaluate(context): + # Closing the window ends the session, so no node is left holding the carrier. + actions.append(RegisterEventHandler(OnProcessExit( + target_action=rviz, + on_exit=[EmitEvent(event=Shutdown(reason='RViz was closed'))]))) + return actions def generate_launch_description(): @@ -265,6 +274,10 @@ def generate_launch_description(): 'rviz_maximized', default_value='true', choices=BOOLEAN_CHOICES, description='Fill the screen with RViz while keeping its panels and controls visible') + exit_with_rviz_arg = DeclareLaunchArgument( + 'exit_with_rviz', default_value='false', choices=BOOLEAN_CHOICES, + description='Shut every node down when the RViz window is closed') + rviz_config_arg = DeclareLaunchArgument( 'rvizconfig', default_value=default_rviz_config_path, description='Absolute path to rviz config file') @@ -332,6 +345,12 @@ def generate_launch_description(): arm_profile, sim_time] ) + # Tells the operator what to do next to start the arm (see waybionic_teleop/setup_guide.py). + setup_guide_node = Node( + package='waybionic_teleop', executable='setup_guide', name='setup_guide', + condition=IfCondition(teleop), parameters=[diagnostics_topic, sim_time] + ) + drives_node = Node( package='waybionic_teleop', executable='sim_arm_drives', name='sim_arm_drives', output='screen', condition=IfCondition(teleop), @@ -404,8 +423,9 @@ def generate_launch_description(): joy_source_arg, autoplay_arg, joy_udp_bind_arg, joy_udp_port_arg, follow_camera_arg, use_sim_time_arg, camera_arg, camera_bind_arg, camera_log_arg, - launch_rviz_arg, rviz_maximized_arg, rviz_config_arg, file_check, + launch_rviz_arg, rviz_maximized_arg, exit_with_rviz_arg, rviz_config_arg, file_check, rsp_node, jsp_gui_node, joint_demo_node, - joy_node, joy_udp_node, autoplay_node, teleop_node, drives_node, camera_follower_node, + joy_node, joy_udp_node, autoplay_node, teleop_node, drives_node, setup_guide_node, + camera_follower_node, temp_diag_pub_node, camera_launch, rviz_node ]) diff --git a/waybionic_bringup/rviz/waybionic_unified.rviz b/waybionic_bringup/rviz/waybionic_unified.rviz index 5b59a973..ab1ed498 100644 --- a/waybionic_bringup/rviz/waybionic_unified.rviz +++ b/waybionic_bringup/rviz/waybionic_unified.rviz @@ -28,6 +28,10 @@ Panels: Name: Time SyncMode: 0 SyncSource: "" + - Class: waybionic_rviz_plugins/SetupPanel + Name: SetupPanel + - Class: waybionic_rviz_plugins/JointControlPanel + Name: JointControlPanel - Class: waybionic_rviz_plugins/DiagnosticsPanel Diagnostics Topic: /diagnostics Name: DiagnosticsPanel @@ -208,12 +212,16 @@ Visualization Manager: Window Geometry: DiagnosticsPanel: collapsed: false + JointControlPanel: + collapsed: false + SetupPanel: + collapsed: false Displays: collapsed: false Height: 800 Hide Left Dock: false Hide Right Dock: false - QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002d9fc0200000001fc00000014000002d90000003a01000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000001600fffffffb0000000a005600690065007700730100000000ffffffff0000001600fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000001600fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000001600ffffff00000001000001b8000002d9fc0200000001fb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000014000002d90000001600ffffff00000003000005000000002dfc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002d900000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002b4fc0200000001fc00000014000002b40000007601000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000005200fffffffb0000000a005600690065007700730100000000ffffffff0000005200fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000005200fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000005200ffffff00000001000001b8000002b4fc0200000003fb000000140053006500740075007000500061006e0065006c0100000014000000970000005200fffffffb00000022004a006f0069006e00740043006f006e00740072006f006c00500061006e0065006c01000000b1000000970000005200fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c010000014e0000017a0000005200ffffff000000030000050000000052fc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002b400000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 Selection: collapsed: false Time: diff --git a/waybionic_bringup/test/test_cartesian_launch.py b/waybionic_bringup/test/test_cartesian_launch.py index 3231f02f..219a1e93 100644 --- a/waybionic_bringup/test/test_cartesian_launch.py +++ b/waybionic_bringup/test/test_cartesian_launch.py @@ -73,6 +73,25 @@ def hold(seconds, *pressed, record=False, **axes): if record: samples.append(tip()) + def gate(): + row = diagnostics.get('arm.command_gate') + return row.values[0].value if row is not None else 'missing' + + def teleop_state(): + row = diagnostics.get('teleop.state') + return row.values[0].value if row is not None else 'missing' + + def enable(): + # The drives stop, and want Start pressed afresh, if the host stalls for half a + # second, as a busy CI runner can. An operator would press Start again. + for _ in range(6): + hold(0.2, 'start') + # Diagnostics are reported every 0.5 s. + hold(0.6) + if gate() == 'enabled' and teleop_state() == 'enabled': + return + self.fail(f'the drives never accepted Start: {diagnostics["arm.command_gate"]}') + try: deadline = time.monotonic() + 30.0 # Press Start only once teleop has loaded the robot description (the group row @@ -82,22 +101,32 @@ def hold(seconds, *pressed, record=False, **axes): and diagnostics['teleop.input'].level == DiagnosticStatus.OK and buffer.can_transform('base_link', 'tool_link', Time())): hold(0.1) - hold(0.2, 'start') + enable() hold(0.3, 'y') # Bend the shoulder, elbow and wrist away from the upright pose. hold(1.0, left_x=1.0, left_y=1.0, right_y=1.0) hold(0.5) hold(0.3, 'y') - # Diagnostics are reported every 0.5 s. hold(0.6) - self.assertEqual(diagnostics['teleop.state'].values[0].value, 'enabled') + if gate() != 'enabled' or teleop_state() != 'enabled': + enable() self.assertEqual(diagnostics['teleop.group'].values[0].value, 'cartesian') - start, tilt = tip() - hold(1.5, 'left_bumper', record=True, left_x=1.0) - hold(0.5, record=True) + for _ in range(3): + samples.clear() + start, tilt = tip() + hold(1.5, 'left_bumper', record=True, left_x=1.0) + hold(0.5, record=True) + if gate() == 'enabled': + break + # The drives stopped during the cut, so it says nothing about the line. + enable() travel = samples[-1][0][1] - start[1] worst = max(math.hypot(x - start[0], z - start[2]) for (x, y, z), _ in samples) - self.assertGreater(travel, 0.025, 'the tool tip did not move sideways') + self.assertGreater( + travel, 0.025, + f'the tool tip did not move sideways (drives {gate()}: ' + f'{diagnostics["arm.command_gate"].message!r}; teleop: ' + f'{diagnostics["teleop.state"].message!r})') self.assertLess(worst, 0.0005, f'the tip left the line by {worst * 1000:.2f} mm') self.assertLess(max(abs(value - tilt) for _, value in samples), 0.005) finally: diff --git a/waybionic_bringup/test/test_launch_options.py b/waybionic_bringup/test/test_launch_options.py index 8802457a..d68f2c21 100644 --- a/waybionic_bringup/test/test_launch_options.py +++ b/waybionic_bringup/test/test_launch_options.py @@ -5,9 +5,11 @@ from unittest.mock import patch from launch import LaunchContext -from launch.actions import DeclareLaunchArgument, RegisterEventHandler +from launch.actions import DeclareLaunchArgument, EmitEvent, RegisterEventHandler from launch.conditions import IfCondition +from launch.event_handlers import OnProcessExit from launch.events import Shutdown +from launch.events.process import ProcessExited from launch_ros.actions import Node import pytest import yaml @@ -116,6 +118,20 @@ def test_rviz_keeps_live_diagnostics_selection(context, mock, mode): assert IfCondition(use_mock).evaluate(context) == (mock == 'true' and mode is None) +def test_rviz_exit_ends_the_launch_only_when_asked(context): + assert declarations()['exit_with_rviz'].default_value[0].text == 'false' + context.launch_configurations['exit_with_rviz'] = 'false' + assert [type(action) for action in MODULE._launch_rviz(context)] == [Node] + context.launch_configurations['exit_with_rviz'] = 'true' + rviz, handler = MODULE._launch_rviz(context) + assert isinstance(handler, RegisterEventHandler) + assert isinstance(handler.event_handler, OnProcessExit) + closed = ProcessExited(action=rviz, name='rviz2', cmd=['rviz2'], cwd=None, env=None, + pid=1, returncode=0) + assert any(isinstance(action, EmitEvent) + for action in handler.event_handler.handle(closed, context)) + + def test_default_window_geometry(): config = yaml.safe_load((ROOT / 'rviz/waybionic_unified.rviz').read_text()) geometry = config['Window Geometry'] diff --git a/waybionic_bringup/test/test_macos_app.py b/waybionic_bringup/test/test_macos_app.py new file mode 100644 index 00000000..f03769e0 --- /dev/null +++ b/waybionic_bringup/test/test_macos_app.py @@ -0,0 +1,247 @@ +"""The double-click launcher for macOS decides what to do without needing a screen.""" + +import os +from pathlib import Path +import plistlib +import shlex +import shutil +import signal +import subprocess +import sys +import time + +import pytest + +APP = (Path(__file__).resolve().parents[2] / 'packaging' / 'macos' + / 'WayBionic Ground Station.app') +LAUNCHER = APP / 'Contents' / 'MacOS' / 'WayBionicGroundStation' + + +@pytest.fixture +def station(tmp_path): + """Return (run, root): run the app copied beside a made-up repository, set up or not.""" + root = tmp_path / 'repo' + (root / 'scripts').mkdir(parents=True) + (root / 'scripts' / 'macos.sh').write_text('#!/bin/bash\n', encoding='utf-8') + (root / 'scripts' / 'macos.sh').chmod(0o755) + app = tmp_path / 'Applications' / APP.name + shutil.copytree(APP, app) + (app / 'Contents' / 'Resources').mkdir(exist_ok=True) + (app / 'Contents' / 'Resources' / 'repo_root').write_text(f'{root}\n', encoding='utf-8') + ports = tmp_path / 'dev' + ports.mkdir() + + def run(*devices, answer=None, set_up=True, **environment): + for item in ports.iterdir(): + item.unlink() + for device in devices: + (ports / device).touch() + installed = root / 'install' / 'setup.bash' + if set_up: + installed.parent.mkdir(exist_ok=True) + installed.touch() + env = {'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin', 'WAYBIONIC_APP_DRY_RUN': '1', + 'WAYBIONIC_APP_PORT_GLOB': str(ports / 'cu.usbmodem*'), **environment} + if answer is not None: + env['WAYBIONIC_APP_ANSWER'] = answer + return subprocess.run( + [str(app / 'Contents' / 'MacOS' / LAUNCHER.name)], env=env, capture_output=True, + text=True, timeout=30, check=False) + return run, root, ports + + +def test_the_bundle_describes_an_app_that_runs_the_launcher(): + info = plistlib.loads((APP / 'Contents' / 'Info.plist').read_bytes()) + assert info['CFBundlePackageType'] == 'APPL' + executable = APP / 'Contents' / 'MacOS' / info['CFBundleExecutable'] + assert executable == LAUNCHER and os.access(executable, os.X_OK) + + +def test_the_only_carrier_starts_the_arm(station): + run, root, ports = station + result = run('cu.usbmodem1101') + assert result.returncode == 0, result.stderr + assert result.stdout.strip() == ( + f'would run in {root}: {root}/scripts/macos.sh arm (carrier: {ports}/cu.usbmodem1101)') + + +def test_a_carrier_chosen_in_the_environment_is_not_searched_for(station): + run, root, _ = station + result = run(WAYBIONIC_CARRIER='/dev/cu.mine') + assert result.stdout.strip().endswith('(carrier: /dev/cu.mine)') + + +@pytest.mark.parametrize('answer, wanted', [ + ('Without the arm', 'scripts/macos.sh launch teleop:=true (carrier: none)'), + ('Quit', None), +]) +def test_without_a_carrier_the_operator_chooses(station, answer, wanted): + run, root, _ = station + result = run(answer=answer) + assert result.returncode == 0 + if wanted is None: + assert 'would run' not in result.stdout + else: + assert result.stdout.strip() == f'would run in {root}: {root}/{wanted}' + + +def test_several_usb_devices_ask_which_is_the_carrier(station): + run, root, _ = station + result = run('cu.usbmodem1101', 'cu.usbmodem2201', answer='/dev/cu.usbmodem2201') + assert result.stdout.strip().endswith('(carrier: /dev/cu.usbmodem2201)') + + +@pytest.mark.parametrize('answer, runs_setup', [('Set up', True), ('Not now', False)]) +def test_a_station_that_was_never_set_up_offers_to_set_it_up(station, answer, runs_setup): + run, root, _ = station + result = run('cu.usbmodem1101', set_up=False, answer=answer) + assert result.returncode == 0 + assert ('would run in a Terminal: cd ' + str(root) + ' && ./scripts/macos.sh setup' + in result.stdout) == runs_setup + assert 'macos.sh arm' not in result.stdout + + +def test_an_app_that_lost_its_repository_says_so(station): + run, root, _ = station + (root / 'scripts' / 'macos.sh').unlink() + result = run('cu.usbmodem1101', answer='Quit') + assert result.returncode == 1 and 'would run' not in result.stdout + + +def test_run_from_inside_the_repository_it_finds_the_repository_without_help(tmp_path): + result = subprocess.run( + [str(LAUNCHER)], env={'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin', + 'WAYBIONIC_APP_DRY_RUN': '1', 'WAYBIONIC_CARRIER': '/dev/cu.x', + 'WAYBIONIC_APP_ANSWER': 'Quit'}, + capture_output=True, text=True, timeout=30, check=False) + root = APP.parents[2] + if (root / 'install' / 'setup.bash').exists(): + assert result.stdout.strip() == ( + f'would run in {root}: {root}/scripts/macos.sh arm (carrier: /dev/cu.x)') + else: + assert 'would run' not in result.stdout + + +def test_the_app_command_installs_a_copy_that_knows_the_repository(tmp_path): + # A fresh clone has no empty Resources folder, as git does not keep one. + repo = tmp_path / 'checkout' + (repo / 'scripts').mkdir(parents=True) + shutil.copy(APP.parents[2] / 'scripts' / 'macos.sh', repo / 'scripts' / 'macos.sh') + shutil.copytree(APP, repo / 'packaging' / 'macos' / APP.name, + ignore=shutil.ignore_patterns('Resources')) + destination = tmp_path / 'Applications' + for _ in range(2): + result = subprocess.run( + ['bash', str(repo / 'scripts' / 'macos.sh'), 'app', str(destination)], env={ + 'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin'}, + capture_output=True, text=True, timeout=30, check=False) + assert result.returncode == 0, result.stderr + installed = destination / APP.name + assert (installed / 'Contents' / 'Resources' / 'repo_root').read_text( + encoding='utf-8') == f'{repo}\n' + launcher = installed / 'Contents' / 'MacOS' / LAUNCHER.name + assert os.access(launcher, os.X_OK) + assert str(installed) in result.stdout + + +def test_the_app_command_is_in_the_usage(): + script = APP.parents[2] / 'scripts' / 'macos.sh' + result = subprocess.run(['bash', str(script), 'help'], capture_output=True, text=True, + timeout=30, check=False) + assert ' app ' in result.stdout + + +def written(path, timeout=10): + """Wait for a made-up macos.sh to finish writing a line into path; return the line.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + text = path.read_text(encoding='utf-8') if path.exists() else '' + if text.endswith('\n'): + return text.strip() + time.sleep(0.02) + raise AssertionError(f'{path.name} was never written') + + +def gone(pid, timeout=10): + """Return whether the process has ended (a zombie nobody reaped yet counts as ended).""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + state = subprocess.run(['ps', '-o', 'stat=', '-p', str(pid)], capture_output=True, + text=True, check=False).stdout.strip() + if not state or state.startswith('Z'): + return True + time.sleep(0.05) + return False + + +@pytest.fixture +def running(station, tmp_path): + """ + Start the launcher for real over a made-up macos.sh. + + Return (start, pids): start(script) runs the launcher and returns its process, and the + made-up macos.sh reports the processes it starts by writing "$PIDS/". + """ + _, root, _ = station + pids = tmp_path / 'pids' + pids.mkdir() + started = [] + + def start(script): + (root / 'scripts' / 'macos.sh').write_text(f'#!/bin/bash\n{script}', encoding='utf-8') + (root / 'install').mkdir(exist_ok=True) + (root / 'install' / 'setup.bash').touch() + app = next((tmp_path / 'Applications').iterdir()) + process = subprocess.Popen( + [str(app / 'Contents' / 'MacOS' / LAUNCHER.name)], env={ + 'HOME': str(tmp_path), 'PATH': '/usr/bin:/bin', 'PIDS': str(pids), + 'WAYBIONIC_CARRIER': '/dev/cu.x', 'WAYBIONIC_APP_ANSWER': 'Close'}, + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + started.append(process) + return process + yield start, pids + for report in pids.glob('*'): + try: + os.kill(int(report.read_text(encoding='utf-8')), signal.SIGKILL) + except (OSError, ValueError): + pass + for process in started: + if process.poll() is None: + process.kill() + process.wait() + + +def test_quitting_before_the_launch_exists_stops_the_station_that_is_starting(running): + start, pids = running + # A background job of a script ignores SIGINT, so only TERM ends a station that has no + # launch process yet. The script dies with TERM and would leave its child behind. + process = start('echo $$ >"$PIDS/script"\nsleep 60 &\necho $! >"$PIDS/sleep"\nwait\n') + script, sleeper = int(written(pids / 'script')), int(written(pids / 'sleep')) + process.send_signal(signal.SIGTERM) + assert process.wait(timeout=10) == 0 + assert gone(script) + assert gone(sleeper) + + +def test_quitting_asks_the_running_launch_to_shut_down_as_ctrl_c_does(running, tmp_path): + start, pids = running + marker, ready = tmp_path / 'got_sigint', tmp_path / 'ready' + # Like the real launch process, it sets up its own SIGINT handler, and its command line + # holds "ros2 launch". + code = ( + 'import signal, sys, time\n' + 'def stop(*_):\n' + f' open({str(marker)!r}, "w").write("SIGINT\\n")\n' + ' sys.exit(0)\n' + 'signal.signal(signal.SIGINT, stop)\n' + f'open({str(ready)!r}, "w").write("ready\\n")\n' + 'time.sleep(60)\n') + process = start( + 'echo $$ >"$PIDS/script"\n' + f'{shlex.quote(sys.executable)} -c {shlex.quote(code)} ros2 launch fake &\n' + 'echo $! >"$PIDS/launch"\nwait\n') + written(ready) + process.send_signal(signal.SIGTERM) + assert process.wait(timeout=10) == 0 + assert marker.exists(), 'the launch process was not asked to shut down with SIGINT' + assert gone(int(written(pids / 'launch'))) diff --git a/waybionic_rviz_plugins/CMakeLists.txt b/waybionic_rviz_plugins/CMakeLists.txt index 50a6f8f1..9fb1c5ea 100644 --- a/waybionic_rviz_plugins/CMakeLists.txt +++ b/waybionic_rviz_plugins/CMakeLists.txt @@ -15,6 +15,7 @@ find_package(Qt5 REQUIRED COMPONENTS Widgets) find_package(rclcpp REQUIRED) find_package(rviz_common REQUIRED) find_package(rviz_default_plugins REQUIRED) +find_package(std_srvs REQUIRED) set(THIS_PACKAGE_INCLUDE_DEPENDS diagnostic_msgs @@ -22,17 +23,26 @@ set(THIS_PACKAGE_INCLUDE_DEPENDS rclcpp rviz_common rviz_default_plugins + std_srvs ) add_library(${PROJECT_NAME} SHARED include/waybionic_rviz_plugins/diagnostics_source.hpp include/waybionic_rviz_plugins/diagnostics_panel.hpp + include/waybionic_rviz_plugins/joint_control_model.hpp + include/waybionic_rviz_plugins/joint_control_panel.hpp include/waybionic_rviz_plugins/motion_test_panel.hpp include/waybionic_rviz_plugins/ros_diagnostics_source.hpp + include/waybionic_rviz_plugins/setup_model.hpp + include/waybionic_rviz_plugins/setup_panel.hpp src/diagnostics_panel.cpp + src/joint_control_model.cpp + src/joint_control_panel.cpp src/mock_diagnostics_source.cpp src/ros_diagnostics_source.cpp src/motion_test_panel.cpp + src/setup_model.cpp + src/setup_panel.cpp ) target_compile_features(${PROJECT_NAME} PUBLIC cxx_std_17) @@ -134,6 +144,31 @@ if(BUILD_TESTING) rclcpp ) endif() + + # The joint control model parses messages without Qt or RViz, so it is built on its own. + ament_add_gtest(test_joint_control_model + test/test_joint_control_model.cpp + src/joint_control_model.cpp + TIMEOUT 60 + ) + if(TARGET test_joint_control_model) + target_include_directories(test_joint_control_model PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + ament_target_dependencies(test_joint_control_model diagnostic_msgs) + endif() + + ament_add_gtest(test_setup_model + test/test_setup_model.cpp + src/setup_model.cpp + TIMEOUT 60 + ) + if(TARGET test_setup_model) + target_include_directories(test_setup_model PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/include + ) + ament_target_dependencies(test_setup_model diagnostic_msgs) + endif() endif() ament_export_targets(export_${PROJECT_NAME} HAS_LIBRARY_TARGET) diff --git a/waybionic_rviz_plugins/README.md b/waybionic_rviz_plugins/README.md index ba759dab..41fcd0fb 100644 --- a/waybionic_rviz_plugins/README.md +++ b/waybionic_rviz_plugins/README.md @@ -1,16 +1,16 @@ # WayBionic RViz2 Diagnostics Plugin -RViz2-native diagnostics and monitoring UI for WayBionic. This package is diagnostics-only: it provides the engineer monitoring panel, mock/live diagnostics switching, and a temporary `/diagnostics` publisher for local validation. +RViz2-native diagnostics and monitoring UI for WayBionic. This package provides the engineer monitoring panel, mock/live diagnostics switching, and a temporary `/diagnostics` publisher for local validation. Two small operator panels sit beside it, the arm setup guide and joint control (see [Operator panels](#operator-panels)); they only read topics and call services, and never send motion. It also provides `ground_station_rviz`, the ground station's RViz entry point. It uses RViz's normal application initialization and then maximizes the window with Qt, rather than entering RViz's panel-hiding fullscreen mode. It accepts the normal RViz and ROS arguments and does not send motor commands. -Monitoring-only scope: +Monitoring scope: - No motor commands from this package. -- No robot control or safety-critical logic. +- No robot control or safety-critical logic. The operator panels ask the drive node to hold or release a joint, or to zero, over services; the drive node decides and refuses while the arm is enabled. - No camera or doctor/surgeon UI in this PR (handled separately later). - Mock diagnostics for validation while backend `/diagnostics` is not ready. @@ -34,13 +34,44 @@ colcon test --packages-select waybionic_rviz_plugins colcon test-result --verbose ``` +## Operator panels + +Both panels are in the ground station's right-hand dock, above the diagnostics panel +(`ground_station_rviz` stacks them; a plain `rviz2` leaves them wherever the layout puts them). +It also puts the joint control and diagnostics panels in scroll areas, so that the three together +do not make the window taller than a laptop screen; the setup panel asks for the height its text +needs and does not scroll. + +**Arm setup** (`waybionic_rviz_plugins/SetupPanel`) lists the start-up steps the `setup_guide` +node publishes on the latched `/arm/setup` topic (a DiagnosticArray of `setup.` rows: +carrier, drives, controller, zero, ready). Each row's message is what to do next and its values +are `title`, `state` (`ok`, `todo`, `blocked` or `working`), `action` (`zero` or empty) and +`current`. When the guide asks for a zero, the panel offers a Zero button; after the operator +confirms the arm is in its zero pose it calls the drive node's `/sim_arm_drives/zero` +(`std_srvs/Trigger`) and shows the answer. Once every step is done the panel shrinks to one line, +and four seconds later (`kSetupHideAfter`) it closes its dock; `SetupDockPolicy` opens it again, once, +when a step before ready needs the operator (`SetupSnapshot::needsAttention`) and again hides it once +the arm is next ready. Teleop merely being stopped changes nothing. + +**Joint control** (`waybionic_rviz_plugins/JointControlPanel`) shows a checkbox per joint, +J1 to J5 and the tool. It reads the latched `/arm/joint_control` topic (a DiagnosticArray with +one row per joint: `state` is `enabled`, `disabled` or `no_drive`, plus `drives` and `angle`) +and calls `/arm//set_enabled` (`std_srvs/SetBool`) when a box is clicked. A joint that +is off is held by the drive node, which refuses a change while the arm is enabled; the panel +shows that refusal and leaves the box as the topic says. A joint with no drive is shown but +cannot be switched. + +Both publishers repeat their message every 0.5 s, so three seconds of silence greys a panel out +as waiting. The parsing of each topic lives in a Qt-free unit (`joint_control_model.*`, +`setup_model.*`) with gtests that build fabricated messages. + ## Package Layout ```text waybionic_rviz_plugins/ CMakeLists.txt # Builds the shared RViz plugin library + tests package.xml # Generic deps only; no Annin/AR4 exec deps - plugin_description.xml # Registers DiagnosticsPanel + plugin_description.xml # Registers DiagnosticsPanel, SetupPanel, JointControlPanel, MotionTestPanel scripts/ temporary_diagnostics_publisher.py diagnostics_recorder.py @@ -48,12 +79,20 @@ waybionic_rviz_plugins/ diagnostics_contract.hpp # Normalized DiagnosticMessage model diagnostics_source.hpp # DiagnosticsSource interface diagnostics_panel.hpp # Engineer monitoring panel + joint_control_model.hpp # Qt-free parsing of /arm/joint_control + joint_control_panel.hpp # Joint on/off checkboxes mock_diagnostics_source.hpp ros_diagnostics_source.hpp + setup_model.hpp # Qt-free parsing of /arm/setup + setup_panel.hpp # Start-up steps and the Zero button src/ diagnostics_panel.cpp + joint_control_model.cpp + joint_control_panel.cpp mock_diagnostics_source.cpp ros_diagnostics_source.cpp + setup_model.cpp + setup_panel.cpp config/ engineer_monitoring_view.rviz # Generic engineer layout (default) launch/ @@ -61,7 +100,9 @@ waybionic_rviz_plugins/ temporary_diagnostics_publisher.launch.py test/ test_package_metadata.py + test_joint_control_model.cpp # /arm/joint_control parsing test_ros_diagnostics_source.cpp # Live/mock source handoff stress tests + test_setup_model.cpp # /arm/setup parsing docs/ DIAGNOSTICS_CONTRACT.md DIAGNOSTICS_SOURCE_LIFECYCLE.md diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_model.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_model.hpp new file mode 100644 index 00000000..8015cfc1 --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_model.hpp @@ -0,0 +1,79 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_MODEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_MODEL_HPP_ + +#include +#include +#include +#include + +#include + +namespace waybionic_rviz_plugins +{ + +/// Latched topic on which the drive node reports the enable state of every joint. +constexpr const char * kJointControlTopic = "/arm/joint_control"; + +/// The drive node republishes every 0.5 s and on every state change, so this long +/// without a message means the node is gone. +constexpr std::chrono::milliseconds kDriveNodeQuietAfter{3000}; + +enum class JointState +{ + Enabled, + Disabled, + NoDrive +}; + +struct JointRow +{ + std::string joint_name; + std::string label; + JointState state{JointState::NoDrive}; + std::vector drives; + double angle_rad{0.0}; + std::string message; + /// True when the drive node offers a set_enabled service for this joint. + bool serviceable{false}; + /// False when the status broke the contract; `problem` then says how. + bool valid{false}; + std::string problem; +}; + +struct JointControlSnapshot +{ + /// True only when the array is non-empty and every row is valid. + bool valid{false}; + /// Rows in display order: the known joints first, then any others as received. + std::vector rows; + /// Summary of the first problem; empty when the snapshot is valid. + std::string error; +}; + +/// Reads one /arm/joint_control message. Never throws: malformed statuses are +/// reported through `valid`, `problem` and `error` so the caller can keep showing +/// the last good snapshot. +JointControlSnapshot parseJointControl(const diagnostic_msgs::msg::DiagnosticArray & array); + +/// Names of the joints the drive node normally reports, in display order. +std::vector knownJointNames(); + +/// Short display label: joint_1..joint_5 are J1..J5 and tool_grip is Tool. +/// Other names are returned unchanged. +std::string jointLabel(const std::string & joint_name); + +/// Name of the SetBool service that enables or disables a joint. +std::string setEnabledServiceName(const std::string & joint_name); + +/// Word shown for a state: "enabled", "disabled" or "no drive". +const char * stateWord(JointState state); + +/// True when the drive node should be treated as gone: nothing has been received, +/// or the last message is at least kDriveNodeQuietAfter old. +bool driveNodeQuiet( + const std::optional & last_message, + std::chrono::steady_clock::time_point now); + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_MODEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_panel.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_panel.hpp new file mode 100644 index 00000000..88be5397 --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/joint_control_panel.hpp @@ -0,0 +1,130 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_PANEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_PANEL_HPP_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "waybionic_rviz_plugins/joint_control_model.hpp" + +class QCheckBox; +class QGridLayout; +class QLabel; +class QScrollArea; +class QTimer; +class QWidget; + +namespace waybionic_rviz_plugins +{ + +struct JointControlMailbox; + +/// Lets the operator hold or release arm joints. +/// +/// The drive node latches the state of every joint on /arm/joint_control and +/// offers a SetBool service per joint. The panel only ever calls those services; +/// it never publishes motion commands or any other topic. The published state is +/// the single source of truth: a checkbox changes only when the topic reports a +/// change, never because it was clicked. +/// +/// Threading: RViz spins its node from the Qt thread, but nothing here relies on +/// that. ROS callbacks only write into a mutex-guarded mailbox, and a Qt timer +/// drains it, so all widget and bookkeeping state is touched by the Qt thread +/// alone and no service call ever blocks it. +class JointControlPanel : public rviz_common::Panel +{ + Q_OBJECT + +public: + explicit JointControlPanel(QWidget * parent = nullptr); + ~JointControlPanel() override; + + void onInitialize() override; + + /// Subscribes to the joint states and prepares the service clients on `node`. + /// onInitialize() calls this with RViz's node; it is public so the panel can + /// also be driven by another node. Calling it again replaces the connection. + void connectToNode(rclcpp::Node::SharedPtr node); + +private: + using SetBool = std_srvs::srv::SetBool; + using SetBoolClient = rclcpp::Client; + + struct RowWidgets + { + QCheckBox * checkbox{nullptr}; + QLabel * state{nullptr}; + QLabel * detail{nullptr}; + QString state_style; + }; + + struct PendingCall + { + std::uint64_t token{0}; + std::int64_t request_id{0}; + bool enable{false}; + std::chrono::steady_clock::time_point sent; + }; + + void buildUi(); + void rebuildRows(const std::vector & joint_names); + void clearRows(); + void disconnectFromNode(); + + void poll(); + void applyMailbox(); + void applySnapshot(JointControlSnapshot snapshot); + void expirePendingCalls(std::chrono::steady_clock::time_point now); + void requestToggle(const std::string & joint_name); + SetBoolClient::SharedPtr clientFor(const std::string & joint_name); + void forgetCall(const std::string & joint_name, const PendingCall & call); + void showStatus(const QString & text); + void render(); + + const JointRow * findRow(const std::string & joint_name) const; + + rclcpp::Node::SharedPtr node_; + rclcpp::Subscription::SharedPtr subscription_; + std::map clients_; + std::shared_ptr mailbox_; + + // The last valid message, kept only while the drive node keeps talking. + JointControlSnapshot snapshot_; + bool has_snapshot_{false}; + std::optional last_message_; + + std::map pending_; + std::uint64_t next_token_{0}; + + QString status_text_; + std::chrono::steady_clock::time_point status_expires_; + + std::vector row_names_; + std::vector row_widgets_; + QString connection_style_; + + QTimer * poll_timer_{nullptr}; + QLabel * connection_label_{nullptr}; + QLabel * status_label_{nullptr}; + QScrollArea * rows_scroll_{nullptr}; + QWidget * rows_widget_{nullptr}; + QGridLayout * rows_layout_{nullptr}; +}; + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__JOINT_CONTROL_PANEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp new file mode 100644 index 00000000..472f971c --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_model.hpp @@ -0,0 +1,127 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__SETUP_MODEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__SETUP_MODEL_HPP_ + +#include +#include +#include +#include + +#include + +namespace waybionic_rviz_plugins +{ + +/// Latched topic on which setup_guide publishes the start-up steps. +constexpr const char * kSetupTopic = "/arm/setup"; + +/// The drive node's zero service (std_srvs/Trigger): the setup panel's Zero button calls it. +constexpr const char * kZeroServiceName = "/sim_arm_drives/zero"; + +/// setup_guide publishes every 0.5 s, so this long without a message means it is gone. +constexpr std::chrono::milliseconds kSetupGuideQuietAfter{3000}; + +/// How long the arm has to stay ready before the setup panel puts itself away. +constexpr std::chrono::milliseconds kSetupHideAfter{4000}; + +enum class StepState +{ + Ok, + Todo, + Blocked, + Working +}; + +struct SetupStep +{ + /// "carrier", "drives", "controller", "zero" or "ready": the row name without "setup.". + std::string name; + std::string title; + StepState state{StepState::Todo}; + /// What the operator is to do, or what is going on. + std::string message; + /// "zero" when the panel is to offer the Zero button; empty otherwise. + std::string action; + /// True for the first step that is not done. + bool current{false}; + bool valid{false}; + std::string problem; +}; + +struct SetupSnapshot +{ + /// True only when the array is non-empty and every step is valid. + bool valid{false}; + /// Known steps in the order the operator does them, then any others as received. + std::vector steps; + /// Summary of the first problem; empty when the snapshot is valid. + std::string error; + + /// True when there is at least one step and every one is done. + bool ready() const; + /// True when the operator has something to do or fix: a step is blocked, or a step before + /// Ready is still to do. A step that is only being checked does not count, and neither does + /// Ready being to do, which is teleop stopped with only Start left to press. + bool needsAttention() const; + /// The step marked current, or nullptr once everything is done. + const SetupStep * currentStep() const; +}; + +/// Reads one /arm/setup message. Never throws: malformed statuses are reported through +/// `valid`, `problem` and `error` so the caller can keep showing the last good snapshot. +SetupSnapshot parseSetup(const diagnostic_msgs::msg::DiagnosticArray & array); + +/// Word shown for a state: "done", "to do", "blocked" or "working". +const char * stepStateWord(StepState state); + +/// True when setup_guide should be treated as gone: nothing has been received, or the last +/// message is at least kSetupGuideQuietAfter old. +bool setupGuideQuiet( + const std::optional & last_message, + std::chrono::steady_clock::time_point now); + +/// What the panel says while it has no report to show. `seen_guide` is whether a valid report +/// has ever arrived, and `guide_quiet` is setupGuideQuiet(). +std::string setupWaitingMessage(bool seen_guide, bool guide_quiet); + +/// What the setup panel's dock is to do about its own visibility. +enum class DockAction +{ + None, + Show, + Hide +}; + +/// How the latest setup report bears on the dock. +enum class SetupDockInput +{ + /// Nothing to act on: no report yet, a step being checked, or only Start left to press. + Waiting, + /// The operator has something to do or fix; see SetupSnapshot::needsAttention. + NeedsAttention, + /// Every step is done. + Ready +}; + +/// Puts the setup panel away once the arm has stayed ready for a while, and brings it back when +/// something needs the operator, so it takes room only while it is useful. It acts on changes +/// only: it shows the panel once when a problem appears, so that closing the panel by hand sticks +/// until the next one, and hides it once per ready period, so that a panel opened by hand while +/// ready stays open. A report that is neither (a step being checked, or only Start left) changes +/// nothing, except that it ends the ready period. +class SetupDockPolicy +{ +public: + explicit SetupDockPolicy(std::chrono::steady_clock::duration hide_after = kSetupHideAfter); + + DockAction update(SetupDockInput input, std::chrono::steady_clock::time_point now); + +private: + std::chrono::steady_clock::duration hide_after_; + SetupDockInput last_{SetupDockInput::Waiting}; + std::chrono::steady_clock::time_point ready_since_; + bool hidden_{false}; +}; + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__SETUP_MODEL_HPP_ diff --git a/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp new file mode 100644 index 00000000..471acd45 --- /dev/null +++ b/waybionic_rviz_plugins/include/waybionic_rviz_plugins/setup_panel.hpp @@ -0,0 +1,137 @@ +#ifndef WAYBIONIC_RVIZ_PLUGINS__SETUP_PANEL_HPP_ +#define WAYBIONIC_RVIZ_PLUGINS__SETUP_PANEL_HPP_ + +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include +#include +#include +#include + +#include "waybionic_rviz_plugins/setup_model.hpp" + +class QDockWidget; +class QLabel; +class QGridLayout; +class QPushButton; +class QResizeEvent; +class QTimer; +class QWidget; + +namespace waybionic_rviz_plugins +{ + +struct SetupMailbox; + +/// Walks the operator through starting the arm: carrier, drives, controller, zero, ready. +/// +/// The setup_guide node turns the other nodes' diagnostics into those steps and latches them +/// on /arm/setup. The panel shows them, and offers one button, Zero, when the guide asks for +/// it: that calls the drive node's own zero service after the operator confirms the arm is in +/// its zero pose. It never publishes anything, and never moves the arm. +/// +/// Once the arm has stayed ready for a few seconds the panel closes its dock, so the other +/// panels get the room, and it opens again when something needs the operator, such as the +/// controller dropping out or a drive losing its zero. The Panels menu opens it by hand. +/// +/// Threading: ROS callbacks only write into a mutex-guarded mailbox, and a Qt timer drains it, +/// so all widget and bookkeeping state is touched by the Qt thread alone and no service call +/// ever blocks it. +class SetupPanel : public rviz_common::Panel +{ + Q_OBJECT + +public: + explicit SetupPanel(QWidget * parent = nullptr); + ~SetupPanel() override; + + void onInitialize() override; + + /// Subscribes to the setup steps and prepares the zero client on `node`. onInitialize() + /// calls this with RViz's node. Calling it again replaces the connection. + void connectToNode(rclcpp::Node::SharedPtr node); + +protected: + void resizeEvent(QResizeEvent * event) override; + +private: + using Trigger = std_srvs::srv::Trigger; + using TriggerClient = rclcpp::Client; + + struct RowWidgets + { + QLabel * icon{nullptr}; + QLabel * title{nullptr}; + QLabel * message{nullptr}; + }; + + struct PendingZero + { + std::uint64_t token{0}; + std::int64_t request_id{0}; + std::chrono::steady_clock::time_point sent; + }; + + void buildUi(); + void rebuildRows(const std::vector & step_names); + void clearRows(); + void disconnectFromNode(); + + void poll(); + void applyMailbox(); + void applySnapshot(SetupSnapshot snapshot); + void expirePendingZero(std::chrono::steady_clock::time_point now); + void requestZero(); + void showStatus(const QString & text, bool success); + void render(); + void fitHeight(); + QDockWidget * dock() const; + SetupDockInput dockInput(bool quiet) const; + void applyDockAction(DockAction action); + + bool zeroOffered() const; + + rclcpp::Node::SharedPtr node_; + rclcpp::Subscription::SharedPtr subscription_; + TriggerClient::SharedPtr zero_client_; + std::shared_ptr mailbox_; + + // The last valid message, kept only while the guide keeps talking. + SetupSnapshot snapshot_; + bool has_snapshot_{false}; + // True once a valid report has arrived, so that a guide that has gone quiet is told from one + // that has not started yet. + bool seen_guide_{false}; + std::optional last_message_; + SetupDockPolicy dock_policy_; + + std::optional pending_zero_; + std::uint64_t next_token_{0}; + + QString status_text_; + bool status_success_{false}; + std::chrono::steady_clock::time_point status_expires_; + + std::vector row_names_; + std::vector row_widgets_; + + QTimer * poll_timer_{nullptr}; + QLabel * summary_label_{nullptr}; + QLabel * status_label_{nullptr}; + QPushButton * zero_button_{nullptr}; + QWidget * rows_widget_{nullptr}; + QGridLayout * rows_layout_{nullptr}; +}; + +} // namespace waybionic_rviz_plugins + +#endif // WAYBIONIC_RVIZ_PLUGINS__SETUP_PANEL_HPP_ diff --git a/waybionic_rviz_plugins/package.xml b/waybionic_rviz_plugins/package.xml index 63bbb2d2..84245655 100644 --- a/waybionic_rviz_plugins/package.xml +++ b/waybionic_rviz_plugins/package.xml @@ -14,6 +14,7 @@ rclcpp sensor_msgs std_msgs + std_srvs rviz_common rviz_default_plugins diff --git a/waybionic_rviz_plugins/plugin_description.xml b/waybionic_rviz_plugins/plugin_description.xml index d6dc67dd..728a1308 100644 --- a/waybionic_rviz_plugins/plugin_description.xml +++ b/waybionic_rviz_plugins/plugin_description.xml @@ -8,6 +8,26 @@ + + + Start-up steps for the arm: carrier, drives, controller, zero and ready, with a Zero + button that asks the drive node to zero. This panel sends no motion commands. + + + + + + Switch arm joints on or off. The drive node holds a joint that is off; this panel + sends no motion commands. + + + #include +#include +#include +#include +#include +#include +#include #include "rclcpp/rclcpp.hpp" #include "rviz_common/logging.hpp" @@ -13,6 +19,65 @@ #include "rviz_common/visualization_frame.hpp" #include "rviz_common/visualizer_app.hpp" +namespace +{ + +// A panel asks for the height of everything in it. The three stacked below ask for more than a +// laptop screen has between them, which made the window taller than the screen and cut off its +// bottom. In a scroll area a dock can be shorter than its panel, and the panel scrolls. +void scrollInDock(QDockWidget * dock) +{ + QWidget * panel = dock->widget(); + if (panel == nullptr || qobject_cast(panel) != nullptr) { + return; + } + auto * scroll = new QScrollArea(); + scroll->setFrameShape(QFrame::NoFrame); + scroll->setWidgetResizable(true); + // Giving the dock another widget hides the panel, so put it in the scroll area and show it. + dock->setWidget(scroll); + scroll->setWidget(panel); + panel->show(); +} + +// The station's own panels, from the top of the right-hand dock down, with the share of its +// height each gets. RViz puts a panel its saved window state does not know in the left dock, so +// they are stacked here whatever the layout file says. Panels that are not loaded are skipped. +// The setup panel never scrolls: it asks for exactly the height its text needs, and it is the +// one the operator has to read while it is open. +void stackRightDock(QMainWindow * frame) +{ + struct Entry + { + const char * name; + int weight; + bool scrolls; + }; + const Entry order[] = { + {"SetupPanel", 2, false}, {"JointControlPanel", 2, true}, {"DiagnosticsPanel", 5, true}}; + QList docks; + QList weights; + for (const auto & entry : order) { + if (auto * dock = frame->findChild(QString::fromLatin1(entry.name))) { + if (entry.scrolls) { + scrollInDock(dock); + } + docks.append(dock); + weights.append(entry.weight); + } + } + if (docks.isEmpty()) { + return; + } + frame->addDockWidget(Qt::RightDockWidgetArea, docks.first()); + for (int index = 1; index < docks.size(); ++index) { + frame->splitDockWidget(docks[index - 1], docks[index], Qt::Vertical); + } + frame->resizeDocks(docks, weights, Qt::Vertical); +} + +} // namespace + int main(int argc, char ** argv) { auto arguments = rclcpp::remove_ros_arguments(argc, argv); @@ -52,6 +117,7 @@ int main(int argc, char ** argv) } for (auto * widget : QApplication::topLevelWidgets()) { if (auto * frame = qobject_cast(widget)) { + stackRightDock(frame); frame->showMaximized(); return application.exec(); } diff --git a/waybionic_rviz_plugins/src/joint_control_model.cpp b/waybionic_rviz_plugins/src/joint_control_model.cpp new file mode 100644 index 00000000..6da6c1b6 --- /dev/null +++ b/waybionic_rviz_plugins/src/joint_control_model.cpp @@ -0,0 +1,310 @@ +#include "waybionic_rviz_plugins/joint_control_model.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +struct KnownJoint +{ + const char * name; + const char * label; +}; + +constexpr KnownJoint kKnownJoints[] = { + {"joint_1", "J1"}, + {"joint_2", "J2"}, + {"joint_3", "J3"}, + {"joint_4", "J4"}, + {"joint_5", "J5"}, + {"tool_grip", "Tool"}, +}; + +std::size_t displayOrder(const std::string & joint_name) +{ + for (std::size_t index = 0; index < std::size(kKnownJoints); ++index) { + if (joint_name == kKnownJoints[index].name) { + return index; + } + } + return std::size(kKnownJoints); +} + +// The name becomes part of a service name, so it must be a valid ROS name token. +bool isValidJointName(const std::string & name) +{ + if (name.empty()) { + return false; + } + for (std::size_t index = 0; index < name.size(); ++index) { + const char character = name[index]; + const bool letter = + (character >= 'a' && character <= 'z') || + (character >= 'A' && character <= 'Z') || character == '_'; + const bool digit = character >= '0' && character <= '9'; + if (!letter && !(digit && index > 0)) { + return false; + } + } + return true; +} + +std::string trim(const std::string & text) +{ + const auto first = text.find_first_not_of(" \t"); + if (first == std::string::npos) { + return {}; + } + const auto last = text.find_last_not_of(" \t"); + return text.substr(first, last - first + 1); +} + +// Problem texts quote the offending message, which ends up in the status line, so +// keep them short and printable whatever the message contains. +std::string shorten(const std::string & text) +{ + constexpr std::size_t kMaxLength = 32; + std::string result = text.substr(0, kMaxLength); + for (auto & character : result) { + const auto byte = static_cast(character); + if (byte < 0x20 || byte >= 0x7f) { + character = '?'; + } + } + if (text.size() > kMaxLength) { + result += "..."; + } + return result; +} + +std::vector splitDrives(const std::string & text) +{ + std::vector drives; + std::size_t start = 0; + while (start <= text.size()) { + const auto end = text.find(',', start); + const auto drive = trim(text.substr(start, end == std::string::npos ? end : end - start)); + if (!drive.empty()) { + drives.push_back(drive); + } + if (end == std::string::npos) { + break; + } + start = end + 1; + } + return drives; +} + +bool parseState(const std::string & text, JointState * state) +{ + if (text == "enabled") { + *state = JointState::Enabled; + } else if (text == "disabled") { + *state = JointState::Disabled; + } else if (text == "no_drive") { + *state = JointState::NoDrive; + } else { + return false; + } + return true; +} + +// Plain decimal numbers only. Hex floats, "nan" and "inf" are rejected up front +// because stream parsing of them differs between standard libraries. +bool parseDecimal(const std::string & text, double * value) +{ + if (text.empty() || text.find_first_not_of("0123456789+-.eE") != std::string::npos) { + return false; + } + std::istringstream stream(text); + stream.imbue(std::locale::classic()); + double parsed = 0.0; + stream >> parsed; + if (stream.fail() || !stream.eof() || !std::isfinite(parsed)) { + return false; + } + *value = parsed; + return true; +} + +// Returns the value stored under `key`, or nullptr. `duplicate` is set when the +// key appears more than once, because the intended value is then ambiguous. +const std::string * findValue( + const diagnostic_msgs::msg::DiagnosticStatus & status, const char * key, bool * duplicate) +{ + const std::string * found = nullptr; + *duplicate = false; + for (const auto & item : status.values) { + if (item.key != key) { + continue; + } + if (found != nullptr) { + *duplicate = true; + } else { + found = &item.value; + } + } + return found; +} + +JointRow parseRow(const diagnostic_msgs::msg::DiagnosticStatus & status) +{ + JointRow row; + row.joint_name = status.name; + row.label = jointLabel(status.name); + row.message = status.message; + + // Only the first problem is kept; it is enough to find the fault. + const auto fail = [&row](const std::string & problem) { + if (row.problem.empty()) { + row.problem = problem; + } + }; + + if (status.name.empty()) { + fail("status without a joint name"); + } else if (!isValidJointName(status.name)) { + fail("invalid joint name '" + shorten(status.name) + "'"); + } + + bool duplicate = false; + const auto * state_text = findValue(status, "state", &duplicate); + if (duplicate) { + fail("duplicate 'state' value"); + } else if (state_text == nullptr) { + fail("missing 'state' value"); + } else if (!parseState(*state_text, &row.state)) { + fail("unknown state '" + shorten(*state_text) + "'"); + } + + const auto * angle_text = findValue(status, "angle", &duplicate); + if (duplicate) { + fail("duplicate 'angle' value"); + } else if (angle_text == nullptr) { + fail("missing 'angle' value"); + } else if (!parseDecimal(*angle_text, &row.angle_rad)) { + fail("angle '" + shorten(*angle_text) + "' is not a number"); + } + + // The drive names are informational, so a status without them is still usable. + const auto * drives_text = findValue(status, "drives", &duplicate); + if (drives_text != nullptr) { + row.drives = splitDrives(*drives_text); + } + + row.valid = row.problem.empty(); + row.serviceable = row.valid && row.state != JointState::NoDrive; + return row; +} + +std::string describeProblem(const JointRow & row, const std::size_t position) +{ + const auto subject = + row.joint_name.empty() ? "status " + std::to_string(position + 1) : shorten(row.joint_name); + return subject + ": " + row.problem; +} + +} // namespace + +JointControlSnapshot parseJointControl(const diagnostic_msgs::msg::DiagnosticArray & array) +{ + JointControlSnapshot snapshot; + snapshot.rows.reserve(array.status.size()); + for (const auto & status : array.status) { + snapshot.rows.push_back(parseRow(status)); + } + + std::set seen; + for (auto & row : snapshot.rows) { + if (!seen.insert(row.joint_name).second) { + row.valid = false; + row.serviceable = false; + if (row.problem.empty()) { + row.problem = "duplicate joint name"; + } + } + } + + if (snapshot.rows.empty()) { + snapshot.error = "no joint statuses"; + } else { + std::size_t problems = 0; + for (std::size_t position = 0; position < snapshot.rows.size(); ++position) { + const auto & row = snapshot.rows[position]; + if (row.valid) { + continue; + } + if (problems == 0) { + snapshot.error = describeProblem(row, position); + } + ++problems; + } + if (problems > 1) { + snapshot.error += " (and " + std::to_string(problems - 1) + " more)"; + } + } + snapshot.valid = snapshot.error.empty(); + + std::stable_sort( + snapshot.rows.begin(), snapshot.rows.end(), [](const JointRow & left, const JointRow & right) { + return displayOrder(left.joint_name) < displayOrder(right.joint_name); + }); + return snapshot; +} + +std::vector knownJointNames() +{ + std::vector names; + for (const auto & joint : kKnownJoints) { + names.emplace_back(joint.name); + } + return names; +} + +std::string jointLabel(const std::string & joint_name) +{ + for (const auto & joint : kKnownJoints) { + if (joint_name == joint.name) { + return joint.label; + } + } + return joint_name; +} + +std::string setEnabledServiceName(const std::string & joint_name) +{ + return "/arm/" + joint_name + "/set_enabled"; +} + +const char * stateWord(const JointState state) +{ + switch (state) { + case JointState::Enabled: + return "enabled"; + case JointState::Disabled: + return "disabled"; + case JointState::NoDrive: + return "no drive"; + } + return "unknown"; +} + +bool driveNodeQuiet( + const std::optional & last_message, + const std::chrono::steady_clock::time_point now) +{ + return !last_message.has_value() || now - *last_message >= kDriveNodeQuietAfter; +} + +} // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/src/joint_control_panel.cpp b/waybionic_rviz_plugins/src/joint_control_panel.cpp new file mode 100644 index 00000000..abccb72b --- /dev/null +++ b/waybionic_rviz_plugins/src/joint_control_panel.cpp @@ -0,0 +1,443 @@ +#include "waybionic_rviz_plugins/joint_control_panel.hpp" + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +constexpr int kPollIntervalMs = 100; +constexpr std::chrono::seconds kServiceTimeout{5}; +constexpr std::chrono::seconds kStatusLifetime{8}; + +constexpr const char * kPanelStyle = R"( +QWidget { + background-color: #071019; + color: #e8f1f8; + font-family: "Segoe UI", "Ubuntu", sans-serif; + font-size: 12px; +} +QLabel#PanelTitle { + font-size: 15px; + font-weight: 700; +} +QLabel#Muted { + color: #8ea3b1; +} +QLabel#Warning { + color: #ffb84d; + font-weight: 700; +} +QCheckBox { + font-weight: 700; + spacing: 8px; +} +QCheckBox:disabled { + color: #5d7282; +} +QScrollArea { + border: none; +} +)"; + +constexpr const char * kEnabledStyle = "color: #3ddc84; font-weight: 700;"; +constexpr const char * kDisabledStyle = "color: #ffb84d; font-weight: 700;"; +constexpr const char * kNoDriveStyle = "color: #8ea3b1;"; +constexpr const char * kWaitingStyle = "color: #5d7282;"; + +const char * styleFor(const JointState state) +{ + switch (state) { + case JointState::Enabled: + return kEnabledStyle; + case JointState::Disabled: + return kDisabledStyle; + case JointState::NoDrive: + return kNoDriveStyle; + } + return kWaitingStyle; +} + +} // namespace + +/// What the ROS threads hand to the Qt thread. Callbacks only ever write here. +struct JointControlMailbox +{ + struct Reply + { + std::string joint_name; + std::uint64_t token{0}; + bool success{false}; + std::string message; + }; + + std::mutex mutex; + std::optional snapshot; + std::optional received_at; + std::deque replies; +}; + +JointControlPanel::JointControlPanel(QWidget * parent) +: rviz_common::Panel(parent), mailbox_(std::make_shared()) +{ + buildUi(); + poll_timer_ = new QTimer(this); + connect(poll_timer_, &QTimer::timeout, this, [this]() {poll();}); + poll_timer_->start(kPollIntervalMs); + render(); +} + +JointControlPanel::~JointControlPanel() +{ + if (poll_timer_ != nullptr) { + poll_timer_->stop(); + } + disconnectFromNode(); +} + +void JointControlPanel::onInitialize() +{ + if (auto ros_node_abstraction = getDisplayContext()->getRosNodeAbstraction().lock()) { + connectToNode(ros_node_abstraction->get_raw_node()); + } +} + +void JointControlPanel::connectToNode(rclcpp::Node::SharedPtr node) +{ + disconnectFromNode(); + node_ = std::move(node); + if (!node_) { + return; + } + { + std::lock_guard lock(mailbox_->mutex); + mailbox_->snapshot.reset(); + mailbox_->received_at.reset(); + mailbox_->replies.clear(); + } + subscription_ = node_->create_subscription( + kJointControlTopic, rclcpp::QoS(1).reliable().transient_local(), + [mailbox = mailbox_](diagnostic_msgs::msg::DiagnosticArray::ConstSharedPtr message) { + auto snapshot = parseJointControl(*message); + std::lock_guard lock(mailbox->mutex); + mailbox->snapshot = std::move(snapshot); + mailbox->received_at = std::chrono::steady_clock::now(); + }); +} + +void JointControlPanel::disconnectFromNode() +{ + subscription_.reset(); + for (const auto & [joint_name, call] : pending_) { + const auto client = clients_.find(joint_name); + if (client != clients_.end()) { + client->second->remove_pending_request(call.request_id); + } + } + pending_.clear(); + clients_.clear(); + node_.reset(); + has_snapshot_ = false; + snapshot_ = JointControlSnapshot{}; + last_message_.reset(); +} + +void JointControlPanel::buildUi() +{ + setStyleSheet(kPanelStyle); + setMinimumWidth(320); + + auto * root_layout = new QVBoxLayout(this); + root_layout->setContentsMargins(10, 10, 10, 10); + root_layout->setSpacing(6); + + auto * title = new QLabel("Joint control"); + title->setObjectName("PanelTitle"); + root_layout->addWidget(title); + + auto * hint = new QLabel( + "A checked joint moves with the sticks. An unchecked joint is held where it is. " + "Switch joints with teleop stopped."); + hint->setObjectName("Muted"); + hint->setWordWrap(true); + root_layout->addWidget(hint); + + connection_label_ = new QLabel(); + connection_label_->setObjectName("Muted"); + connection_label_->setWordWrap(true); + root_layout->addWidget(connection_label_); + + rows_scroll_ = new QScrollArea(); + rows_scroll_->setWidgetResizable(true); + rows_scroll_->setMinimumHeight(200); + rows_widget_ = new QWidget(); + rows_layout_ = new QGridLayout(rows_widget_); + rows_layout_->setContentsMargins(0, 0, 0, 0); + rows_layout_->setHorizontalSpacing(12); + rows_layout_->setVerticalSpacing(6); + rows_layout_->setColumnStretch(2, 1); + rows_scroll_->setWidget(rows_widget_); + root_layout->addWidget(rows_scroll_, 1); + + status_label_ = new QLabel(); + status_label_->setObjectName("Warning"); + status_label_->setWordWrap(true); + root_layout->addWidget(status_label_); +} + +void JointControlPanel::clearRows() +{ + // A checkbox may be running its own click handler, so the widgets go when Qt is done. + for (auto & row : row_widgets_) { + for (QWidget * widget : {static_cast(row.checkbox), + static_cast(row.state), static_cast(row.detail)}) + { + rows_layout_->removeWidget(widget); + widget->hide(); + widget->deleteLater(); + } + } + row_widgets_.clear(); + row_names_.clear(); +} + +void JointControlPanel::rebuildRows(const std::vector & joint_names) +{ + clearRows(); + row_names_ = joint_names; + int line = 0; + for (const auto & joint_name : joint_names) { + RowWidgets row; + row.checkbox = new QCheckBox(QString::fromStdString(jointLabel(joint_name))); + row.state = new QLabel(); + row.detail = new QLabel(); + row.detail->setObjectName("Muted"); + row.detail->setWordWrap(true); + connect(row.checkbox, &QCheckBox::clicked, this, [this, joint_name](bool) { + // The checkbox follows the published state, not the click: the click only asks. + requestToggle(joint_name); + render(); + }); + rows_layout_->addWidget(row.checkbox, line, 0); + rows_layout_->addWidget(row.state, line, 1); + rows_layout_->addWidget(row.detail, line, 2); + row_widgets_.push_back(row); + ++line; + } + rows_layout_->setRowStretch(line, 1); +} + +const JointRow * JointControlPanel::findRow(const std::string & joint_name) const +{ + const auto found = std::find_if( + snapshot_.rows.begin(), snapshot_.rows.end(), + [&joint_name](const JointRow & row) {return row.joint_name == joint_name;}); + return found == snapshot_.rows.end() ? nullptr : &*found; +} + +void JointControlPanel::poll() +{ + applyMailbox(); + expirePendingCalls(std::chrono::steady_clock::now()); + render(); +} + +void JointControlPanel::applyMailbox() +{ + std::optional snapshot; + std::optional received_at; + std::deque replies; + { + std::lock_guard lock(mailbox_->mutex); + snapshot.swap(mailbox_->snapshot); + received_at = mailbox_->received_at; + replies.swap(mailbox_->replies); + } + if (received_at.has_value()) { + last_message_ = received_at; + } + if (snapshot.has_value()) { + applySnapshot(std::move(*snapshot)); + } + for (const auto & reply : replies) { + const auto call = pending_.find(reply.joint_name); + if (call == pending_.end() || call->second.token != reply.token) { + continue; // Answers a call that already timed out. + } + pending_.erase(call); + if (!reply.success) { + const auto * row = findRow(reply.joint_name); + const auto label = row != nullptr ? row->label : reply.joint_name; + showStatus(QString::fromStdString(label + ": " + reply.message)); + } + } +} + +void JointControlPanel::applySnapshot(JointControlSnapshot snapshot) +{ + if (!snapshot.valid) { + // Keep showing the last good report, and say that this one was ignored. + showStatus(QString::fromStdString("Ignoring a malformed joint report: " + snapshot.error)); + return; + } + snapshot_ = std::move(snapshot); + has_snapshot_ = true; +} + +void JointControlPanel::expirePendingCalls(const std::chrono::steady_clock::time_point now) +{ + std::vector expired; + for (const auto & [joint_name, call] : pending_) { + if (now - call.sent > kServiceTimeout) { + expired.push_back(joint_name); + } + } + for (const auto & joint_name : expired) { + const auto call = pending_.at(joint_name); + forgetCall(joint_name, call); + const auto * row = findRow(joint_name); + const auto label = row != nullptr ? row->label : joint_name; + showStatus(QString::fromStdString("No answer from the drive node for " + label)); + } +} + +void JointControlPanel::forgetCall(const std::string & joint_name, const PendingCall & call) +{ + const auto client = clients_.find(joint_name); + if (client != clients_.end()) { + client->second->remove_pending_request(call.request_id); + } + pending_.erase(joint_name); +} + +JointControlPanel::SetBoolClient::SharedPtr JointControlPanel::clientFor( + const std::string & joint_name) +{ + const auto found = clients_.find(joint_name); + if (found != clients_.end()) { + return found->second; + } + auto client = node_->create_client(setEnabledServiceName(joint_name)); + clients_[joint_name] = client; + return client; +} + +void JointControlPanel::requestToggle(const std::string & joint_name) +{ + if (!node_ || !has_snapshot_ || pending_.count(joint_name) > 0 || + driveNodeQuiet(last_message_, std::chrono::steady_clock::now())) + { + return; + } + const auto * row = findRow(joint_name); + if (row == nullptr || !row->serviceable) { + return; + } + const auto client = clientFor(joint_name); + if (!client->service_is_ready()) { + showStatus(QString::fromStdString(row->label + ": drive node not available")); + return; + } + auto request = std::make_shared(); + request->data = row->state != JointState::Enabled; + PendingCall call; + call.token = ++next_token_; + call.enable = request->data; + call.sent = std::chrono::steady_clock::now(); + const auto sent = client->async_send_request( + request, + [mailbox = mailbox_, joint_name, token = call.token](SetBoolClient::SharedFuture future) { + const auto response = future.get(); + std::lock_guard lock(mailbox->mutex); + mailbox->replies.push_back({joint_name, token, response->success, response->message}); + }); + call.request_id = sent.request_id; + pending_[joint_name] = call; +} + +void JointControlPanel::showStatus(const QString & text) +{ + status_text_ = text; + status_expires_ = std::chrono::steady_clock::now() + kStatusLifetime; +} + +void JointControlPanel::render() +{ + const auto now = std::chrono::steady_clock::now(); + const bool quiet = driveNodeQuiet(last_message_, now); + const bool shown = has_snapshot_ && !quiet; + + if (quiet) { + connection_label_->setText("Waiting for the drive node (sim_arm_drives)..."); + } else if (!has_snapshot_) { + connection_label_->setText("Waiting for a valid joint report..."); + } else { + connection_label_->setText("Drive node connected"); + } + + std::vector names = knownJointNames(); + if (has_snapshot_) { + names.clear(); + for (const auto & row : snapshot_.rows) { + names.push_back(row.joint_name); + } + } + if (names != row_names_) { + rebuildRows(names); + } + + for (std::size_t index = 0; index < row_names_.size(); ++index) { + auto & widgets = row_widgets_[index]; + const auto * row = shown ? findRow(row_names_[index]) : nullptr; + const QSignalBlocker blocker(widgets.checkbox); + if (row == nullptr) { + widgets.checkbox->setChecked(false); + widgets.checkbox->setEnabled(false); + widgets.state->setText(QString::fromUtf8("\xE2\x80\x94")); + widgets.state->setStyleSheet(kWaitingStyle); + widgets.detail->setText(QString()); + continue; + } + const auto call = pending_.find(row->joint_name); + const bool waiting = call != pending_.end(); + widgets.checkbox->setChecked(row->state == JointState::Enabled); + widgets.checkbox->setEnabled(row->serviceable && !waiting); + QString word = QString::fromUtf8(stateWord(row->state)); + if (waiting) { + word = call->second.enable ? "enabling..." : "disabling..."; + } + widgets.state->setText(word); + const QString style = QString::fromUtf8(styleFor(row->state)); + if (widgets.state_style != style) { + widgets.state->setStyleSheet(style); + widgets.state_style = style; + } + const auto detail = QString::fromStdString(row->message); + widgets.detail->setText(detail); + widgets.checkbox->setToolTip(detail); + } + + status_label_->setText(now < status_expires_ ? status_text_ : QString()); +} + +} // namespace waybionic_rviz_plugins + +PLUGINLIB_EXPORT_CLASS(waybionic_rviz_plugins::JointControlPanel, rviz_common::Panel) diff --git a/waybionic_rviz_plugins/src/setup_model.cpp b/waybionic_rviz_plugins/src/setup_model.cpp new file mode 100644 index 00000000..fd4083d3 --- /dev/null +++ b/waybionic_rviz_plugins/src/setup_model.cpp @@ -0,0 +1,280 @@ +#include "waybionic_rviz_plugins/setup_model.hpp" + +#include +#include +#include +#include +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +constexpr const char * kPrefix = "setup."; +constexpr const char * kKnownSteps[] = {"carrier", "drives", "controller", "zero", "ready"}; +// The last step: it is to do while teleop is stopped, which is not a fault. +constexpr const char * kReadyStep = "ready"; + +std::size_t displayOrder(const std::string & name) +{ + for (std::size_t index = 0; index < std::size(kKnownSteps); ++index) { + if (name == kKnownSteps[index]) { + return index; + } + } + return std::size(kKnownSteps); +} + +// Problem texts quote the offending message, which ends up in the panel, so keep them short +// and printable whatever the message contains. +std::string shorten(const std::string & text) +{ + constexpr std::size_t kMaxLength = 32; + std::string result = text.substr(0, kMaxLength); + for (auto & character : result) { + const auto byte = static_cast(character); + if (byte < 0x20 || byte >= 0x7f) { + character = '?'; + } + } + if (text.size() > kMaxLength) { + result += "..."; + } + return result; +} + +// Returns the value stored under `key`, or nullptr. `duplicate` is set when the key appears +// more than once, because the intended value is then ambiguous. +const std::string * findValue( + const diagnostic_msgs::msg::DiagnosticStatus & status, const char * key, bool * duplicate) +{ + const std::string * found = nullptr; + *duplicate = false; + for (const auto & item : status.values) { + if (item.key != key) { + continue; + } + if (found != nullptr) { + *duplicate = true; + } else { + found = &item.value; + } + } + return found; +} + +bool parseState(const std::string & text, StepState * state) +{ + if (text == "ok") { + *state = StepState::Ok; + } else if (text == "todo") { + *state = StepState::Todo; + } else if (text == "blocked") { + *state = StepState::Blocked; + } else if (text == "working") { + *state = StepState::Working; + } else { + return false; + } + return true; +} + +SetupStep parseStep(const diagnostic_msgs::msg::DiagnosticStatus & status) +{ + SetupStep step; + step.message = status.message; + + // Only the first problem is kept; it is enough to find the fault. + const auto fail = [&step](const std::string & problem) { + if (step.problem.empty()) { + step.problem = problem; + } + }; + + const std::string prefix = kPrefix; + if (status.name.compare(0, prefix.size(), prefix) != 0 || status.name.size() == prefix.size()) { + fail("not a setup step"); + step.name = status.name; + } else { + step.name = status.name.substr(prefix.size()); + } + step.title = step.name; + + bool duplicate = false; + const auto * title = findValue(status, "title", &duplicate); + if (title != nullptr && !duplicate && !title->empty()) { + step.title = *title; + } + + const auto * state_text = findValue(status, "state", &duplicate); + if (duplicate) { + fail("duplicate 'state' value"); + } else if (state_text == nullptr) { + fail("missing 'state' value"); + } else if (!parseState(*state_text, &step.state)) { + fail("unknown state '" + shorten(*state_text) + "'"); + } + + // Only the zero action exists; an unknown one must not become a button that does something else. + const auto * action = findValue(status, "action", &duplicate); + if (duplicate) { + fail("duplicate 'action' value"); + } else if (action != nullptr && !action->empty()) { + if (*action == "zero") { + step.action = *action; + } else { + fail("unknown action '" + shorten(*action) + "' (only zero)"); + } + } + + const auto * current = findValue(status, "current", &duplicate); + step.current = !duplicate && current != nullptr && *current == "true"; + + step.valid = step.problem.empty(); + return step; +} + +} // namespace + +bool SetupSnapshot::ready() const +{ + return valid && !steps.empty() && + std::all_of(steps.begin(), steps.end(), [](const SetupStep & step) { + return step.state == StepState::Ok; + }); +} + +const SetupStep * SetupSnapshot::currentStep() const +{ + const auto found = std::find_if( + steps.begin(), steps.end(), [](const SetupStep & step) {return step.current;}); + return found == steps.end() ? nullptr : &*found; +} + +bool SetupSnapshot::needsAttention() const +{ + return valid && std::any_of( + steps.begin(), steps.end(), [](const SetupStep & step) { + if (step.state == StepState::Blocked) { + return true; + } + return step.state == StepState::Todo && step.name != kReadyStep; + }); +} + +SetupSnapshot parseSetup(const diagnostic_msgs::msg::DiagnosticArray & array) +{ + SetupSnapshot snapshot; + snapshot.steps.reserve(array.status.size()); + for (const auto & status : array.status) { + snapshot.steps.push_back(parseStep(status)); + } + + std::set seen; + for (auto & step : snapshot.steps) { + if (!seen.insert(step.name).second) { + step.valid = false; + if (step.problem.empty()) { + step.problem = "duplicate step"; + } + } + } + + if (snapshot.steps.empty()) { + snapshot.error = "no setup steps"; + } else { + std::size_t problems = 0; + for (const auto & step : snapshot.steps) { + if (step.valid) { + continue; + } + if (problems == 0) { + snapshot.error = shorten(step.name) + ": " + step.problem; + } + ++problems; + } + if (problems > 1) { + snapshot.error += " (and " + std::to_string(problems - 1) + " more)"; + } + } + snapshot.valid = snapshot.error.empty(); + + std::stable_sort( + snapshot.steps.begin(), snapshot.steps.end(), [](const SetupStep & left, const SetupStep & right) { + return displayOrder(left.name) < displayOrder(right.name); + }); + return snapshot; +} + +const char * stepStateWord(const StepState state) +{ + switch (state) { + case StepState::Ok: + return "done"; + case StepState::Todo: + return "to do"; + case StepState::Blocked: + return "blocked"; + case StepState::Working: + return "working"; + } + return "unknown"; +} + +bool setupGuideQuiet( + const std::optional & last_message, + const std::chrono::steady_clock::time_point now) +{ + return !last_message.has_value() || now - *last_message >= kSetupGuideQuietAfter; +} + +std::string setupWaitingMessage(const bool seen_guide, const bool guide_quiet) +{ + if (!guide_quiet) { + return "Waiting for a valid setup report..."; + } + if (seen_guide) { + return "The setup guide (setup_guide) has stopped reporting."; + } + return "Waiting for the setup guide. It runs when the station is started for the arm " + "(teleop:=true), as windows-arm.cmd and ./scripts/macos.sh arm do."; +} + +SetupDockPolicy::SetupDockPolicy(const std::chrono::steady_clock::duration hide_after) +: hide_after_(hide_after) +{ +} + +DockAction SetupDockPolicy::update( + const SetupDockInput input, const std::chrono::steady_clock::time_point now) +{ + DockAction action = DockAction::None; + switch (input) { + case SetupDockInput::NeedsAttention: + if (last_ != SetupDockInput::NeedsAttention) { + action = DockAction::Show; + } + hidden_ = false; + break; + case SetupDockInput::Ready: + if (last_ != SetupDockInput::Ready) { + ready_since_ = now; + hidden_ = false; + } + if (!hidden_ && now - ready_since_ >= hide_after_) { + action = DockAction::Hide; + hidden_ = true; + } + break; + case SetupDockInput::Waiting: + hidden_ = false; + break; + } + last_ = input; + return action; +} + +} // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/src/setup_panel.cpp b/waybionic_rviz_plugins/src/setup_panel.cpp new file mode 100644 index 00000000..1d48c21c --- /dev/null +++ b/waybionic_rviz_plugins/src/setup_panel.cpp @@ -0,0 +1,477 @@ +#include "waybionic_rviz_plugins/setup_panel.hpp" + +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +namespace waybionic_rviz_plugins +{ +namespace +{ + +constexpr int kPollIntervalMs = 100; +// The most height the panel asks of its dock for its text; a dock that is shorter scrolls it. +constexpr int kMaxFittedHeight = 420; +// The drive node waits up to half a second for the drives' replies before it answers. +constexpr std::chrono::seconds kZeroTimeout{10}; +constexpr std::chrono::seconds kStatusLifetime{10}; + +constexpr const char * kPanelStyle = R"( +QWidget { + background-color: #071019; + color: #e8f1f8; + font-family: "Segoe UI", "Ubuntu", sans-serif; + font-size: 12px; +} +QLabel#PanelTitle { + font-size: 15px; + font-weight: 700; +} +QLabel#Muted { + color: #8ea3b1; +} +QLabel#Ready { + color: #3ddc84; + font-weight: 700; +} +QPushButton { + background-color: #101d2a; + border: 1px solid #43a6ff; + border-radius: 6px; + color: #e8f1f8; + font-weight: 700; + padding: 6px; +} +QPushButton:disabled { + border-color: #284052; + color: #5d7282; +} +)"; + +struct StepLook +{ + const char * icon; + const char * color; +}; + +StepLook lookFor(const StepState state) +{ + switch (state) { + case StepState::Ok: + return {"\xE2\x9C\x93", "#3ddc84"}; // check mark + case StepState::Working: + return {"\xE2\x80\xA6", "#43a6ff"}; // ellipsis + case StepState::Todo: + return {"\xE2\x97\x8F", "#ffb84d"}; // black circle + case StepState::Blocked: + return {"\xE2\x9C\x97", "#ff4d5e"}; // ballot x + } + return {"?", "#8ea3b1"}; +} + +} // namespace + +/// What the ROS threads hand to the Qt thread. Callbacks only ever write here. +struct SetupMailbox +{ + struct ZeroReply + { + std::uint64_t token{0}; + bool success{false}; + std::string message; + }; + + std::mutex mutex; + std::optional snapshot; + std::optional received_at; + std::optional zero_reply; +}; + +SetupPanel::SetupPanel(QWidget * parent) +: rviz_common::Panel(parent), mailbox_(std::make_shared()) +{ + buildUi(); + poll_timer_ = new QTimer(this); + connect(poll_timer_, &QTimer::timeout, this, [this]() {poll();}); + poll_timer_->start(kPollIntervalMs); + render(); +} + +SetupPanel::~SetupPanel() +{ + if (poll_timer_ != nullptr) { + poll_timer_->stop(); + } + disconnectFromNode(); +} + +void SetupPanel::onInitialize() +{ + if (auto ros_node_abstraction = getDisplayContext()->getRosNodeAbstraction().lock()) { + connectToNode(ros_node_abstraction->get_raw_node()); + } +} + +void SetupPanel::connectToNode(rclcpp::Node::SharedPtr node) +{ + disconnectFromNode(); + node_ = std::move(node); + if (!node_) { + return; + } + { + std::lock_guard lock(mailbox_->mutex); + mailbox_->snapshot.reset(); + mailbox_->received_at.reset(); + mailbox_->zero_reply.reset(); + } + subscription_ = node_->create_subscription( + kSetupTopic, rclcpp::QoS(1).reliable().transient_local(), + [mailbox = mailbox_](diagnostic_msgs::msg::DiagnosticArray::ConstSharedPtr message) { + auto snapshot = parseSetup(*message); + std::lock_guard lock(mailbox->mutex); + mailbox->snapshot = std::move(snapshot); + mailbox->received_at = std::chrono::steady_clock::now(); + }); + zero_client_ = node_->create_client(kZeroServiceName); +} + +void SetupPanel::disconnectFromNode() +{ + subscription_.reset(); + if (pending_zero_.has_value() && zero_client_) { + zero_client_->remove_pending_request(pending_zero_->request_id); + } + pending_zero_.reset(); + zero_client_.reset(); + node_.reset(); + has_snapshot_ = false; + seen_guide_ = false; + snapshot_ = SetupSnapshot{}; + last_message_.reset(); + dock_policy_ = SetupDockPolicy(); +} + +void SetupPanel::buildUi() +{ + setStyleSheet(kPanelStyle); + setMinimumWidth(320); + + auto * root_layout = new QVBoxLayout(this); + root_layout->setContentsMargins(10, 10, 10, 10); + root_layout->setSpacing(6); + + auto * title = new QLabel("Arm setup"); + title->setObjectName("PanelTitle"); + root_layout->addWidget(title); + + summary_label_ = new QLabel(); + summary_label_->setObjectName("Muted"); + summary_label_->setWordWrap(true); + root_layout->addWidget(summary_label_); + + rows_widget_ = new QWidget(); + rows_layout_ = new QGridLayout(rows_widget_); + rows_layout_->setContentsMargins(0, 0, 0, 0); + rows_layout_->setHorizontalSpacing(8); + rows_layout_->setVerticalSpacing(6); + rows_layout_->setColumnStretch(2, 1); + root_layout->addWidget(rows_widget_); + + zero_button_ = new QPushButton("Zero the arm"); + zero_button_->setToolTip( + "Makes the arm's present position the zero of every drive. Only with the arm in its zero " + "pose and teleop stopped."); + connect(zero_button_, &QPushButton::clicked, this, [this]() {requestZero();}); + root_layout->addWidget(zero_button_); + + status_label_ = new QLabel(); + status_label_->setWordWrap(true); + root_layout->addWidget(status_label_); + root_layout->addStretch(1); +} + +void SetupPanel::clearRows() +{ + // The widgets go when Qt is done with any handler that is running. + for (auto & row : row_widgets_) { + for (QWidget * widget : {static_cast(row.icon), + static_cast(row.title), static_cast(row.message)}) + { + rows_layout_->removeWidget(widget); + widget->hide(); + widget->deleteLater(); + } + } + row_widgets_.clear(); + row_names_.clear(); +} + +void SetupPanel::rebuildRows(const std::vector & step_names) +{ + clearRows(); + row_names_ = step_names; + int line = 0; + for (std::size_t index = 0; index < step_names.size(); ++index) { + RowWidgets row; + row.icon = new QLabel(); + row.title = new QLabel(); + row.message = new QLabel(); + row.message->setWordWrap(true); + rows_layout_->addWidget(row.icon, line, 0, Qt::AlignTop); + rows_layout_->addWidget(row.title, line, 1, Qt::AlignTop); + rows_layout_->addWidget(row.message, line, 2); + row_widgets_.push_back(row); + ++line; + } +} + +void SetupPanel::poll() +{ + applyMailbox(); + expirePendingZero(std::chrono::steady_clock::now()); + render(); +} + +void SetupPanel::applyMailbox() +{ + std::optional snapshot; + std::optional received_at; + std::optional reply; + { + std::lock_guard lock(mailbox_->mutex); + snapshot.swap(mailbox_->snapshot); + received_at = mailbox_->received_at; + reply.swap(mailbox_->zero_reply); + } + if (received_at.has_value()) { + last_message_ = received_at; + } + if (snapshot.has_value()) { + applySnapshot(std::move(*snapshot)); + } + if (reply.has_value() && pending_zero_.has_value() && pending_zero_->token == reply->token) { + pending_zero_.reset(); + showStatus(QString::fromStdString(reply->message), reply->success); + } +} + +void SetupPanel::applySnapshot(SetupSnapshot snapshot) +{ + if (!snapshot.valid) { + // Keep showing the last good steps, and say that this message was ignored. + showStatus(QString::fromStdString("Ignoring a malformed setup report: " + snapshot.error), false); + return; + } + snapshot_ = std::move(snapshot); + has_snapshot_ = true; + seen_guide_ = true; +} + +void SetupPanel::expirePendingZero(const std::chrono::steady_clock::time_point now) +{ + if (pending_zero_.has_value() && now - pending_zero_->sent > kZeroTimeout) { + if (zero_client_) { + zero_client_->remove_pending_request(pending_zero_->request_id); + } + pending_zero_.reset(); + showStatus("No answer from the drive node to the zero request", false); + } +} + +bool SetupPanel::zeroOffered() const +{ + return has_snapshot_ && std::any_of( + snapshot_.steps.begin(), snapshot_.steps.end(), [](const SetupStep & step) { + return step.action == "zero" && step.state != StepState::Ok; + }); +} + +void SetupPanel::requestZero() +{ + if (!node_ || !zero_client_ || pending_zero_.has_value() || !zeroOffered() || + setupGuideQuiet(last_message_, std::chrono::steady_clock::now())) + { + return; + } + const auto answer = QMessageBox::question( + this, "Zero the arm", + "Is the arm in its zero pose, upright as RViz shows it, with teleop stopped?\n\n" + "Zeroing makes the arm's present position the zero of every drive.", + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); + if (answer != QMessageBox::Yes) { + return; + } + if (!zero_client_->service_is_ready()) { + showStatus("Drive node not available", false); + return; + } + PendingZero call; + call.token = ++next_token_; + call.sent = std::chrono::steady_clock::now(); + const auto sent = zero_client_->async_send_request( + std::make_shared(), + [mailbox = mailbox_, token = call.token](TriggerClient::SharedFuture future) { + const auto response = future.get(); + std::lock_guard lock(mailbox->mutex); + mailbox->zero_reply = SetupMailbox::ZeroReply{token, response->success, response->message}; + }); + call.request_id = sent.request_id; + pending_zero_ = call; + render(); +} + +void SetupPanel::showStatus(const QString & text, const bool success) +{ + status_text_ = text; + status_success_ = success; + status_expires_ = std::chrono::steady_clock::now() + kStatusLifetime; +} + +SetupDockInput SetupPanel::dockInput(const bool quiet) const +{ + if (quiet) { + // A guide that was there and has gone is a fault; one that has not started yet is not. + return seen_guide_ ? SetupDockInput::NeedsAttention : SetupDockInput::Waiting; + } + if (!has_snapshot_) { + return SetupDockInput::Waiting; + } + if (snapshot_.needsAttention()) { + return SetupDockInput::NeedsAttention; + } + return snapshot_.ready() ? SetupDockInput::Ready : SetupDockInput::Waiting; +} + +QDockWidget * SetupPanel::dock() const +{ + // The dock may hold the panel through a scroll area. + for (QWidget * widget = parentWidget(); widget != nullptr; widget = widget->parentWidget()) { + if (auto * found = qobject_cast(widget)) { + return found; + } + } + return nullptr; +} + +void SetupPanel::applyDockAction(const DockAction action) +{ + // RViz keeps every panel in a dock of its own. Hiding it is what the dock's close button does, + // and the Panels menu shows it again. + auto * panel_dock = dock(); + if (panel_dock == nullptr || action == DockAction::None) { + return; + } + if (action == DockAction::Hide) { + panel_dock->hide(); + } else { + panel_dock->show(); + panel_dock->raise(); + } +} + +void SetupPanel::resizeEvent(QResizeEvent * event) +{ + rviz_common::Panel::resizeEvent(event); + fitHeight(); +} + +// A word-wrapped label reports a one-line minimum height, and a dock gives its panel no height +// for its width, so a long message was squeezed over the row below it. Asking for the height the +// layout needs at this width keeps the text readable: a dock or scroll area that is shorter +// scrolls the panel instead. +void SetupPanel::fitHeight() +{ + // Before the dock has laid the panel out it is far narrower than it will be, so the height it + // would need there is meaningless, and as a minimum it would stop the window from maximizing. + if (layout() == nullptr || width() < minimumWidth()) { + return; + } + const int needed = std::min(layout()->totalHeightForWidth(width()), kMaxFittedHeight); + if (needed > 0 && needed != minimumHeight()) { + setMinimumHeight(needed); + } +} + +void SetupPanel::render() +{ + const auto now = std::chrono::steady_clock::now(); + const bool quiet = setupGuideQuiet(last_message_, now); + const bool shown = has_snapshot_ && !quiet; + const bool ready = shown && snapshot_.ready(); + applyDockAction(dock_policy_.update(dockInput(quiet), now)); + + if (!shown) { + summary_label_->setObjectName("Muted"); + summary_label_->setText(QString::fromStdString(setupWaitingMessage(seen_guide_, quiet))); + } else if (ready) { + summary_label_->setObjectName("Ready"); + summary_label_->setText(QString::fromUtf8("\xE2\x9C\x93 Ready: the arm can be operated")); + } else { + summary_label_->setObjectName("Muted"); + const auto * current = snapshot_.currentStep(); + summary_label_->setText( + current != nullptr ? QString::fromStdString("Next: " + current->title) : QString()); + } + // The object name picks the style, so it has to be applied again. + summary_label_->style()->unpolish(summary_label_); + summary_label_->style()->polish(summary_label_); + + std::vector names; + if (shown && !ready) { + for (const auto & step : snapshot_.steps) { + names.push_back(step.name); + } + } + if (names != row_names_) { + rebuildRows(names); + } + rows_widget_->setVisible(!names.empty()); + + for (std::size_t index = 0; index < row_names_.size(); ++index) { + const auto & step = snapshot_.steps[index]; + auto & widgets = row_widgets_[index]; + const auto look = lookFor(step.state); + widgets.icon->setText(QString::fromUtf8(look.icon)); + widgets.icon->setStyleSheet(QString("color: %1; font-weight: 700;").arg(look.color)); + widgets.title->setText(QString::fromStdString(step.title)); + widgets.title->setStyleSheet(step.current ? "font-weight: 700;" : "color: #8ea3b1;"); + widgets.message->setText(QString::fromStdString(step.message)); + widgets.message->setStyleSheet(step.current ? "" : "color: #8ea3b1;"); + } + + const bool offered = shown && zeroOffered(); + zero_button_->setVisible(offered); + zero_button_->setEnabled(offered && !pending_zero_.has_value()); + zero_button_->setText(pending_zero_.has_value() ? "Zeroing..." : "Zero the arm"); + + fitHeight(); + + if (now < status_expires_) { + status_label_->setStyleSheet( + status_success_ ? "color: #3ddc84; font-weight: 700;" : "color: #ffb84d; font-weight: 700;"); + status_label_->setText(status_text_); + } else { + status_label_->setText(QString()); + } +} + +} // namespace waybionic_rviz_plugins + +PLUGINLIB_EXPORT_CLASS(waybionic_rviz_plugins::SetupPanel, rviz_common::Panel) diff --git a/waybionic_rviz_plugins/test/test_joint_control_model.cpp b/waybionic_rviz_plugins/test/test_joint_control_model.cpp new file mode 100644 index 00000000..0b98f8ed --- /dev/null +++ b/waybionic_rviz_plugins/test/test_joint_control_model.cpp @@ -0,0 +1,459 @@ +// Tests for the Qt-free parsing of /arm/joint_control. They build fabricated +// DiagnosticArray messages, so no drive node or ROS graph is needed. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "waybionic_rviz_plugins/joint_control_model.hpp" + +namespace waybionic_rviz_plugins +{ +namespace +{ + +using diagnostic_msgs::msg::DiagnosticArray; +using diagnostic_msgs::msg::DiagnosticStatus; +using diagnostic_msgs::msg::KeyValue; +using namespace std::chrono_literals; + +KeyValue keyValue(const std::string & key, const std::string & value) +{ + KeyValue item; + item.key = key; + item.value = value; + return item; +} + +DiagnosticStatus makeStatus( + const std::string & name, const std::string & state, const std::string & angle = "0.0", + const std::string & drives = "", const std::string & message = "") +{ + DiagnosticStatus status; + status.name = name; + status.message = message; + status.values.push_back(keyValue("state", state)); + status.values.push_back(keyValue("drives", drives)); + status.values.push_back(keyValue("angle", angle)); + return status; +} + +DiagnosticArray makeArray(const std::vector & statuses) +{ + DiagnosticArray array; + array.status = statuses; + return array; +} + +// The array the drive node publishes for an arm with J2 and the tool unfitted. +DiagnosticArray healthyArray() +{ + return makeArray( + { + makeStatus("joint_1", "enabled", "0.1", "base_yaw", "enabled"), + makeStatus("joint_2", "no_drive", "0.0", "", "no drive fitted: locked at 0.0 deg"), + makeStatus("joint_3", "disabled", "0.2146755", "elbow", "disabled: held at +12.3 deg"), + makeStatus("joint_4", "enabled", "-0.3490658503988659", "wrist_left, wrist_right", "enabled"), + makeStatus("joint_5", "enabled", "0.0", "wrist_left,wrist_right", "enabled"), + makeStatus("tool_grip", "no_drive", "0.0", "", "no drive fitted: locked at 0.0 deg"), + }); +} + +std::vector names(const JointControlSnapshot & snapshot) +{ + std::vector result; + for (const auto & row : snapshot.rows) { + result.push_back(row.joint_name); + } + return result; +} + +const JointRow & rowFor(const JointControlSnapshot & snapshot, const std::string & name) +{ + for (const auto & row : snapshot.rows) { + if (row.joint_name == name) { + return row; + } + } + ADD_FAILURE() << "no row for " << name; + static const JointRow missing; + return missing; +} + +TEST(JointControlModel, ParsesAllThreeStates) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_TRUE(snapshot.error.empty()); + ASSERT_EQ(snapshot.rows.size(), 6u); + + const auto & enabled = rowFor(snapshot, "joint_1"); + EXPECT_EQ(enabled.state, JointState::Enabled); + EXPECT_TRUE(enabled.valid); + EXPECT_EQ(enabled.message, "enabled"); + EXPECT_DOUBLE_EQ(enabled.angle_rad, 0.1); + + const auto & disabled = rowFor(snapshot, "joint_3"); + EXPECT_EQ(disabled.state, JointState::Disabled); + EXPECT_EQ(disabled.message, "disabled: held at +12.3 deg"); + EXPECT_DOUBLE_EQ(disabled.angle_rad, 0.2146755); + + const auto & no_drive = rowFor(snapshot, "joint_2"); + EXPECT_EQ(no_drive.state, JointState::NoDrive); + EXPECT_EQ(no_drive.message, "no drive fitted: locked at 0.0 deg"); + EXPECT_DOUBLE_EQ(no_drive.angle_rad, 0.0); +} + +TEST(JointControlModel, ReadsNegativeAnglesWithFullPrecision) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid); + EXPECT_DOUBLE_EQ(rowFor(snapshot, "joint_4").angle_rad, -0.3490658503988659); +} + +TEST(JointControlModel, SplitsAndTrimsDriveNames) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(rowFor(snapshot, "joint_1").drives, std::vector{"base_yaw"}); + EXPECT_EQ( + rowFor(snapshot, "joint_4").drives, (std::vector{"wrist_left", "wrist_right"})); + EXPECT_EQ( + rowFor(snapshot, "joint_5").drives, (std::vector{"wrist_left", "wrist_right"})); + EXPECT_TRUE(rowFor(snapshot, "joint_2").drives.empty()); +} + +TEST(JointControlModel, DropsEmptyDriveNames) +{ + const auto snapshot = + parseJointControl(makeArray({makeStatus("joint_1", "enabled", "0.0", " ,base_yaw,, ")})); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(snapshot.rows.front().drives, std::vector{"base_yaw"}); +} + +TEST(JointControlModel, ToleratesAMissingDrivesEntry) +{ + auto status = makeStatus("joint_1", "enabled"); + status.values.erase(status.values.begin() + 1); // "drives" + const auto snapshot = parseJointControl(makeArray({status})); + + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_TRUE(snapshot.rows.front().drives.empty()); +} + +TEST(JointControlModel, KeepsTheKnownJointOrderWhateverTheArrivalOrder) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("tool_grip", "no_drive"), + makeStatus("joint_5", "enabled"), + makeStatus("joint_3", "enabled"), + makeStatus("joint_1", "enabled"), + makeStatus("joint_4", "enabled"), + makeStatus("joint_2", "no_drive"), + })); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ( + names(snapshot), + (std::vector{"joint_1", "joint_2", "joint_3", "joint_4", "joint_5", "tool_grip"})); +} + +TEST(JointControlModel, PutsUnknownJointsLastInArrivalOrder) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("wrist_roll", "enabled"), + makeStatus("tool_grip", "no_drive"), + makeStatus("joint_6", "disabled"), + makeStatus("joint_1", "enabled"), + })); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ( + names(snapshot), + (std::vector{"joint_1", "tool_grip", "wrist_roll", "joint_6"})); +} + +TEST(JointControlModel, LabelsKnownJointsAndKeepsRawNamesOtherwise) +{ + EXPECT_EQ(jointLabel("joint_1"), "J1"); + EXPECT_EQ(jointLabel("joint_2"), "J2"); + EXPECT_EQ(jointLabel("joint_3"), "J3"); + EXPECT_EQ(jointLabel("joint_4"), "J4"); + EXPECT_EQ(jointLabel("joint_5"), "J5"); + EXPECT_EQ(jointLabel("tool_grip"), "Tool"); + EXPECT_EQ(jointLabel("joint_6"), "joint_6"); + EXPECT_EQ(jointLabel("wrist_roll"), "wrist_roll"); + + const auto snapshot = parseJointControl( + makeArray({makeStatus("joint_3", "enabled"), makeStatus("wrist_roll", "enabled")})); + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(rowFor(snapshot, "joint_3").label, "J3"); + EXPECT_EQ(rowFor(snapshot, "wrist_roll").label, "wrist_roll"); +} + +TEST(JointControlModel, ListsTheKnownJointsInDisplayOrder) +{ + EXPECT_EQ( + knownJointNames(), + (std::vector{"joint_1", "joint_2", "joint_3", "joint_4", "joint_5", "tool_grip"})); +} + +TEST(JointControlModel, OnlyEnabledAndDisabledJointsAreServiceable) +{ + const auto snapshot = parseJointControl(healthyArray()); + + ASSERT_TRUE(snapshot.valid); + EXPECT_TRUE(rowFor(snapshot, "joint_1").serviceable); + EXPECT_FALSE(rowFor(snapshot, "joint_2").serviceable); + EXPECT_TRUE(rowFor(snapshot, "joint_3").serviceable); + EXPECT_TRUE(rowFor(snapshot, "joint_4").serviceable); + EXPECT_TRUE(rowFor(snapshot, "joint_5").serviceable); + EXPECT_FALSE(rowFor(snapshot, "tool_grip").serviceable); +} + +TEST(JointControlModel, IgnoresTheDiagnosticLevel) +{ + auto status = makeStatus("joint_1", "enabled"); + status.level = DiagnosticStatus::ERROR; + auto locked = makeStatus("joint_2", "disabled"); + locked.level = DiagnosticStatus::OK; + const auto snapshot = parseJointControl(makeArray({status, locked})); + + ASSERT_TRUE(snapshot.valid); + EXPECT_EQ(rowFor(snapshot, "joint_1").state, JointState::Enabled); + EXPECT_EQ(rowFor(snapshot, "joint_2").state, JointState::Disabled); +} + +TEST(JointControlModel, IgnoresEntriesItDoesNotKnow) +{ + auto status = makeStatus("joint_1", "enabled"); + status.values.push_back(keyValue("firmware", "1.2")); + const auto snapshot = parseJointControl(makeArray({status})); + + EXPECT_TRUE(snapshot.valid) << snapshot.error; +} + +TEST(JointControlModel, MissingStateInvalidatesTheArray) +{ + auto broken = makeStatus("joint_3", "enabled"); + broken.values.erase(broken.values.begin()); // "state" + const auto snapshot = parseJointControl(makeArray({makeStatus("joint_1", "enabled"), broken})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("joint_3"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("state"), std::string::npos) << snapshot.error; + EXPECT_TRUE(rowFor(snapshot, "joint_1").valid); + const auto & row = rowFor(snapshot, "joint_3"); + EXPECT_FALSE(row.valid); + EXPECT_FALSE(row.serviceable); + EXPECT_FALSE(row.problem.empty()); +} + +TEST(JointControlModel, UnknownStateInvalidatesTheArray) +{ + for (const std::string bad : {"faulted", "Enabled", "ENABLED", "no drive", "", " enabled"}) { + const auto snapshot = + parseJointControl(makeArray({makeStatus("joint_1", "enabled"), makeStatus("joint_2", bad)})); + + EXPECT_FALSE(snapshot.valid) << "state '" << bad << "' was accepted"; + EXPECT_FALSE(rowFor(snapshot, "joint_2").valid); + EXPECT_FALSE(rowFor(snapshot, "joint_2").serviceable); + EXPECT_NE(snapshot.error.find("joint_2"), std::string::npos) << snapshot.error; + } +} + +TEST(JointControlModel, DuplicateJointNamesInvalidateTheArray) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("joint_1", "enabled"), + makeStatus("joint_3", "enabled"), + makeStatus("joint_3", "disabled"), + })); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("joint_3"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("duplicate"), std::string::npos) << snapshot.error; + ASSERT_EQ(snapshot.rows.size(), 3u); + EXPECT_TRUE(snapshot.rows[0].valid); + EXPECT_TRUE(snapshot.rows[1].valid); + EXPECT_FALSE(snapshot.rows[2].valid); +} + +TEST(JointControlModel, NonNumericAngleInvalidatesTheRow) +{ + const std::vector bad_angles = { + "", "abc", "nan", "inf", "-inf", "1.5x", "0x10", " 1.0", "1.0 ", "1,5", "1e999", "--1", "1.2.3", + "e5", "+", "."}; + for (const auto & bad : bad_angles) { + const auto snapshot = parseJointControl( + makeArray({makeStatus("joint_1", "enabled"), makeStatus("joint_4", "enabled", bad)})); + + EXPECT_FALSE(snapshot.valid) << "angle '" << bad << "' was accepted"; + EXPECT_TRUE(rowFor(snapshot, "joint_1").valid); + EXPECT_FALSE(rowFor(snapshot, "joint_4").valid); + EXPECT_NE(snapshot.error.find("joint_4"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("angle"), std::string::npos) << snapshot.error; + } +} + +TEST(JointControlModel, AcceptsPlainDecimalAngles) +{ + const std::vector> good_angles = { + {"0.0", 0.0}, {"-0.3490658503988659", -0.3490658503988659}, {"1.5707963267948966", + 1.5707963267948966}, {"+0.5", 0.5}, {"-3", -3.0}, {"2.", 2.0}, {".25", 0.25}, {"1e-3", 0.001}, + {"-1.5E2", -150.0}}; + for (const auto & [text, expected] : good_angles) { + const auto snapshot = parseJointControl(makeArray({makeStatus("joint_1", "enabled", text)})); + + ASSERT_TRUE(snapshot.valid) << "angle '" << text << "' was rejected: " << snapshot.error; + EXPECT_DOUBLE_EQ(snapshot.rows.front().angle_rad, expected); + } +} + +TEST(JointControlModel, MissingAngleInvalidatesTheRow) +{ + auto status = makeStatus("joint_1", "enabled"); + status.values.pop_back(); // "angle" + const auto snapshot = parseJointControl(makeArray({status})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("angle"), std::string::npos) << snapshot.error; +} + +TEST(JointControlModel, RepeatedStateOrAngleEntriesAreAmbiguous) +{ + auto twice_state = makeStatus("joint_1", "enabled"); + twice_state.values.push_back(keyValue("state", "disabled")); + auto twice_angle = makeStatus("joint_2", "enabled"); + twice_angle.values.push_back(keyValue("angle", "1.0")); + const auto snapshot = parseJointControl(makeArray({twice_state, twice_angle})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_FALSE(rowFor(snapshot, "joint_1").valid); + EXPECT_FALSE(rowFor(snapshot, "joint_2").valid); +} + +TEST(JointControlModel, JointNamesMustBeUsableInAServiceName) +{ + for (const std::string bad : {"", "arm/joint_1", "/joint_1", "1joint", "joint 1", "joint-1"}) { + const auto snapshot = parseJointControl(makeArray({makeStatus(bad, "enabled")})); + + EXPECT_FALSE(snapshot.valid) << "name '" << bad << "' was accepted"; + EXPECT_FALSE(snapshot.rows.front().serviceable); + } +} + +TEST(JointControlModel, AnEmptyArrayIsInvalid) +{ + const auto snapshot = parseJointControl(DiagnosticArray()); + + EXPECT_FALSE(snapshot.valid); + EXPECT_TRUE(snapshot.rows.empty()); + EXPECT_FALSE(snapshot.error.empty()); +} + +TEST(JointControlModel, ReportsTheFirstProblemAndCountsTheRest) +{ + const auto snapshot = parseJointControl( + makeArray( + { + makeStatus("joint_1", "enabled"), + makeStatus("joint_2", "bogus"), + makeStatus("joint_3", "enabled", "x"), + makeStatus("joint_4", "enabled", "y"), + })); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("joint_2"), std::string::npos) << snapshot.error; + EXPECT_NE(snapshot.error.find("2 more"), std::string::npos) << snapshot.error; +} + +TEST(JointControlModel, NamesAnonymousStatusesByPosition) +{ + const auto snapshot = + parseJointControl(makeArray({makeStatus("joint_1", "enabled"), makeStatus("", "enabled")})); + + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(snapshot.error.find("status 2"), std::string::npos) << snapshot.error; +} + +TEST(JointControlModel, SurvivesHostileStrings) +{ + const std::string long_text(100000, 'x'); + const std::string with_nul("1.0\0junk", 8); + auto hostile = makeStatus(long_text, long_text, long_text, long_text, long_text); + hostile.values.push_back(keyValue(long_text, long_text)); + hostile.values.push_back(keyValue("", "")); + const auto snapshot = parseJointControl( + makeArray( + { + hostile, + makeStatus(std::string("joint_1\0x", 9), "enabled", with_nul), + makeStatus("joint_2", with_nul), + })); + + EXPECT_FALSE(snapshot.valid); + EXPECT_EQ(snapshot.rows.size(), 3u); + for (const auto & row : snapshot.rows) { + EXPECT_FALSE(row.valid); + EXPECT_FALSE(row.serviceable); + } +} + +TEST(JointControlModel, ServiceNamesFollowTheContract) +{ + EXPECT_EQ(setEnabledServiceName("joint_3"), "/arm/joint_3/set_enabled"); + EXPECT_EQ(setEnabledServiceName("tool_grip"), "/arm/tool_grip/set_enabled"); + EXPECT_STREQ(kJointControlTopic, "/arm/joint_control"); +} + +TEST(JointControlModel, StateWordsAreForTheOperator) +{ + EXPECT_STREQ(stateWord(JointState::Enabled), "enabled"); + EXPECT_STREQ(stateWord(JointState::Disabled), "disabled"); + EXPECT_STREQ(stateWord(JointState::NoDrive), "no drive"); +} + +TEST(JointControlModel, DriveNodeIsQuietWithoutAnyMessage) +{ + EXPECT_TRUE(driveNodeQuiet(std::nullopt, std::chrono::steady_clock::now())); +} + +TEST(JointControlModel, DriveNodeIsQuietFromThreeSecondsWithoutAMessage) +{ + const auto last = std::chrono::steady_clock::now(); + + EXPECT_FALSE(driveNodeQuiet(last, last)); + EXPECT_FALSE(driveNodeQuiet(last, last + 500ms)); + EXPECT_FALSE(driveNodeQuiet(last, last + 2999ms)); + EXPECT_TRUE(driveNodeQuiet(last, last + 3000ms)); + EXPECT_TRUE(driveNodeQuiet(last, last + 10s)); +} + +TEST(JointControlModel, AMessageFromTheFutureIsNotQuiet) +{ + const auto now = std::chrono::steady_clock::now(); + + EXPECT_FALSE(driveNodeQuiet(now + 1s, now)); +} + +} // namespace +} // namespace waybionic_rviz_plugins diff --git a/waybionic_rviz_plugins/test/test_setup_model.cpp b/waybionic_rviz_plugins/test/test_setup_model.cpp new file mode 100644 index 00000000..c59d3fcd --- /dev/null +++ b/waybionic_rviz_plugins/test/test_setup_model.cpp @@ -0,0 +1,392 @@ +// Tests for the Qt-free parsing of /arm/setup. They build fabricated DiagnosticArray +// messages, so no setup_guide node or ROS graph is needed. + +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +#include "waybionic_rviz_plugins/setup_model.hpp" + +namespace waybionic_rviz_plugins +{ +namespace +{ + +using diagnostic_msgs::msg::DiagnosticArray; +using diagnostic_msgs::msg::DiagnosticStatus; +using diagnostic_msgs::msg::KeyValue; +using namespace std::chrono_literals; + +KeyValue keyValue(const std::string & key, const std::string & value) +{ + KeyValue item; + item.key = key; + item.value = value; + return item; +} + +DiagnosticStatus makeStep( + const std::string & name, const std::string & title, const std::string & state, + const std::string & message, const std::string & action = "", + const std::string & current = "false") +{ + DiagnosticStatus status; + status.name = name; + status.message = message; + status.values.push_back(keyValue("title", title)); + status.values.push_back(keyValue("state", state)); + status.values.push_back(keyValue("action", action)); + status.values.push_back(keyValue("current", current)); + return status; +} + +DiagnosticArray makeArray(const std::vector & statuses) +{ + DiagnosticArray array; + array.status = statuses; + return array; +} + +// What setup_guide publishes while the arm waits to be zeroed. +DiagnosticArray zeroingArray() +{ + return makeArray( + { + makeStep("setup.carrier", "Carrier", "ok", "Carrier connected"), + makeStep("setup.drives", "Drives", "ok", "4 drives answer"), + makeStep("setup.controller", "Controller", "ok", "Controller connected"), + makeStep( + "setup.zero", "Zero", "todo", + "Put the arm in its zero pose (upright, as RViz shows it), then press Zero", "zero", + "true"), + makeStep("setup.ready", "Ready", "todo", "Waits for the steps above"), + }); +} + +DiagnosticArray readyArray() +{ + return makeArray( + { + makeStep("setup.carrier", "Carrier", "ok", "Carrier connected"), + makeStep("setup.drives", "Drives", "ok", "4 drives answer"), + makeStep("setup.controller", "Controller", "ok", "Controller connected"), + makeStep("setup.zero", "Zero", "ok", "Zeroed"), + makeStep("setup.ready", "Ready", "ok", "Teleop is on"), + }); +} + +} // namespace + +TEST(SetupModel, ParsesTheFiveStepsInOrder) +{ + const auto snapshot = parseSetup(zeroingArray()); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + ASSERT_EQ(5u, snapshot.steps.size()); + EXPECT_EQ("carrier", snapshot.steps[0].name); + EXPECT_EQ("Carrier", snapshot.steps[0].title); + EXPECT_EQ(StepState::Ok, snapshot.steps[0].state); + EXPECT_EQ("zero", snapshot.steps[3].name); + EXPECT_EQ(StepState::Todo, snapshot.steps[3].state); + EXPECT_EQ("zero", snapshot.steps[3].action); + EXPECT_TRUE(snapshot.steps[3].current); + EXPECT_FALSE(snapshot.steps[4].current); + EXPECT_EQ("Waits for the steps above", snapshot.steps[4].message); +} + +TEST(SetupModel, ReadsEveryState) +{ + const auto snapshot = parseSetup( + makeArray( + { + makeStep("setup.carrier", "Carrier", "ok", ""), + makeStep("setup.drives", "Drives", "todo", ""), + makeStep("setup.controller", "Controller", "blocked", ""), + makeStep("setup.zero", "Zero", "working", ""), + })); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_EQ(StepState::Ok, snapshot.steps[0].state); + EXPECT_EQ(StepState::Todo, snapshot.steps[1].state); + EXPECT_EQ(StepState::Blocked, snapshot.steps[2].state); + EXPECT_EQ(StepState::Working, snapshot.steps[3].state); +} + +TEST(SetupModel, KnowsWhenEverythingIsReady) +{ + EXPECT_FALSE(parseSetup(zeroingArray()).ready()); + EXPECT_TRUE(parseSetup(readyArray()).ready()); + EXPECT_FALSE(parseSetup(DiagnosticArray()).ready()); +} + +TEST(SetupModel, FindsTheCurrentStep) +{ + const auto snapshot = parseSetup(zeroingArray()); + ASSERT_NE(nullptr, snapshot.currentStep()); + EXPECT_EQ("zero", snapshot.currentStep()->name); + EXPECT_EQ(nullptr, parseSetup(readyArray()).currentStep()); +} + +TEST(SetupModel, OnlyTheZeroActionIsKnown) +{ + auto array = zeroingArray(); + array.status[3].values[2].value = "reboot"; + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("action")); + EXPECT_NE(std::string::npos, snapshot.error.find("zero")); +} + +TEST(SetupModel, AMissingActionMeansNone) +{ + auto array = zeroingArray(); + array.status[3].values.erase(array.status[3].values.begin() + 2); + const auto snapshot = parseSetup(array); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_EQ("", snapshot.steps[3].action); +} + +TEST(SetupModel, AMissingTitleFallsBackToTheStepName) +{ + auto array = zeroingArray(); + array.status[1].values.erase(array.status[1].values.begin()); + const auto snapshot = parseSetup(array); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + EXPECT_EQ("drives", snapshot.steps[1].title); +} + +TEST(SetupModel, UnknownOrMissingStatesInvalidateTheSnapshot) +{ + auto array = zeroingArray(); + array.status[0].values[1].value = "fine"; + auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("carrier")); + EXPECT_NE(std::string::npos, snapshot.error.find("fine")); + + array = zeroingArray(); + array.status[0].values.erase(array.status[0].values.begin() + 1); + snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("state")); +} + +TEST(SetupModel, StepsMustBeNamedSetupSomething) +{ + auto array = zeroingArray(); + array.status[2].name = "controller"; + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("controller")); +} + +TEST(SetupModel, DuplicateStepsInvalidateTheSnapshot) +{ + auto array = zeroingArray(); + array.status[1].name = "setup.carrier"; + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_NE(std::string::npos, snapshot.error.find("duplicate")); +} + +TEST(SetupModel, AnEmptyArrayIsInvalid) +{ + const auto snapshot = parseSetup(DiagnosticArray()); + EXPECT_FALSE(snapshot.valid); + EXPECT_FALSE(snapshot.error.empty()); +} + +TEST(SetupModel, KeepsKnownStepsInOrderAndUnknownOnesLast) +{ + const auto snapshot = parseSetup( + makeArray( + { + makeStep("setup.extra", "Extra", "ok", ""), + makeStep("setup.ready", "Ready", "todo", ""), + makeStep("setup.carrier", "Carrier", "ok", ""), + })); + ASSERT_TRUE(snapshot.valid) << snapshot.error; + ASSERT_EQ(3u, snapshot.steps.size()); + EXPECT_EQ("carrier", snapshot.steps[0].name); + EXPECT_EQ("ready", snapshot.steps[1].name); + EXPECT_EQ("extra", snapshot.steps[2].name); +} + +TEST(SetupModel, SurvivesHostileStrings) +{ + auto array = zeroingArray(); + array.status[0].message = std::string("a\0b\xff\n", 5); + array.status[1].values[0].value = std::string(10000, 'x'); + array.status[2].values[1].value = std::string("\x01\x02", 2); + const auto snapshot = parseSetup(array); + EXPECT_FALSE(snapshot.valid); + EXPECT_LT(snapshot.error.size(), 200u); +} + +TEST(SetupModel, StateWordsAreForTheOperator) +{ + EXPECT_STREQ("done", stepStateWord(StepState::Ok)); + EXPECT_STREQ("to do", stepStateWord(StepState::Todo)); + EXPECT_STREQ("blocked", stepStateWord(StepState::Blocked)); + EXPECT_STREQ("working", stepStateWord(StepState::Working)); +} + +TEST(SetupModel, TheGuideIsQuietFromThreeSecondsWithoutAMessage) +{ + const auto now = std::chrono::steady_clock::now(); + EXPECT_TRUE(setupGuideQuiet(std::nullopt, now)); + EXPECT_FALSE(setupGuideQuiet(now - 2900ms, now)); + EXPECT_TRUE(setupGuideQuiet(now - 3000ms, now)); + EXPECT_FALSE(setupGuideQuiet(now + 1s, now)); +} + +namespace +{ + +// The array with one step replaced, as when the controller drops out of a ready arm. +DiagnosticArray withStep( + DiagnosticArray array, const std::size_t index, const DiagnosticStatus & step) +{ + array.status[index] = step; + return array; +} + +// Seconds after an arbitrary start, on the clock the panel uses. +std::chrono::steady_clock::time_point at(const int seconds) +{ + return std::chrono::steady_clock::time_point{} + std::chrono::hours(1) + + std::chrono::seconds(seconds); +} + +} // namespace + +TEST(SetupModel, ASetupStepBeforeReadyThatIsNotDoneNeedsTheOperator) +{ + EXPECT_TRUE(parseSetup(zeroingArray()).needsAttention()); + EXPECT_FALSE(parseSetup(readyArray()).needsAttention()); + EXPECT_FALSE(parseSetup(DiagnosticArray()).needsAttention()); + + const auto no_controller = withStep( + readyArray(), 2, + makeStep("setup.controller", "Controller", "todo", "Connect an Xbox controller")); + EXPECT_TRUE(parseSetup(no_controller).needsAttention()); + + const auto no_answer = withStep( + readyArray(), 1, makeStep("setup.drives", "Drives", "blocked", "No answer from elbow")); + EXPECT_TRUE(parseSetup(no_answer).needsAttention()); +} + +TEST(SetupModel, AStepBeingCheckedDoesNotNeedTheOperatorYet) +{ + const auto checking = withStep( + readyArray(), 1, makeStep("setup.drives", "Drives", "working", "Checking the drives...")); + EXPECT_FALSE(parseSetup(checking).needsAttention()); +} + +TEST(SetupModel, TeleopThatIsOnlyStoppedLeavesThePanelAlone) +{ + const auto paused = withStep( + readyArray(), 4, + makeStep("setup.ready", "Ready", "todo", "Press Start (the Menu button) on the controller")); + EXPECT_FALSE(parseSetup(paused).needsAttention()); + EXPECT_FALSE(parseSetup(paused).ready()); + + const auto stopped_by_a_fault = withStep( + readyArray(), 4, + makeStep("setup.ready", "Ready", "blocked", "DRIVES-STOPPED: following error")); + EXPECT_TRUE(parseSetup(stopped_by_a_fault).needsAttention()); +} + +TEST(SetupDock, ShowsOnceWhenSomethingNeedsTheOperator) +{ + SetupDockPolicy policy(4s); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(0))); + EXPECT_EQ(DockAction::Show, policy.update(SetupDockInput::NeedsAttention, at(1))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::NeedsAttention, at(2))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::NeedsAttention, at(60))); +} + +TEST(SetupDock, HidesOnceAfterTheArmHasBeenReadyForTheDelay) +{ + SetupDockPolicy policy(4s); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(0))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(3))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); + // Opened again by hand while ready, it stays open. + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(5))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(600))); +} + +TEST(SetupDock, ANewProblemShowsItAgainAndReadyHidesItAgain) +{ + SetupDockPolicy policy(4s); + policy.update(SetupDockInput::Ready, at(0)); + ASSERT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); + // The controller drops out and comes back, straight from ready to a problem and back. + EXPECT_EQ(DockAction::Show, policy.update(SetupDockInput::NeedsAttention, at(10))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(12))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(15))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(16))); +} + +TEST(SetupDock, AStepBeingCheckedRestartsTheCountdown) +{ + SetupDockPolicy policy(4s); + policy.update(SetupDockInput::Ready, at(0)); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(3))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(3))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(4))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(7))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(8))); +} + +TEST(SetupDock, PausingTeleopNeitherShowsNorHidesThePanel) +{ + SetupDockPolicy policy(4s); + policy.update(SetupDockInput::Ready, at(0)); + ASSERT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); + // B stops teleop: only Start is left to press. + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(10))); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Waiting, at(100))); + // Start again: a new ready period, so it is hidden again after the delay. + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(101))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(105))); +} + +TEST(SetupDock, TheDefaultDelayIsFourSeconds) +{ + EXPECT_EQ(std::chrono::milliseconds(4000), kSetupHideAfter); + SetupDockPolicy policy; + policy.update(SetupDockInput::Ready, at(0)); + EXPECT_EQ(DockAction::None, policy.update(SetupDockInput::Ready, at(3))); + EXPECT_EQ(DockAction::Hide, policy.update(SetupDockInput::Ready, at(4))); +} + +TEST(SetupModel, SaysWhyThereIsNoSetupGuide) +{ + // A station started without the arm, such as the plain viewer, never runs the guide. + const auto never = setupWaitingMessage(false, true); + EXPECT_NE(std::string::npos, never.find("teleop:=true")); + EXPECT_NE(std::string::npos, never.find("windows-arm")); + EXPECT_NE(std::string::npos, never.find("macos.sh arm")); + // One that was running and has gone is a fault, not a missing launch option. + const auto gone = setupWaitingMessage(true, true); + EXPECT_NE(std::string::npos, gone.find("stopped")); + EXPECT_EQ(std::string::npos, gone.find("teleop:=true")); + // Reports that arrive but are all malformed. + EXPECT_NE(std::string::npos, setupWaitingMessage(false, false).find("valid setup report")); +} + +TEST(SetupModel, TheZeroServiceIsTheDriveNodes) +{ + EXPECT_STREQ("/sim_arm_drives/zero", kZeroServiceName); + EXPECT_STREQ("/arm/setup", kSetupTopic); +} + +} // namespace waybionic_rviz_plugins diff --git a/waybionic_teleop/config/arm_profile_bench.yaml b/waybionic_teleop/config/arm_profile_bench.yaml new file mode 100644 index 00000000..3cf4f420 --- /dev/null +++ b/waybionic_teleop/config/arm_profile_bench.yaml @@ -0,0 +1,7 @@ +# The bench arm as it is built now: a drive on each of J1 to J5 (CAN IDs 1 to 5) and no tool +# drive. The Windows launcher (compose.yaml, wslg-arm) uses this file, as a Mac uses +# ~/.waybionic/arm_profile.yaml; waybionic_teleop/arm_profile.py describes the format. +# When the tool drive (CAN ID 6) is fitted, add `tool` to fitted_drives and delete tool_grip +# from locked_joints. +fitted_drives: [base_yaw, shoulder, elbow, wrist_left, wrist_right] +locked_joints: {tool_grip: 0.0} diff --git a/waybionic_teleop/setup.py b/waybionic_teleop/setup.py index a5943eff..2a4fcda2 100644 --- a/waybionic_teleop/setup.py +++ b/waybionic_teleop/setup.py @@ -31,6 +31,7 @@ 'mks_drive_sim = waybionic_teleop.mks_drive_sim:main', 'mks_setup = waybionic_teleop.mks_setup:main', 'autoplay = waybionic_teleop.autoplay_node:main', + 'setup_guide = waybionic_teleop.setup_guide:main', 'joy_udp_receiver = waybionic_teleop.joy_udp_receiver:main', ], }, diff --git a/waybionic_teleop/test/test_arm_profile.py b/waybionic_teleop/test/test_arm_profile.py index 1d8c39a1..2457b3c7 100644 --- a/waybionic_teleop/test/test_arm_profile.py +++ b/waybionic_teleop/test/test_arm_profile.py @@ -1,5 +1,7 @@ """An arm profile says which drives one arm has and holds still the joints it lacks.""" +from pathlib import Path + import pytest from waybionic_teleop.arm_profile import ( @@ -25,6 +27,15 @@ def test_the_bench_profile_runs_four_drives_and_holds_the_shoulder(parameters, b assert params['drives'][1] == 'shoulder' +def test_the_shipped_bench_profile_fits_the_arm_as_built(parameters): + # The Windows launcher passes this file, so it has to stay valid for the arm map. + shipped = Path(__file__).resolve().parent.parent / 'config' / 'arm_profile_bench.yaml' + profile = load_profile(shipped) + assert profile.locked_joints == {'tool_grip': 0.0} + fitted = fit_drive_parameters(parameters('arm_drives.yaml', 'sim_arm_drives'), profile) + assert fitted['drives'] == ['base_yaw', 'shoulder', 'elbow', 'wrist_left', 'wrist_right'] + + @pytest.mark.parametrize('data, message', [ ([], 'must be a mapping'), ({'fitted': ['base_yaw']}, 'unknown keys'), diff --git a/waybionic_teleop/test/test_carrier_relay.py b/waybionic_teleop/test/test_carrier_relay.py new file mode 100644 index 00000000..d812def1 --- /dev/null +++ b/waybionic_teleop/test/test_carrier_relay.py @@ -0,0 +1,212 @@ +import socket +import threading +import time +from types import SimpleNamespace + +import pytest +import serial + +from waybionic_teleop import carrier_relay + + +class LostCarrier: + """A carrier that has just been unplugged.""" + + in_waiting = 0 + + def read(self, size=1): + raise serial.SerialException('device unplugged') + + def write(self, data): + raise serial.SerialException('device unplugged') + + +def loop_carrier(): + return serial.serial_for_url('loop://', timeout=carrier_relay.POLL_S) + + +def start(link): + """Run relay() in a thread; return our end of the connection, stop, thread and result.""" + ours, theirs = socket.socketpair() + ours.settimeout(2.0) + stop = threading.Event() + result = [] + thread = threading.Thread( + target=lambda: result.append(carrier_relay.relay(link, theirs, stop)), daemon=True) + thread.start() + return ours, stop, thread, result + + +def test_frames_pass_both_ways(): + link = loop_carrier() + ours, stop, thread, result = start(link) + frame = b't00121234\r' + ours.sendall(frame) + echoed = b'' + while len(echoed) < len(frame): + echoed += ours.recv(64) + assert echoed == frame + stop.set() + thread.join(2.0) + assert result == ['stopped'] + ours.close() + link.close() + + +def test_lost_carrier_closes_the_connection(): + ours, stop, thread, result = start(LostCarrier()) + assert ours.recv(64) == b'' + thread.join(2.0) + assert result == ['serial'] + ours.close() + + +def test_stopping_closes_the_connection(): + link = loop_carrier() + ours, stop, thread, result = start(link) + stop.set() + assert ours.recv(64) == b'' + thread.join(2.0) + assert result == ['stopped'] + ours.close() + link.close() + + +def test_ground_station_disconnect_keeps_the_carrier_open(): + link = loop_carrier() + ours, stop, thread, result = start(link) + ours.close() + thread.join(2.0) + assert result == ['client'] + assert link.is_open + link.close() + + +def test_no_connection_while_the_carrier_is_unplugged(): + probe = socket.create_server(('127.0.0.1', 0)) + tcp_port = probe.getsockname()[1] + probe.close() + stop = threading.Event() + + def unplugged(): + raise serial.SerialException('could not open port') + + thread = threading.Thread( + target=carrier_relay.serve, + args=(unplugged, '127.0.0.1', tcp_port, stop, lambda message: None), daemon=True) + thread.start() + try: + with pytest.raises(OSError): + socket.create_connection(('127.0.0.1', tcp_port), timeout=1.0) + finally: + stop.set() + thread.join(2.0) + + +def test_port_in_use_exits_with_a_message(): + taken = socket.create_server(('127.0.0.1', 0)) + tcp_port = taken.getsockname()[1] + stop = threading.Event() + try: + with pytest.raises(SystemExit, match='already in use'): + carrier_relay.serve(loop_carrier, '127.0.0.1', tcp_port, stop, lambda message: None) + finally: + taken.close() + + +class ComPorts: + """The COM ports Windows lists, which a test changes as the carrier is plugged in.""" + + def __init__(self, *devices): + self.devices, self.opened = list(devices), [] + + def arduino(self, device): + return SimpleNamespace(device=device, vid=carrier_relay.ARDUINO_VID) + + def listed(self): + return [self.arduino(device) if device.startswith('COM') else + SimpleNamespace(device=device, vid=0x1A86) for device in self.devices] + + def open_serial(self, name, baudrate, timeout): + self.opened.append((name, baudrate)) + return name + + +def opener(ports, port=None): + return carrier_relay.carrier_opener( + port, 1000000, open_serial=ports.open_serial, list_com_ports=ports.listed, + log=lambda message: None) + + +def test_a_carrier_plugged_in_after_the_relay_started_is_found(): + ports = ComPorts() + open_carrier = opener(ports) + with pytest.raises(serial.SerialException, match='no Arduino COM port found.*plug in'): + open_carrier() + ports.devices.append('COM5') + assert open_carrier() == 'COM5' + assert ports.opened == [('COM5', 1000000)] + + +def test_a_replugged_carrier_is_found_under_its_new_com_number(): + ports = ComPorts('COM5') + open_carrier = opener(ports) + assert open_carrier() == 'COM5' + ports.devices[:] = ['COM7'] + assert open_carrier() == 'COM7' + + +def test_other_serial_devices_are_not_mistaken_for_the_carrier(): + ports = ComPorts('/dev/ttyUSB0') + with pytest.raises(serial.SerialException, match='no Arduino COM port found'): + opener(ports)() + assert ports.opened == [] + + +def test_the_relay_does_not_guess_between_several_arduinos(): + ports = ComPorts('COM3', 'COM5') + with pytest.raises(serial.SerialException, match=r'COM3, COM5.*--port'): + opener(ports)() + assert ports.opened == [] + + +def test_a_port_that_is_given_is_opened_without_looking_for_it(): + ports = ComPorts() + assert opener(ports, port='COM9')() == 'COM9' + + +def test_the_relay_starts_listening_once_the_carrier_is_plugged_in(): + probe = socket.create_server(('127.0.0.1', 0)) + tcp_port = probe.getsockname()[1] + probe.close() + ports = ComPorts() + messages, stop = [], threading.Event() + opener_with_loop = carrier_relay.carrier_opener( + None, 1000000, open_serial=lambda name, baudrate, timeout: loop_carrier(), + list_com_ports=ports.listed, log=messages.append) + thread = threading.Thread( + target=carrier_relay.serve, daemon=True, + args=(opener_with_loop, '127.0.0.1', tcp_port, stop, messages.append)) + thread.start() + try: + time.sleep(0.2) + with pytest.raises(OSError): + socket.create_connection(('127.0.0.1', tcp_port), timeout=0.5) + assert any('plug in the carrier' in message for message in messages) + ports.devices.append('COM5') + deadline = time.monotonic() + 4.0 + while True: + try: + client = socket.create_connection(('127.0.0.1', tcp_port), timeout=0.5) + break + except OSError: + assert time.monotonic() < deadline, 'the relay never listened' + time.sleep(0.05) + client.settimeout(2.0) + client.sendall(b't00121234\r') + assert client.recv(64) == b't00121234\r' + client.close() + assert 'Carrier on COM5' in messages + finally: + stop.set() + thread.join(3.0) diff --git a/waybionic_teleop/test/test_incision.py b/waybionic_teleop/test/test_incision.py index 529a2ce2..8bc97cdc 100644 --- a/waybionic_teleop/test/test_incision.py +++ b/waybionic_teleop/test/test_incision.py @@ -323,3 +323,39 @@ def test_a_new_incision_point_clears_only_the_incision_warning(teleop): run(teleop, 0.1) assert teleop.incision is not None assert teleop.warning and teleop.note == 'Controller lost; press Start (Menu) to enable' + + +def test_switching_a_joint_off_with_the_tool_through_the_incision_keeps_the_group(teleop): + run(teleop, 1.0, left_y=1.0) + run(teleop, 0.3) + first, inserted = teleop.incision, dict(teleop.targets) + assert teleop.set_disabled({'joint_5'}, inserted) + # Leaving the group would let the other groups, and going home, drag the tool sideways + # inside the incision, as Y and A are refused for. + assert not teleop.enabled and teleop.active_group.name == 'incision' + assert teleop.incision == first and teleop.warning and 'switch it back on' in teleop.note + press(teleop, 'start') + assert not teleop.enabled and 'switch it back on' in teleop.note + run(teleop, 0.5, 'a') + assert teleop.targets == inserted + # With the joint back on, the group moves again. + assert teleop.set_disabled(set(), inserted) + press(teleop, 'start') + assert teleop.enabled and teleop.active_group.name == 'incision' + assert teleop.incision == pytest.approx(first, abs=1e-12) + + +def test_a_tool_that_is_out_of_the_incision_lets_the_group_go_and_is_remembered(teleop, arm): + run(teleop, 1.0, left_y=1.0) + run(teleop, 0.3) + first = teleop.incision + # While teleop is off the tool ends up beside the incision point, still deep. + beside = shifted(arm, teleop.targets, 0.02) + teleop.disable(beside, 'moved') + assert teleop.set_disabled({'joint_5'}, beside) + assert teleop.active_group.name == 'base' and not teleop.withdrawn + teleop.set_disabled(set(), beside) + # Choosing the incision group again must not take the tool tip for the new incision point. + for _ in range(len(teleop.groups) - 1): + press(teleop, 'y') + assert teleop.active_group.name == 'incision' and teleop.incision == first diff --git a/waybionic_teleop/test/test_setup_guide.py b/waybionic_teleop/test/test_setup_guide.py new file mode 100644 index 00000000..786a69d6 --- /dev/null +++ b/waybionic_teleop/test/test_setup_guide.py @@ -0,0 +1,280 @@ +"""The guided start-up steps: what the operator has to do next, from the /diagnostics rows.""" + +from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue +import pytest +import rclpy +from rclpy.parameter import Parameter + +from waybionic_teleop import setup_guide +from waybionic_teleop.setup_guide import BLOCKED, OK, SetupGuide, TODO, WORKING + +OK_LEVEL, WARN, ERROR, STALE = (DiagnosticStatus.OK, DiagnosticStatus.WARN, + DiagnosticStatus.ERROR, DiagnosticStatus.STALE) + + +def row(name, level=OK_LEVEL, message='', value='', **values): + items = {'value': value, **values} + return DiagnosticStatus(name=name, level=level, message=message, values=[ + KeyValue(key=key, value=str(item)) for key, item in items.items()]) + + +def table(*rows): + return {item.name: item for item in rows} + + +def drive(name, can_id, text='ready', level=OK_LEVEL): + return row(f'drive.{name}', level, f'CAN ID {can_id}: {text}', '0.000', can_id=can_id) + + +CARRIER = row('can.carrier', value='released') +GATE = row('arm.command_gate', WARN, 'Teleop disabled', 'stopped') +DRIVES = [drive('base_yaw', 1), drive('elbow', 3), drive('wrist_left', 4), + drive('wrist_right', 5)] +JOINTS = [row(f'arm.joint_{number}', value='+0.0', unit='deg') for number in range(1, 6)] +CONTROLLER = row('teleop.input', value='120') + + +def ready_rows(**changes): + rows = table(CARRIER, GATE, *DRIVES, *JOINTS, CONTROLLER, + row('can.bus', value='500', interface='slcan'), + row('teleop.state', value='disabled', message='Press Start to enable')) + rows.update(changes) + return {name: item for name, item in rows.items() if item is not None} + + +def states(rows): + return {step.name: step.state for step in setup_guide.evaluate(rows)} + + +def step(rows, name): + return next(item for item in setup_guide.evaluate(rows) if item.name == name) + + +def test_the_steps_come_in_the_order_the_operator_does_them(): + steps = setup_guide.evaluate({}) + assert [item.name for item in steps] == ['carrier', 'drives', 'controller', 'zero', 'ready'] + assert [item.title for item in steps] == ['Carrier', 'Drives', 'Controller', 'Zero', 'Ready'] + + +def test_nothing_is_running_yet(): + found = states({}) + assert found == {'carrier': WORKING, 'drives': TODO, 'controller': WORKING, 'zero': TODO, + 'ready': TODO} + assert 'Waiting' in step({}, 'carrier').message + + +def test_everything_in_order_leaves_only_start(): + found = states(ready_rows()) + assert [found[name] for name in ('carrier', 'drives', 'controller', 'zero')] == [OK] * 4 + ready = step(ready_rows(), 'ready') + assert ready.state == TODO and 'Start' in ready.message + assert states(ready_rows(**{'teleop.state': row('teleop.state', value='enabled')}))[ + 'ready'] == OK + + +def test_the_current_step_is_the_first_that_is_not_done(): + assert setup_guide.current(setup_guide.evaluate(ready_rows())).name == 'ready' + done = ready_rows(**{'teleop.state': row('teleop.state', value='enabled')}) + assert setup_guide.current(setup_guide.evaluate(done)) is None + assert setup_guide.current(setup_guide.evaluate({})).name == 'carrier' + + +@pytest.mark.parametrize('carrier, state, words', [ + (row('can.carrier', ERROR, 'USB link lost', 'unplugged'), TODO, 'USB-C'), + (row('can.carrier', WARN, 'No status from the carrier', 'silent'), BLOCKED, 'firmware'), + (row('can.carrier', ERROR, 'E-stop pressed', 'pressed'), BLOCKED, 'E-stop'), +]) +def test_a_carrier_that_is_not_there_holds_up_the_drives_and_what_needs_them( + carrier, state, words): + rows = ready_rows(**{'can.carrier': carrier}) + assert step(rows, 'carrier').state == state and words in step(rows, 'carrier').message + # The controller does not depend on it. + assert states(rows) == {'carrier': state, 'drives': TODO, 'controller': OK, 'zero': TODO, + 'ready': TODO} + assert setup_guide.current(setup_guide.evaluate(rows)).name == 'carrier' + + +def test_a_simulated_or_other_bus_needs_no_carrier(): + simulated = ready_rows(**{'can.carrier': None, + 'can.bus': row('can.bus', value='500', interface='sim')}) + assert step(simulated, 'carrier').state == OK and 'Simulated' in step( + simulated, 'carrier').message + socketcan = ready_rows(**{'can.carrier': None, + 'can.bus': row('can.bus', value='500', interface='socketcan')}) + assert 'socketcan' in step(socketcan, 'carrier').message + + +def test_a_drive_that_does_not_answer_is_named_with_its_can_id(): + silent = drive('elbow', 3, 'no reply', ERROR) + rows = ready_rows(**{'drive.elbow': silent}) + found = step(rows, 'drives') + assert found.state == BLOCKED + assert 'elbow' in found.message and 'CAN 3' in found.message + assert 'Joint control' in found.message + assert step(rows, 'zero').state == TODO + + +def test_a_drive_whose_joint_is_switched_off_is_not_a_problem(): + off = drive('elbow', 3, 'disabled (no reply)', WARN) + found = step(ready_rows(**{'drive.elbow': off}), 'drives') + assert found.state == OK and '3 drives answer' in found.message + assert '1 switched off' in found.message + + +def test_a_drive_that_reports_a_fault_blocks_with_its_state(): + failed = drive('base_yaw', 1, 'run failed', ERROR) + found = step(ready_rows(**{'drive.base_yaw': failed}), 'drives') + assert found.state == BLOCKED and 'base_yaw' in found.message and 'run failed' in found.message + + +def test_a_drive_that_fails_its_health_check_says_what_it_found(): + # The drive node raises the row's level for its health state but its message only has the + # move status, so the guide has to say what the health check found. + behind = row('drive.base_yaw', ERROR, 'CAN ID 1: run complete; last 001#F5000000000000F6', + '0.000', can_id=1, state='FOLLOWING_ERROR', target_encoder_error_deg='-6.300') + found = step(ready_rows(**{'drive.base_yaw': behind}), 'drives') + assert found.state == BLOCKED + assert 'base_yaw (following error: 6.3 deg off its target)' in found.message + assert 'run complete' not in found.message + + stalled = row('drive.elbow', ERROR, 'CAN ID 3: running', '0.000', can_id=3, state='STALLED', + target_encoder_error_deg='2.000') + assert 'elbow (stalled: 2.0 deg off its target)' in step( + ready_rows(**{'drive.elbow': stalled}), 'drives').message + + disabled = row('drive.elbow', ERROR, 'CAN ID 3: ready', '0.000', can_id=3, state='DISABLED') + assert 'elbow (disabled)' in step(ready_rows(**{'drive.elbow': disabled}), 'drives').message + + +def test_a_drive_that_fails_its_move_keeps_its_own_status_when_it_is_healthy(): + failed = row('drive.base_yaw', ERROR, 'CAN ID 1: run failed', '0.000', can_id=1, state='OK', + target_encoder_error_deg='0.100') + assert 'base_yaw (run failed)' in step( + ready_rows(**{'drive.base_yaw': failed}), 'drives').message + + +def test_drives_still_being_set_up_are_work_in_progress(): + pending = drive('base_yaw', 1, 'ready, setup 82h unconfirmed', WARN) + assert step(ready_rows(**{'drive.base_yaw': pending}), 'drives').state == WORKING + assert step(ready_rows(**{f'drive.{name}': None for name in ( + 'base_yaw', 'elbow', 'wrist_left', 'wrist_right')}), 'drives').state == WORKING + + +def test_the_controller_must_be_sending_input(): + quiet = row('teleop.input', STALE, 'No /joy input from a controller', '0') + found = step(ready_rows(**{'teleop.input': quiet}), 'controller') + assert found.state == TODO and 'Connect' in found.message + assert step(ready_rows(**{'teleop.input': None}), 'controller').state == WORKING + + +def test_zero_asks_for_the_zero_pose_and_offers_the_zero_action(): + rows = ready_rows(**{'arm.zero': row('arm.zero', WARN, 'Not zeroed.', 'no'), + **{f'arm.joint_{number}': None for number in range(1, 6)}}) + found = step(rows, 'zero') + assert found.state == TODO and found.action == 'zero' and 'zero pose' in found.message + assert step(ready_rows(), 'zero').action == '' + checking = ready_rows(**{'arm.zero': row('arm.zero', WARN, 'Checking', 'checking'), + **{f'arm.joint_{number}': None for number in range(1, 6)}}) + assert step(checking, 'zero').state == WORKING and step(checking, 'zero').action == '' + assert step(rows, 'ready').state == TODO and 'above' in step(rows, 'ready').message + + +def test_a_teleop_that_cannot_start_blocks_the_last_step(): + broken = row('teleop.state', ERROR, 'Waiting for robot_description', 'disabled') + found = step(ready_rows(**{'teleop.state': broken}), 'ready') + assert found.state == BLOCKED and 'robot_description' in found.message + + +@pytest.fixture +def guide(monkeypatch): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + node = SetupGuide(context=context, parameter_overrides=[ + Parameter('diagnostics_topic', value='/diagnostics')]) + yield node + node.destroy_node() + rclpy.try_shutdown(context=context) + + +def test_the_guide_publishes_each_step_latched(guide, monkeypatch): + published = [] + monkeypatch.setattr(guide.publisher, 'publish', published.append) + assert guide.publisher.qos_profile.durability == rclpy.qos.DurabilityPolicy.TRANSIENT_LOCAL + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + guide.publish_steps() + message = published[-1] + assert [item.name for item in message.status] == [ + 'setup.carrier', 'setup.drives', 'setup.controller', 'setup.zero', 'setup.ready'] + values = [{item.key: item.value for item in found.values} for found in message.status] + assert [item['state'] for item in values] == [OK, OK, OK, OK, TODO] + assert [item['title'] for item in values] == [ + 'Carrier', 'Drives', 'Controller', 'Zero', 'Ready'] + assert [item['current'] for item in values] == ['false'] * 4 + ['true'] + assert [found.level for found in message.status] == [OK_LEVEL] * 4 + [WARN] + + +def test_rows_that_stop_arriving_are_forgotten(guide, monkeypatch): + clock = [100.0] + monkeypatch.setattr(setup_guide.time, 'monotonic', lambda: clock[0]) + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + assert states(guide.fresh_rows()) == states(ready_rows()) + clock[0] += setup_guide.ROW_TIMEOUT_S + 0.1 + assert step(guide.fresh_rows(), 'carrier').state == WORKING + # One row that keeps coming stays, whatever the rest do. + guide.on_diagnostics(DiagnosticArray(status=[CARRIER, GATE])) + assert set(guide.fresh_rows()) == {'can.carrier', 'arm.command_gate'} + + +def test_a_step_that_changes_is_logged_once(guide, monkeypatch): + messages = [] + monkeypatch.setattr(guide, 'announce', messages.append) + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + guide.publish_steps() + guide.publish_steps() + assert len(messages) == 1 and 'Ready' in messages[0] and 'Start' in messages[0] + + +def test_a_problem_is_only_reported_once_it_has_lasted(guide, monkeypatch): + # The drives and the carrier take a few seconds to answer after a start; saying 'no answer' + # at once would blame wiring that is fine. + clock = [100.0] + monkeypatch.setattr(setup_guide.time, 'monotonic', lambda: clock[0]) + published = [] + monkeypatch.setattr(guide.publisher, 'publish', published.append) + + def drives(*changes): + # The other nodes report every half second, so the rows stay fresh. + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows(**dict(changes)).values()))) + guide.publish_steps() + found = next(item for item in published[-1].status if item.name == 'setup.drives') + return {item.key: item.value for item in found.values}['state'], found.message + + silent = ('drive.elbow', drive('elbow', 3, 'no reply', ERROR)) + state, message = drives(silent) + assert state == WORKING and 'elbow' not in message + clock[0] += setup_guide.BLOCK_GRACE_S - 0.5 + assert drives(silent)[0] == WORKING + clock[0] += 1.0 + state, message = drives(silent) + assert state == BLOCKED and 'elbow' in message + # Once it clears, the next problem starts the wait again. + assert drives()[0] == OK + clock[0] += 0.5 + assert drives(silent)[0] == WORKING + + +def test_a_zero_that_succeeded_is_not_offered_again(guide): + # The drive node reports arm.zero or the joints' positions, never both, so one appearing + # ends the other even though its last row is still fresh. + joints = {f'arm.joint_{number}': None for number in range(1, 6)} + unzeroed = ready_rows(**{'arm.zero': row('arm.zero', WARN, 'Not zeroed.', 'no'), **joints}) + guide.on_diagnostics(DiagnosticArray(status=list(unzeroed.values()))) + assert step(guide.fresh_rows(), 'zero').action == 'zero' + guide.on_diagnostics(DiagnosticArray(status=list(ready_rows().values()))) + assert 'arm.zero' not in guide.fresh_rows() + assert step(guide.fresh_rows(), 'zero').state == OK + # And when the arm loses its zero, the old positions are no longer true. + guide.on_diagnostics(DiagnosticArray(status=list(unzeroed.values()))) + assert not any(name.startswith('arm.joint_') for name in guide.fresh_rows()) + assert step(guide.fresh_rows(), 'zero').action == 'zero' diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index 607480a7..4a1d3f03 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -1,5 +1,6 @@ """Exercise the ROS command gate and MKS frames without a hardware CAN interface.""" +from collections import deque import importlib.util import math from pathlib import Path @@ -14,7 +15,7 @@ from rclpy.parameter import Parameter from sensor_msgs.msg import JointState from std_msgs.msg import Bool, String -from std_srvs.srv import Trigger +from std_srvs.srv import SetBool, Trigger from waybionic_control.drive_health import ( DriveHealthMonitor, @@ -1626,26 +1627,315 @@ def measured(): return dict(zip(states[-1].name, states[-1].position)) teleop.enable(measured(), [0.0] * len(AXES)) assert teleop.enabled, teleop.note - # The base group's sticks ask for the base, the shoulder and the elbow at once; then, with - # the elbow bent, the Cartesian group asks for a straight move only the shoulder could make. - sticks = [[0.0] * len(AXES) for _ in range(2)] + # The Cartesian groups solve the shoulder too, so there are none for this arm. + assert [group.name for group in teleop.groups] == ['base', 'upper'] + # The base group's sticks ask for the base, the shoulder and the elbow at once. The + # shoulder cannot move, which is not a limit, so the controller has nothing to rumble about. + axes = [0.0] * len(AXES) for axis in ('left_x', 'left_y', 'right_y'): - sticks[0][AXES.index(axis)] = 1.0 - sticks[1][AXES.index('left_y')] = 1.0 - for group, axes in zip(('base', 'cartesian'), sticks): - teleop.group = [item.name for item in teleop.groups].index(group) - for _ in range(60): - teleop.update(axes, [0] * len(BUTTONS), measured(), bench.period) - targets = teleop.command_targets - bench.on_enabled(Bool(data=True)) - bench.on_command(JointState( - name=list(targets), position=list(targets.values()), - velocity=[teleop.velocities[joint] for joint in targets])) - advance(bench) - assert bench.authorized, bench.stop_reason - assert 'joint_2' in teleop.blocked, group + axes[AXES.index(axis)] = 1.0 + for _ in range(60): + teleop.update(axes, [0] * len(BUTTONS), measured(), bench.period) + targets = teleop.command_targets + bench.on_enabled(Bool(data=True)) + bench.on_command(JointState( + name=list(targets), position=list(targets.values()), + velocity=[teleop.velocities[joint] for joint in targets])) + advance(bench) + assert bench.authorized, bench.stop_reason + assert teleop.blocked == [] assert bench.rejected == 0 assert abs(measured()['joint_1']) > 0.1 and measured()['joint_2'] == 0.0 + assert abs(measured()['joint_3']) > 0.1 + + +def without_drive(drives_with, can_id, **changes): + """Make a node whose drive is not on the bus, as when it is faulty or not yet fitted.""" + node = drives_with(zero_on_start=False, **changes) + node.bus.drives.pop(can_id) + # Whatever it answered while the node was being made is not heard. + node.bus.replies = deque(reply for reply in node.bus.replies if reply[0] != can_id) + return node + + +def arm_up(node): + advance(node) + node.on_description(String(data=URDF)) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert node.authorized, node.stop_reason + + +def published_joint_control(node, monkeypatch): + messages = [] + monkeypatch.setattr(node.joint_control_publisher, 'publish', messages.append) + return messages + + +def rows(message): + return {row.name: ({item.key: item.value for item in row.values}, row.message) + for row in message.status} + + +def test_a_joint_is_switched_off_only_while_the_arm_is_stopped(node): + ready(node) + ok, message = node.set_joint_enabled('joint_3', False) + assert not ok and 'disable teleop' in message and not node.disabled + node.on_enabled(Bool(data=False)) + node.on_command(command(node)) + ok, message = node.set_joint_enabled('joint_3', False) + assert not ok and 'still arriving' in message + node.command_time -= QUIET_BEFORE_ZERO_S + assert node.set_joint_enabled('joint_3', False) == (True, 'joint_3 is disabled') + assert node.disabled == {'joint_3'} + assert node.set_joint_enabled('joint_3', True) == (True, 'joint_3 is enabled') + assert node.disabled == set() + + +def test_a_joint_with_no_drive_cannot_be_switched(bench): + ok, message = bench.set_joint_enabled('joint_2', True) + assert not ok and 'no drive' in message + assert not bench.set_joint_enabled('not_a_joint', False)[0] + assert bench.disabled == set() + + +def test_a_disabled_joint_gets_no_target_and_the_others_keep_moving(node): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.on_command(command(node, joint_2=0.1)) + advance(node) + advance(node) + assert node.authorized and node.rejected == 0 + assert node.bus.drives[2].target is not None + assert node.bus.drives[1].target is None + + +@pytest.mark.parametrize('moved, accepted', [(0.005, True), (0.5, False)]) +def test_a_command_must_hold_a_disabled_joint_at_its_anchor(node, moved, accepted): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.on_command(command(node, joint_1=moved, joint_2=0.1)) + assert node.authorized == accepted + if accepted: + # Count jitter between teleop's reading and ours is absorbed, and sent back exactly. + assert node.commanded['joint_1'] == 0.0 and node.velocities['joint_1'] == 0.0 + else: + assert node.stop_reason == 'joint_1 is disabled' and node.rejected == 1 + + +def test_one_wrist_joint_disabled_keeps_both_wrist_drives_following(node): + assert node.set_joint_enabled('joint_4', False)[0] + assert node.idle == set() + ready(node) + node.on_command(command(node, joint_5=0.2)) + advance(node) + advance(node) + assert node.bus.drives[4].target is not None and node.bus.drives[5].target is not None + node.on_command(command(node, joint_4=0.2)) + assert not node.authorized and node.stop_reason == 'joint_4 is disabled' + node.command_time -= QUIET_BEFORE_ZERO_S + assert node.set_joint_enabled('joint_5', False)[0] and node.idle == {3, 4} + + +def test_a_disabled_drive_that_stops_answering_does_not_stop_the_arm(node, monkeypatch): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + states = [] + monkeypatch.setattr(node.state_publisher, 'publish', states.append) + node.bus.drives.pop(1) + node.heard[0] -= 10.0 + for _ in range(node.max_unanswered + 5): + advance(node) + assert node.lost[0] and not node.zeroed[0] + assert node.authorized, node.stop_reason + node.on_command(command(node, joint_2=0.1)) + advance(node) + assert node.authorized and node.bus.drives[2].target is not None + # Every joint is still reported, the disabled one where it was. + published = dict(zip(states[-1].name, states[-1].position)) + assert set(published) == set(node.map.joints) and published['joint_1'] == 0.0 + + +def test_a_disabled_drive_that_never_answered_does_not_keep_the_arm_off(drives_with): + node = without_drive(drives_with, 1) + advance(node) + node.on_description(String(data=URDF)) + # The base drive is not answering, so it cannot be zeroed, and the arm needs it. + assert not node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert not node.authorized + assert node.set_joint_enabled('joint_1', False)[0] + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert node.authorized, node.stop_reason + + +def test_the_zero_service_succeeds_without_a_disabled_drive_and_saves_the_others( + drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + node = without_drive(drives_with, 1, zero_state=str(path)) + advance(node) + assert node.set_joint_enabled('joint_1', False)[0] + response = node.on_zero(Trigger.Request(), Trigger.Response()) + assert response.success and 'base_yaw' in response.message + for _ in range(3): + advance(node) + saved = yaml.safe_load(path.read_text(encoding='utf-8'))['drives'] + assert 'base_yaw' not in saved and len(saved) == len(node.map.drives) - 1 + # A drive that is not disabled still has to answer. + node.set_joint_enabled('joint_1', True) + response = node.on_zero(Trigger.Request(), Trigger.Response()) + assert not response.success and 'base_yaw' in response.message + + +def test_a_drive_that_comes_back_after_its_joint_is_enabled_must_be_zeroed(drives_with): + node = without_drive(drives_with, 1) + advance(node) + assert node.set_joint_enabled('joint_1', False)[0] + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + arm_up(node) + node.on_enabled(Bool(data=False)) + node.command_time -= QUIET_BEFORE_ZERO_S + node.bus.drives[1] = SimulatedServo(1) + assert node.set_joint_enabled('joint_1', True)[0] + # The drive was never set up: the node asks again once its reply timeout has passed. + node.setup_time[0] = -math.inf + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert not node.authorized and not node.zeroed[0] + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + advance(node) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert node.authorized, node.stop_reason + + +def test_a_hand_moved_disabled_joint_does_not_slow_the_other_drives(node, monkeypatch): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.bus.drives[1].axis = 20000.0 + seen = [] + synchronized = node.map.synchronized + + def record(positions, counts, *args): + seen.append(list(counts)) + return synchronized(positions, counts, *args) + monkeypatch.setattr(node.map, 'synchronized', record) + node.on_command(command(node, joint_2=0.1)) + advance(node) + assert seen and seen[-1][0] == node.map.to_counts(node.commanded)[0] + + +def test_a_hand_moved_disabled_joint_is_not_a_following_error(node): + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.on_command(command(node, joint_2=0.1)) + advance(node) + node.on_enabled(Bool(data=False)) + for _ in range(3): + advance(node) + node.bus.drives[1].axis = 5.0 * node.following_error + for _ in range(2 * node.following_ticks): + advance(node) + assert node.behind[0] == 0 and not node.stopping + assert node.stop_reason == 'Teleop disabled' + + +def test_the_drive_rows_of_a_disabled_joint_never_report_an_error(node, monkeypatch): + diagnostics = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', diagnostics.append) + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + node.bus.drives.pop(1) + node.heard[0] -= 10.0 + for _ in range(node.max_unanswered + 5): + advance(node) + node.report() + row = next(item for item in diagnostics[-1].status if item.name == 'drive.base_yaw') + assert row.level == DiagnosticStatus.WARN and 'disabled' in row.message + assert not any(item.level == DiagnosticStatus.ERROR for item in diagnostics[-1].status + if item.name.startswith('drive.')) + + +def test_the_joint_states_are_published_latched_and_on_every_change(node, monkeypatch): + messages = published_joint_control(node, monkeypatch) + assert node.joint_control_publisher.qos_profile.durability == ( + rclpy.qos.DurabilityPolicy.TRANSIENT_LOCAL) + assert node.set_joint_enabled('joint_3', False)[0] + assert len(messages) == 1 + found = rows(messages[-1]) + assert list(found) == ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'tool_grip'] + values, text = found['joint_3'] + assert values['state'] == 'disabled' and values['drives'] == 'elbow' + assert text.startswith('disabled: held at') and math.isfinite(float(values['angle'])) + assert {name: found[name][0]['state'] for name in found if name != 'joint_3'} == { + name: 'enabled' for name in found if name != 'joint_3'} + assert found['joint_4'][0]['drives'] == 'wrist_left,wrist_right' + # A refused change publishes nothing new, and the report repeats the state. + ready(node) + assert not node.set_joint_enabled('joint_1', False)[0] + assert len(messages) == 1 + node.report() + assert len(messages) == 2 and rows(messages[-1])['joint_3'][0]['state'] == 'disabled' + + +def test_a_joint_with_no_drive_is_reported_as_such_and_has_no_service(bench, monkeypatch): + messages = published_joint_control(bench, monkeypatch) + bench.report() + found = rows(messages[-1]) + assert found['joint_2'][0]['state'] == 'no_drive' and found['joint_2'][0]['angle'] == '0.0' + assert found['joint_2'][1].startswith('no drive fitted: locked at') + assert found['tool_grip'][0]['state'] == 'no_drive' + assert found['joint_1'][0]['state'] == 'enabled' + assert sorted(bench.joint_services) == ['joint_1', 'joint_3', 'joint_4', 'joint_5'] + + +def test_the_set_enabled_service_changes_a_joint_and_says_why_it_cannot(node): + request = SetBool.Request(data=False) + response = node.on_set_enabled('joint_3', request, SetBool.Response()) + assert response.success and node.disabled == {'joint_3'} + ready(node) + response = node.on_set_enabled('joint_3', SetBool.Request(data=True), SetBool.Response()) + assert not response.success and 'disable teleop' in response.message + assert node.disabled == {'joint_3'} + + +def test_teleop_drives_an_arm_with_a_disabled_base_without_a_stop( + node, parameters, monkeypatch): + states = [] + monkeypatch.setattr(node.state_publisher, 'publish', states.append) + assert node.set_joint_enabled('joint_1', False)[0] + ready(node) + arm = ArmKinematics.from_urdf(URDF) + teleop = ArmTeleop(config_from_parameters(parameters('xbox_teleop.yaml', 'xbox_teleop')), + joint_limits(URDF, arm.joints), arm) + + def measured(): + return dict(zip(states[-1].name, states[-1].position)) + teleop.set_disabled(node.disabled, measured()) + teleop.enable(measured(), [0.0] * len(AXES)) + assert teleop.enabled, teleop.note + axes = [0.0] * len(AXES) + for axis in ('left_x', 'left_y', 'right_y'): + axes[AXES.index(axis)] = 1.0 + for _ in range(60): + teleop.update(axes, [0] * len(BUTTONS), measured(), node.period) + targets = teleop.command_targets + node.on_enabled(Bool(data=True)) + node.on_command(JointState( + name=list(targets), position=list(targets.values()), + velocity=[teleop.velocities[joint] for joint in targets])) + advance(node) + assert node.authorized, node.stop_reason + assert teleop.blocked == [] + assert node.rejected == 0 and node.bus.drives[1].target is None + assert measured()['joint_1'] == 0.0 and abs(measured()['joint_2']) > 0.1 @pytest.fixture diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index 92a68121..38741677 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -2,12 +2,15 @@ import os import shutil +import socket import subprocess +import threading import time import pytest +import serial -from waybionic_teleop import carrier, mks_can, slcan_bus +from waybionic_teleop import carrier, carrier_relay, mks_can, slcan_bus from waybionic_teleop.slcan_bus import SlcanBus # The carrier's answer to V, which comes before the answers to C, Sn and O. @@ -266,6 +269,27 @@ def slcan_sim(): return path if path and os.access(path, os.X_OK) else None +def check_the_simulated_carrier_answers(bus): + frames = [] + + def wait_for(done, seconds=2.0): + deadline = time.monotonic() + seconds + while not done() and time.monotonic() < deadline: + bus.step(0.0) + frame = bus.receive() + if frame is None: + time.sleep(0.002) + else: + frames.append(frame) + return done() + + assert wait_for(lambda: any(can_id == carrier.STATUS_ID for can_id, _ in frames)) + bus.send(1, mks_can.read_encoder(1)) + assert wait_for(lambda: (1, bytes.fromhex('3100000000000032')) in frames) + assert bus.errors == 0 + bus.shutdown() + + @pytest.mark.skipif(slcan_sim() is None, reason='waybionic_can slcan_sim is not built') def test_the_simulated_carrier_answers_through_the_real_bridge_code(): sim = subprocess.Popen([slcan_sim(), '--ids', '1', '--move-ms', '100'], @@ -273,25 +297,87 @@ def test_the_simulated_carrier_answers_through_the_real_bridge_code(): try: port = sim.stdout.readline().strip() # A pty ignores the baud rate, and macOS refuses a custom rate such as 1000000 on one. - bus = SlcanBus(port, 500000, baudrate=115200) - frames = [] + check_the_simulated_carrier_answers(SlcanBus(port, 500000, baudrate=115200)) + finally: + sim.terminate() + sim.wait() - def wait_for(done, seconds=2.0): - deadline = time.monotonic() + seconds - while not done() and time.monotonic() < deadline: - bus.step(0.0) - frame = bus.receive() - if frame is None: - time.sleep(0.002) - else: - frames.append(frame) - return done() - - assert wait_for(lambda: any(can_id == carrier.STATUS_ID for can_id, _ in frames)) - bus.send(1, mks_can.read_encoder(1)) - assert wait_for(lambda: (1, bytes.fromhex('3100000000000032')) in frames) - assert bus.errors == 0 - bus.shutdown() + +@pytest.mark.skipif(slcan_sim() is None, reason='waybionic_can slcan_sim is not built') +def test_the_simulated_carrier_answers_through_a_carrier_relay(): + # The Windows path: the relay carries the carrier's port over TCP to the drive node. + sim = subprocess.Popen([slcan_sim(), '--ids', '1', '--move-ms', '100'], + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) + stop = threading.Event() + try: + port = sim.stdout.readline().strip() + with socket.create_server(('127.0.0.1', 0)) as probe: + tcp_port = probe.getsockname()[1] + relay = threading.Thread(target=carrier_relay.serve, daemon=True, args=( + lambda: serial.Serial(port, 115200, timeout=carrier_relay.POLL_S), + '127.0.0.1', tcp_port, stop, lambda message: None)) + relay.start() + deadline = time.monotonic() + 3.0 + while True: + try: + bus = SlcanBus(f'socket://127.0.0.1:{tcp_port}', 500000, baudrate=115200) + break + except serial.SerialException: + assert time.monotonic() < deadline, 'the relay never listened' + time.sleep(0.02) + check_the_simulated_carrier_answers(bus) finally: + stop.set() + relay.join(3.0) sim.terminate() sim.wait() + + +@pytest.fixture +def relay_end(): + """Listen as a carrier relay does, yielding (server, url) for a socket:// port.""" + server = socket.create_server(('127.0.0.1', 0)) + server.settimeout(2.0) + yield server, f'socket://127.0.0.1:{server.getsockname()[1]}' + server.close() + + +def test_a_burst_of_frames_through_a_relay_is_read_in_one_pass(relay_end): + # pyserial's socket port reports at most one byte waiting, so a read of what is waiting + # would take a control tick for every byte and leave the replies far behind. + server, url = relay_end + bus = SlcanBus(url, 500000, baudrate=115200) + peer, _ = server.accept() + try: + peer.sendall(VERSION + b'\r\r\r') + for _ in range(200): + bus.receive() + if not bus.syncing: + break + time.sleep(0.001) + assert not bus.syncing + peer.sendall(b't0013F501F7\r' * 100) + time.sleep(0.05) + frames = [] + while (frame := bus.receive()) is not None: + frames.append(frame) + assert frames == [(1, bytes.fromhex('F501F7'))] * 100 + assert bus.errors == 0 + finally: + peer.close() + bus.shutdown() + + +def test_a_relay_that_stops_reading_fails_the_write_instead_of_stalling_the_loop(relay_end): + server, url = relay_end + link = slcan_bus.open_link(url, 115200) + peer, _ = server.accept() + started = time.monotonic() + try: + with pytest.raises(serial.SerialException): + while time.monotonic() - started < 10.0: + link.write(b'x' * 65536) + assert time.monotonic() - started < 2.0 + finally: + peer.close() + link.close() diff --git a/waybionic_teleop/test/test_teleop.py b/waybionic_teleop/test/test_teleop.py index 3ec923e1..7b6f623e 100644 --- a/waybionic_teleop/test/test_teleop.py +++ b/waybionic_teleop/test/test_teleop.py @@ -78,16 +78,93 @@ def test_a_locked_joint_stays_exactly_at_its_angle(params, arm): # Even a measured value a rounding error away is sent back exactly. press(teleop, 'start', {**HOME, 'joint_2': 0.25 + 1e-12}) assert teleop.enabled and teleop.command_targets['joint_2'] == 0.25 - for axes, joint in (({'left_x': -1.0, 'left_y': 1.0}, 'joint_2'), - ({'right_trigger': -1.0}, 'tool_grip')): + for axes in ({'left_x': -1.0, 'left_y': 1.0}, {'right_trigger': -1.0}): teleop.update(*sample(**axes), HOME, DT) - assert joint in teleop.blocked + # A joint that cannot move is not a limit the operator hit, so it is never reported: + # the controller would rumble at every push of a stick that cannot do anything. + assert teleop.blocked == [] assert teleop.command_targets['joint_2'] == 0.25 assert teleop.command_targets['tool_grip'] == 0.0 assert teleop.velocities['joint_2'] == teleop.velocities['tool_grip'] == 0.0 assert teleop.targets['joint_1'] > 0.0 +def test_the_cartesian_and_incision_groups_need_every_joint_of_the_arm(params, arm): + free = ArmTeleop(config_from_parameters(params), LIMITS, arm) + assert [group.name for group in free.groups] == ['base', 'upper', 'cartesian', 'incision'] + # They solve all five joints together, so one that cannot move leaves them nowhere to go. + fixed = ArmTeleop(config_from_parameters(params), LIMITS, arm, locked={'joint_2': 0.0}) + assert [group.name for group in fixed.groups] == ['base', 'upper'] + press(fixed, 'start') + press(fixed, 'y') + press(fixed, 'y') + assert fixed.active_group.name == 'base' + + +def test_a_disabled_joint_holds_the_angle_it_had_at_enable(teleop): + assert teleop.set_disabled({'joint_3'}, HOME) + assert not teleop.set_disabled({'joint_3'}, HOME) + pose = {**HOME, 'joint_3': 0.3} + press(teleop, 'start', pose) + run(teleop, 1.0, left_x=-1.0, right_y=-1.0) + assert teleop.targets['joint_1'] > 0.3 + assert teleop.targets['joint_3'] == teleop.command_targets['joint_3'] == 0.3 + assert teleop.velocities['joint_3'] == 0.0 and teleop.blocked == [] + + +def test_a_disabled_joint_is_not_homed_or_driven_by_the_tool_trigger(teleop): + teleop.set_disabled({'joint_3', 'tool_grip'}, HOME) + pose = {**HOME, 'joint_1': 0.4, 'joint_3': 0.3, 'tool_grip': 0.5} + press(teleop, 'start', pose) + run(teleop, 3.0, 'a', right_trigger=1.0) + assert abs(teleop.targets['joint_1']) < 0.01 + assert teleop.targets['joint_3'] == 0.3 and teleop.targets['tool_grip'] == 0.5 + assert teleop.blocked == [] + + +def test_changing_the_disabled_joints_while_enabled_stops_teleop(teleop): + press(teleop, 'start') + assert not teleop.set_disabled(set(), HOME) + assert teleop.enabled + pose = {**HOME, 'joint_1': 0.2} + assert teleop.set_disabled({'joint_1'}, pose) + assert not teleop.enabled and teleop.targets['joint_1'] == 0.2 + assert 'Joint enable changed' in teleop.note and not teleop.warning + # The next Start holds the joint where it is, and the sticks leave it alone. + press(teleop, 'start', pose) + run(teleop, 1.0, left_x=1.0) + assert teleop.enabled and teleop.targets['joint_1'] == 0.2 + + +def test_groups_follow_the_disabled_joints_and_keep_the_active_group(params, arm): + teleop = ArmTeleop(config_from_parameters(params), LIMITS, arm) + press(teleop, 'start', DOWN) + press(teleop, 'y', DOWN) + assert teleop.active_group.name == 'upper' + teleop.set_disabled({'joint_4'}, DOWN) + assert [group.name for group in teleop.groups] == ['base', 'upper'] + assert teleop.active_group.name == 'upper' + teleop.set_disabled(set(), DOWN) + assert [group.name for group in teleop.groups] == ['base', 'upper', 'cartesian', 'incision'] + assert teleop.active_group.name == 'upper' + # A group with nothing left to move is dropped, and the first one left takes over. + teleop.set_disabled({'joint_2', 'joint_3', 'joint_4', 'joint_5'}, DOWN) + assert [group.name for group in teleop.groups] == ['base'] + assert teleop.active_group.name == 'base' + + +def test_teleop_will_not_enable_with_no_joint_able_to_move(teleop): + teleop.set_disabled(set(LIMITS) | {'tool_grip'}, HOME) + press(teleop, 'start') + assert not teleop.enabled and teleop.warning and 'No joint is enabled' in teleop.note + + +def test_only_joints_of_this_arm_can_be_disabled_and_locked_ones_stay_locked(params): + teleop = ArmTeleop(config_from_parameters(params), LIMITS, locked={'joint_2': 0.0}) + assert not teleop.set_disabled({'joint_2', 'not_a_joint'}, HOME) + assert teleop.disabled == set() + + @pytest.mark.parametrize('axes', [{'left_x': 0.8}, {'right_y': -0.5}, {'right_trigger': -0.6}]) def test_enable_refuses_held_or_stuck_inputs(teleop, axes): teleop.update(*sample('start', **axes), HOME, DT) diff --git a/waybionic_teleop/test/test_xbox_teleop_node.py b/waybionic_teleop/test/test_xbox_teleop_node.py index 61eb8e13..a8b568c0 100644 --- a/waybionic_teleop/test/test_xbox_teleop_node.py +++ b/waybionic_teleop/test/test_xbox_teleop_node.py @@ -4,13 +4,14 @@ from pathlib import Path import time +from diagnostic_msgs.msg import DiagnosticArray import pytest import rclpy from rclpy.parameter import Parameter from sensor_msgs.msg import JointState, Joy from std_msgs.msg import Bool, String -from waybionic_teleop import xbox_teleop_node +from waybionic_teleop import joint_control, xbox_teleop_node from waybionic_teleop.gamepad import AXES, BUTTONS from waybionic_teleop.sim_arm_drives_node import SimArmDrives from waybionic_teleop.xbox_teleop_node import XboxTeleop @@ -281,3 +282,57 @@ def gate_report(): assert node.summary(True).endswith('DISABLED\nPRESS-MENU') finally: drives.destroy_node() + + +def joint_control_report(*disabled): + names = ['joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', 'tool_grip'] + return DiagnosticArray(status=[ + joint_control.joint_status( + joint, joint_control.DISABLED if joint in disabled else joint_control.ENABLED, + [], 0.0, 'disabled' if joint in disabled else 'enabled') + for joint in names]) + + +def test_a_joint_switched_off_while_enabled_holds_the_arm(node, monkeypatch): + enabled, commands = [], [] + monkeypatch.setattr(node.enable_publisher, 'publish', enabled.append) + monkeypatch.setattr(node.command_publisher, 'publish', commands.append) + ready(node) + # A report that changes nothing leaves the arm enabled. + node.on_joint_control(joint_control_report()) + assert node.teleop.enabled + node.measured['joint_3'] = 0.3 + node.on_joint_control(joint_control_report('joint_3')) + assert not node.teleop.enabled and node.teleop.disabled == {'joint_3'} + assert 'Joint enable changed' in node.teleop.note + assert enabled[-1].data is False and not any(commands[-1].velocity) + assert dict(zip(commands[-1].name, commands[-1].position))['joint_3'] == pytest.approx(0.3) + # Start holds it where it is, and its stick does nothing. + tick(node) + tick(node, 'start') + for _ in range(20): + tick(node, right_y=-1.0) + assert node.teleop.enabled and node.teleop.targets['joint_3'] == pytest.approx(0.3) + assert node.teleop.blocked == [] + + +def test_a_joint_reported_off_before_the_description_still_applies(node): + node.on_joint_control(joint_control_report('joint_3')) + assert node.teleop is None + node.load(String(data=URDF)) + assert node.teleop.disabled == {'joint_3'} + # The same report again, as the drive node repeats it, changes nothing. + node.on_joint_control(joint_control_report('joint_3')) + assert node.teleop.disabled == {'joint_3'} + node.on_joint_control(joint_control_report()) + assert node.teleop.disabled == set() + + +def test_the_state_row_names_the_joints_that_are_off(node, monkeypatch): + diagnostics = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', diagnostics.append) + node.load(String(data=URDF)) + node.on_joint_control(joint_control_report('joint_3', 'joint_1')) + node.report() + row = next(item for item in diagnostics[-1].status if item.name == 'teleop.state') + assert row.message.startswith('Joints off: joint_1, joint_3; ') diff --git a/waybionic_teleop/waybionic_teleop/carrier_relay.py b/waybionic_teleop/waybionic_teleop/carrier_relay.py new file mode 100644 index 00000000..e458fb06 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/carrier_relay.py @@ -0,0 +1,221 @@ +""" +Relay the WayBionic carrier's COM port to a local TCP port for the drive node in Docker. + +Docker Desktop cannot open Windows COM ports, but the drive node opens the carrier with +pyserial's serial_for_url, so it accepts socket://host.docker.internal:PORT as its +drive_channel. This passes bytes both ways unchanged, as soon as they arrive. If the carrier +is unplugged or the bridge stops, the connection closes, so the drive node loses the carrier +exactly as it does when the USB cable is pulled on a Mac or Linux. Needs pyserial. Run from +the waybionic_teleop directory: + + python -m waybionic_teleop.carrier_relay + +It looks for the Arduino's COM port each time it opens the carrier, so a carrier plugged in +after it starts, or replugged under another COM number, is found. With several Arduinos plugged +in, name the carrier's: --port COM5. +""" + +import argparse +import socket +import threading + +import serial +from serial.tools import list_ports + +ARDUINO_VID = 0x2341 +DEFAULT_BAUDRATE = 1000000 +DEFAULT_TCP_PORT = 47320 +REOPEN_EVERY_S = 1.0 +# How often blocking calls wake up to check whether to stop. +POLL_S = 0.05 +CHUNK = 4096 + + +def carrier_opener(port, baudrate, open_serial=serial.Serial, list_com_ports=list_ports.comports, + log=print): + """ + Return the open_port that serve() calls whenever it needs the carrier. + + With no port it looks for the only Arduino COM port every time, because the carrier may be + plugged in after the relay starts, still be enumerating, or come back under another COM + number. It never guesses between several Arduinos. + """ + def open_carrier(): + name = port + if name is None: + infos = list_com_ports() + arduinos = sorted(info.device for info in infos if info.vid == ARDUINO_VID) + if not arduinos: + listed = ', '.join(sorted(info.device for info in infos)) or 'none' + raise serial.SerialException( + f'no Arduino COM port found (COM ports: {listed}); plug in the carrier') + if len(arduinos) > 1: + raise serial.SerialException( + f'several Arduino COM ports ({", ".join(arduinos)}); plug in only the ' + 'carrier, or pass --port') + name = arduinos[0] + link = open_serial(name, baudrate, timeout=POLL_S) + log(f'Carrier on {name}') + return link + return open_carrier + + +def relay(link, client, stop): + """ + Pass bytes both ways between the carrier and one TCP client until either side fails. + + Return 'client' if the client disconnected, 'serial' if the carrier was lost, or + 'stopped' once stop is set. Always closes the client; never closes the carrier. + """ + try: + # Send each frame at once instead of waiting to fill a packet. + client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) + except OSError: + pass # Not a TCP socket, as in the tests. + client.settimeout(POLL_S) + done = threading.Event() + lock = threading.Lock() + reasons = [] + + def finish(reason): + with lock: + if not done.is_set(): + reasons.append(reason) + done.set() + + def to_client(): + while not done.is_set(): + try: + data = link.read(link.in_waiting or 1) + except (serial.SerialException, OSError): + finish('serial') + return + if not data: + continue + try: + client.sendall(data) + except OSError: + finish('client') + return + + def to_carrier(): + while not done.is_set(): + try: + data = client.recv(CHUNK) + except socket.timeout: + continue + except OSError: + finish('client') + return + if not data: + finish('client') + return + try: + link.write(data) + except (serial.SerialException, OSError): + finish('serial') + return + + threads = [threading.Thread(target=pump, daemon=True) for pump in (to_client, to_carrier)] + for thread in threads: + thread.start() + try: + while not done.wait(POLL_S): + if stop.is_set(): + finish('stopped') + finally: + done.set() + for thread in threads: + thread.join() + client.close() + return reasons[0] if reasons else 'stopped' + + +def _carrier_alive(link): + """Discard what the carrier sent with nobody connected; return False if it is gone.""" + try: + link.reset_input_buffer() + except (serial.SerialException, OSError): + return False + return True + + +def _close(thing): + if thing is not None: + try: + thing.close() + except (serial.SerialException, OSError): + pass + return None + + +def serve(open_port, bind, tcp_port, stop, log=print): + """ + Relay the carrier to one client at a time until stop is set. + + Listen only while the carrier is open, so the drive node's connection is refused, as an + unplugged port would be, until the carrier is back. + """ + link = server = None + problem = None + try: + while not stop.is_set(): + if link is None: + try: + link = open_port() + except (serial.SerialException, OSError) as error: + if str(error) != problem: + problem = str(error) + log(f'Carrier unavailable, retrying every second: {error}') + stop.wait(REOPEN_EVERY_S) + continue + problem = None + try: + server = socket.create_server((bind, tcp_port)) + except OSError as error: + raise SystemExit( + f'Port {tcp_port} is already in use ({error}).' + 'Another carrier bridge may still be running, close it first.') from None + server.settimeout(POLL_S) + log('Carrier open; waiting for the ground station') + try: + client, address = server.accept() + except socket.timeout: + reason = None if _carrier_alive(link) else 'serial' + else: + log(f'Ground station connected from {address[0]}') + reason = relay(link, client, stop) + if reason == 'serial': + log('Carrier lost; connection closed') + server = _close(server) + link = _close(link) + elif reason == 'client': + log('Ground station disconnected; waiting for it to reconnect') + finally: + _close(server) + _close(link) + + +def main(): + parser = argparse.ArgumentParser(description='Relay the carrier COM port to the arm.') + parser.add_argument('--port', + help='carrier COM port, such as COM5 (default: the only Arduino, ' + 'looked for again whenever the carrier is opened)') + parser.add_argument('--baudrate', type=int, default=DEFAULT_BAUDRATE) + parser.add_argument('--bind', default='127.0.0.1', + help='listen address; keep it local, this drives the arm') + parser.add_argument('--tcp-port', type=int, default=DEFAULT_TCP_PORT) + args = parser.parse_args() + print(f'Relaying the carrier to {args.bind}:{args.tcp_port} (Ctrl+C to stop)') + print(f'Ground station: drive_channel:=socket://host.docker.internal:{args.tcp_port}') + stop = threading.Event() + try: + serve(carrier_opener(args.port, args.baudrate), args.bind, args.tcp_port, stop) + except KeyboardInterrupt: + pass + finally: + stop.set() + + +if __name__ == '__main__': + main() diff --git a/waybionic_teleop/waybionic_teleop/joint_control.py b/waybionic_teleop/waybionic_teleop/joint_control.py new file mode 100644 index 00000000..fc4882b2 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/joint_control.py @@ -0,0 +1,30 @@ +""" +The arm's joint enable states, as the drive node publishes them on ``arm/joint_control``. + +The topic carries a latched DiagnosticArray with one row per joint, ``joint_1`` to +``joint_5`` and then ``tool_grip``. A row's name is the joint, its message says what it is +doing, and its values are ``state`` (one of ENABLED, DISABLED or NO_DRIVE), ``drives`` (the +drives that move it, comma separated) and ``angle`` (radians, where the joint was last seen). +The drive node serves ``arm//set_enabled`` (std_srvs/SetBool) for the joints that have +a drive. The RViz joint control panel and the Xbox teleop node both read this topic. +""" + +from diagnostic_msgs.msg import DiagnosticStatus, KeyValue + +TOPIC = 'arm/joint_control' +ENABLED, DISABLED, NO_DRIVE = 'enabled', 'disabled', 'no_drive' + + +def joint_status(joint, state, drives, angle, message): + """Return the row for one joint.""" + return DiagnosticStatus( + name=joint, level=DiagnosticStatus.OK if state == ENABLED else DiagnosticStatus.WARN, + message=message, values=[KeyValue(key='state', value=state), + KeyValue(key='drives', value=','.join(drives)), + KeyValue(key='angle', value=repr(float(angle)))]) + + +def disabled_joints(message): + """Return the joints a joint control message says are switched off.""" + return {row.name for row in message.status + if any(item.key == 'state' and item.value == DISABLED for item in row.values)} diff --git a/waybionic_teleop/waybionic_teleop/setup_guide.py b/waybionic_teleop/waybionic_teleop/setup_guide.py new file mode 100644 index 00000000..c580c4a6 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/setup_guide.py @@ -0,0 +1,268 @@ +""" +Walk the operator through starting the arm: what to do next, from the /diagnostics rows. + +The drive and teleop nodes already report the carrier, each drive, the controller and the zero +on /diagnostics. This node turns those rows into five steps, in the order the operator does +them: carrier, drives, controller, zero and ready. It publishes them on ``arm/setup`` (a latched +DiagnosticArray of ``setup.`` rows) for the RViz setup panel, and says each change in the +terminal. A row's message is the instruction, and its values are ``title``, ``state`` (OK, +TODO, BLOCKED or WORKING), ``action`` (``zero`` when the panel is to offer the zero button) and +``current`` (true for the first step that is not done). + +It only reads and reports. The zero is the drive node's own ``~/zero`` service. +""" + +from dataclasses import dataclass +import time + +from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue +import rclpy +from rclpy.executors import ExternalShutdownException +from rclpy.node import Node +from rclpy.qos import DurabilityPolicy, QoSProfile + +from waybionic_teleop.ros_shutdown import is_shutdown_error + +TOPIC = 'arm/setup' +OK, TODO, BLOCKED, WORKING = 'ok', 'todo', 'blocked', 'working' +LEVELS = {OK: DiagnosticStatus.OK, WORKING: DiagnosticStatus.OK, TODO: DiagnosticStatus.WARN, + BLOCKED: DiagnosticStatus.ERROR} +# The drive node reports twice a second; a row this old means whoever sent it has gone. +ROW_TIMEOUT_S = 3.0 +PUBLISH_PERIOD_S = 0.5 +# The carrier and the drives need a few seconds to answer after a start, so a problem is only +# reported once it has lasted this long; until then the step is still being checked. +BLOCK_GRACE_S = 5.0 +TITLES = {'carrier': 'Carrier', 'drives': 'Drives', 'controller': 'Controller', + 'zero': 'Zero', 'ready': 'Ready'} +WAITS = 'Waits for the steps above' + + +@dataclass +class Step: + """One thing the operator has to get right, and what to do about it.""" + + name: str + state: str + message: str + action: str = '' + + @property + def title(self): + return TITLES[self.name] + + +def value(row, key='value'): + """Return one of a row's values, or '' if it has none.""" + if row is None: + return '' + return next((item.value for item in row.values if item.key == key), '') + + +def carrier_step(rows): + if 'arm.command_gate' not in rows: + return Step('carrier', WORKING, 'Waiting for the ground station to start...') + carrier = rows.get('can.carrier') + if carrier is None: + interface = value(rows.get('can.bus'), 'interface') + if interface == 'sim': + return Step('carrier', OK, 'Simulated drives, no hardware') + return Step('carrier', OK, f'Using the {interface or "CAN"} adapter') + state = value(carrier) + if state == 'unplugged': + return Step('carrier', TODO, "Plug the carrier's USB-C cable into this computer") + if state == 'silent': + return Step('carrier', BLOCKED, + 'The carrier is plugged in but silent: replug it, or flash its firmware ' + '(./scripts/macos.sh flash)') + if state == 'pressed': + return Step('carrier', BLOCKED, 'The E-stop is pressed: release it') + return Step('carrier', OK, 'Carrier connected') + + +def fault(name, row): + """Say why a drive's row is an error: its health check, or else its move status.""" + # The drive node raises the row's level for a failed health check, but its message only has + # the move status, such as "run complete", so the reason is in the row's state value. + health = value(row, 'state') + if health and health != 'OK': + text = health.lower().replace('_', ' ') + if health in ('FOLLOWING_ERROR', 'STALLED'): + try: + error = abs(float(value(row, 'target_encoder_error_deg'))) + text += f': {error:.1f} deg off its target' + except ValueError: + pass + return f'{name} ({text})' + return f'{name} ({row.message.split(": ", 1)[-1]})' + + +def drives_step(rows): + drives = {name[len('drive.'):]: row for name, row in rows.items() + if name.startswith('drive.')} + if not drives: + return Step('drives', WORKING, 'Waiting for the drives...') + off = [name for name, row in drives.items() if 'disabled (' in row.message] + on = {name: row for name, row in drives.items() if name not in off} + missing = [f'{name} (CAN {value(row, "can_id")})' for name, row in on.items() + if 'no reply' in row.message] + if missing: + return Step('drives', BLOCKED, + f'No answer from {", ".join(missing)}: check its power and CAN wiring, or ' + 'switch its joint off in Joint control') + failed = [fault(name, row) for name, row in on.items() + if row.level == DiagnosticStatus.ERROR] + if failed: + return Step('drives', BLOCKED, f'Drive fault: {", ".join(failed)}') + if any('unconfirmed' in row.message for row in on.values()): + return Step('drives', WORKING, 'Setting up the drives...') + message = f'{len(on)} drives answer' + if off: + message += f', {len(off)} switched off' + return Step('drives', OK, message) + + +def controller_step(rows): + row = rows.get('teleop.input') + if row is None: + return Step('controller', WORKING, 'Waiting for teleop to start...') + if row.level == DiagnosticStatus.OK: + return Step('controller', OK, 'Controller connected') + return Step('controller', TODO, + 'Connect an Xbox controller (USB or Bluetooth) and press any button') + + +def zero_step(rows): + zero = rows.get('arm.zero') + if zero is not None: + if value(zero) == 'checking': + return Step('zero', WORKING, 'Checking whether the drives kept their saved zero...') + return Step('zero', TODO, + 'Put the arm in its zero pose (upright, as RViz shows it), then press Zero', + action='zero') + if any(name.startswith('arm.') and name not in ('arm.zero', 'arm.command_gate') + for name in rows): + return Step('zero', OK, 'Zeroed') + return Step('zero', WORKING, 'Reading the drives...') + + +def ready_step(rows): + state = rows.get('teleop.state') + if state is None: + return Step('ready', WORKING, 'Waiting for teleop to start...') + if state.level == DiagnosticStatus.ERROR: + return Step('ready', BLOCKED, state.message) + if value(state) == 'enabled': + return Step('ready', OK, 'Teleop is on: the sticks move the arm, B stops it') + message = 'Press Start (the Menu button) on the controller' + if state.level == DiagnosticStatus.WARN and state.message: + message = state.message + return Step('ready', TODO, message) + + +def evaluate(rows): + """ + Return the five steps for the fresh /diagnostics rows, {name: DiagnosticStatus}. + + The controller can be plugged in at any time. The others need what comes before them: the + drives are on the carrier's bus, and the zero and the Start press need drives that answer. + """ + carrier = carrier_step(rows) + drives = drives_step(rows) if carrier.state == OK else Step('drives', TODO, WAITS) + controller = controller_step(rows) + zero = zero_step(rows) if drives.state == OK else Step('zero', TODO, WAITS) + before = (carrier, drives, controller, zero) + ready = (ready_step(rows) if all(step.state == OK for step in before) + else Step('ready', TODO, WAITS)) + return [*before, ready] + + +def current(steps): + """Return the first step that is not done, or None once the arm is ready.""" + return next((step for step in steps if step.state != OK), None) + + +class SetupGuide(Node): + """Publish the start-up steps as the other nodes' rows change.""" + + def __init__(self, **kwargs): + super().__init__('setup_guide', automatically_declare_parameters_from_overrides=True, + **kwargs) + topic = (self.get_parameter('diagnostics_topic').value + if self.has_parameter('diagnostics_topic') else '/diagnostics') + self.rows = {} + self.blocked_since = {} + self.announced = None + latched = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) + self.publisher = self.create_publisher(DiagnosticArray, TOPIC, latched) + self.create_subscription(DiagnosticArray, topic, self.on_diagnostics, 10) + self.create_timer(PUBLISH_PERIOD_S, self.publish_steps) + + def on_diagnostics(self, message): + now = time.monotonic() + names = {row.name for row in message.status} + positions = [name for name in names + if name.startswith('arm.') and name not in ('arm.zero', 'arm.command_gate')] + # The drive node reports arm.zero or the joints' positions, never both, so one appearing + # ends the other, though its last row would count as fresh for a few seconds more. + if 'arm.zero' in names: + for name in [name for name in self.rows if name.startswith('arm.') + and name not in ('arm.zero', 'arm.command_gate')]: + del self.rows[name] + elif positions: + self.rows.pop('arm.zero', None) + for row in message.status: + self.rows[row.name] = (row, now) + + def fresh_rows(self): + now = time.monotonic() + return {name: row for name, (row, seen) in self.rows.items() + if now - seen <= ROW_TIMEOUT_S} + + def announce(self, text): + self.get_logger().info(text) + + def publish_steps(self): + now = time.monotonic() + steps = evaluate(self.fresh_rows()) + for step in steps: + if step.state != BLOCKED: + self.blocked_since.pop(step.name, None) + elif now - self.blocked_since.setdefault(step.name, now) < BLOCK_GRACE_S: + step.state, step.message = WORKING, f'Checking the {step.title.lower()}...' + first = current(steps) + statuses = [] + for step in steps: + statuses.append(DiagnosticStatus( + name=f'setup.{step.name}', level=LEVELS[step.state], message=step.message, + values=[KeyValue(key='title', value=step.title), + KeyValue(key='state', value=step.state), + KeyValue(key='action', value=step.action), + KeyValue(key='current', value=str(step is first).lower())])) + message = DiagnosticArray(status=statuses) + message.header.stamp = self.get_clock().now().to_msg() + self.publisher.publish(message) + summary = (first.name, first.state, first.message) if first else None + if summary != self.announced: + self.announced = summary + self.announce(f'Setup: {first.title} - {first.message}' if first + else 'Setup: ready, the arm can be operated') + + +def main(): + rclpy.init() + node = SetupGuide() + try: + rclpy.spin(node) + except (KeyboardInterrupt, ExternalShutdownException): + pass + except RuntimeError as error: + if not is_shutdown_error(error): + raise + finally: + node.destroy_node() + rclpy.try_shutdown() + + +if __name__ == '__main__': + main() diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index 0efe5d71..0865c1f4 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -17,6 +17,12 @@ has fitted; each joint no fitted drive moves is published at its locked angle, and a command must leave it there. +A joint can be switched off while the arm is stopped (``arm//set_enabled``, see +waybionic_teleop/joint_control.py), for a drive that is faulty or not fitted yet. It is held +where it was and teleop must leave it there. A drive whose joints are all off gets no targets, +and its silence or its turns do not stop the arm; it is read for the joints' angles while it +answers. One wrist joint off still needs both wrist drives, which then hold it. + Joint commands are accepted only after a valid robot_description and a fresh teleop enable that teleop keeps republishing. Whoever publishes ``/joint_commands`` must keep publishing while the arm is meant to move: once ``command_timeout_s`` passes with no command, every @@ -35,6 +41,7 @@ """ import datetime +import functools import math import os import time @@ -47,14 +54,14 @@ from rclpy.qos import DurabilityPolicy, QoSProfile from sensor_msgs.msg import JointState from std_msgs.msg import Bool, String -from std_srvs.srv import Trigger +from std_srvs.srv import SetBool, Trigger from waybionic_control.drive_health import ( DriveHealthMonitor, DriveHealthState, DriveHealthThresholds, ) -from waybionic_teleop import carrier, mks_can +from waybionic_teleop import carrier, joint_control, mks_can from waybionic_teleop.arm_profile import fit_drive_parameters, load_profile from waybionic_teleop.drive_map import drive_map_from_parameters from waybionic_teleop.frame_log import RecordingBus @@ -78,6 +85,8 @@ RUN_FAULTS = (0, 3) # Teleop sends a locked joint's angle back unchanged; anything beyond rounding is a move. LOCKED_TOLERANCE_RAD = 1e-6 +# A disabled joint is held where teleop saw it, give or take the counts between two readings. +DISABLED_TOLERANCE_RAD = 0.01 # A drive stopped mid-move starts again once an encoder reading this long after its stop no # longer advances the old way, or once it reports the stop complete and barely moves. Bench # reversals on firmware V1.0.9 settled in 17 ms (median) and 42 ms at most at 120 Hz. @@ -158,6 +167,11 @@ def __init__(self, **kwargs): raise ValueError('at least one drive joint needs a URDF limit') drives = self.map.drives self.index = {drive.can_id: index for index, drive in enumerate(drives)} + # Joints switched off at run time, where each was held when the arm was last enabled, + # and where each was last seen, for the drives that no longer tell. + self.disabled, self.anchors, self.last_angle = set(), {}, {} + self.drive_joints = [{joint for joint, factor in drive.factors.items() if factor} + for drive in drives] if self.interface == 'sim': self.bus = SimulatedBus([SimulatedServo(drive.can_id) for drive in drives], self.bitrate) @@ -251,6 +265,12 @@ def __init__(self, **kwargs): self.create_subscription(Bool, 'teleop_enabled', self.on_enabled, latched) self.create_subscription(JointState, 'joint_commands', self.on_command, 10) self.create_service(Trigger, '~/zero', self.on_zero) + self.joint_control_publisher = self.create_publisher( + DiagnosticArray, joint_control.TOPIC, latched) + self.joint_services = { + joint: self.create_service(SetBool, f'arm/{joint}/set_enabled', + functools.partial(self.on_set_enabled, joint)) + for joint in self.map.joints} self.state_publisher = self.create_publisher(JointState, 'joint_states', 10) self.diagnostics_publisher = self.create_publisher(DiagnosticArray, topic, 10) self.last_tick = time.monotonic() @@ -258,6 +278,7 @@ def __init__(self, **kwargs): self.report_errors = self.report_refused = 0 self.create_timer(self.period, self.tick) self.create_timer(REPORT_PERIOD_S, self.report) + self.publish_joint_control() drive_list = ', '.join(f'{drive.name}=CAN {drive.can_id}' for drive in drives) if self.interface == 'sim': self.get_logger().info(f'Simulated drives: {drive_list} (no hardware)') @@ -308,13 +329,20 @@ def on_zero(self, request, response): return response self.zero() deadline = time.monotonic() + REPLY_TIMEOUT_S - while not all(self.zeroed) and time.monotonic() < deadline: + idle = self.idle + while (not all(self.zeroed[index] for index in self.active(idle)) + and time.monotonic() < deadline): time.sleep(0.005) self.drain(time.monotonic(), zeroing=True) - missing = [drive.name for drive, done in zip(self.map.drives, self.zeroed) if not done] + missing = [drive.name for index, drive in enumerate(self.map.drives) + if not self.zeroed[index] and index not in idle] + skipped = [drive.name for index, drive in enumerate(self.map.drives) + if not self.zeroed[index] and index in idle] response.success = not missing - response.message = ('Zeroed every drive' if response.success - else 'No zero reply from ' + ', '.join(missing)) + response.message = ('No zero reply from ' + ', '.join(missing) if missing + else 'Zeroed every drive but ' + ', '.join(skipped) + + ' (its joints are disabled)' if skipped + else 'Zeroed every drive') self.get_logger().info(response.message) return response @@ -363,7 +391,8 @@ def finish_check(self, index): self.get_logger().warning(f'{name} does not report its zero, so it is not saved') return self.zero_offsets[index] = offset - if len(self.zero_offsets) == len(self.map.drives): + # A drive with its joints off may never answer; it is saved if it did. + if all(other in self.zero_offsets for other in self.active()): self.save_zero() return saved = self.saved_zero[index] @@ -400,7 +429,7 @@ def load_zero(self): def save_zero(self): drives = {drive.name: {'can_id': drive.can_id, 'offset': self.zero_offsets[index]} - for index, drive in enumerate(self.map.drives)} + for index, drive in enumerate(self.map.drives) if index in self.zero_offsets} saved = {'saved': datetime.datetime.now().isoformat(timespec='seconds'), 'drives': drives} partial = self.zero_state + '.partial' @@ -439,19 +468,60 @@ def on_description(self, message): return self.description_valid = True + @property + def idle(self): + """Return the indices of the drives whose joints are all disabled: nothing moves them.""" + return {index for index, joints in enumerate(self.drive_joints) + if joints <= self.disabled} + + def active(self, idle=None): + """Return the indices of the drives that the arm needs.""" + idle = self.idle if idle is None else idle + return [index for index in range(len(self.map.drives)) if index not in idle] + + def trusted(self, index, now): + """Return whether a drive has answered lately and holds the zero.""" + heard = self.heard[index] + return (self.counts[index] is not None and self.zeroed[index] and not self.lost[index] + and heard is not None and now - heard <= REPLY_TIMEOUT_S) + + def full_counts(self, now=None): + """ + Return one encoder count per drive, or None while a drive the arm needs has none. + + A drive whose joints are all off may be missing, faulty or unzeroed: it counts as + wherever its joints were last seen, so the others neither wait for it nor tell it apart. + """ + now = time.monotonic() if now is None else now + idle = self.idle + counts = [] + for index, count in enumerate(self.counts): + if index in idle and not self.trusted(index, now): + angles = {joint: self.last_angle.get(joint, 0.0) for joint in self.map.joints} + count = self.map.to_counts(angles)[index] + elif count is None: + return None + counts.append(count) + return counts + def feedback_fresh(self, now): - return all(heard is not None and now - heard <= REPLY_TIMEOUT_S for heard in self.heard) + return all(self.heard[index] is not None and now - self.heard[index] <= REPLY_TIMEOUT_S + for index in self.active()) def on_enabled(self, message): now = time.monotonic() + counts = self.full_counts(now) if not message.data: self.disarm('Teleop disabled') self.awaiting_release = False - elif (not self.awaiting_release and self.description_valid and all(self.zeroed) - and not any(self.unconfirmed) and not self.stopping and None not in self.counts + elif (not self.awaiting_release and self.description_valid + and all(self.zeroed[index] for index in self.active()) + and not any(self.unconfirmed[index] for index in self.active()) + and not self.stopping and counts is not None and self.feedback_fresh(now) and not self.estop_pressed): if not self.authorized: - self.commanded = self.map.to_positions(self.counts) + self.commanded = self.map.to_positions(counts) + self.anchors = {joint: self.commanded[joint] for joint in self.disabled} self.authorized = True self.enabled_at = now self.stop_reason = '' @@ -492,8 +562,20 @@ def on_command(self, message): self.reject_command(f'{joint} is locked at {angle:g} rad') return del velocities[joint] - measured = self.map.to_positions(self.counts) + for joint in self.disabled: + if abs(positions[joint] - self.anchors[joint]) > DISABLED_TOLERANCE_RAD: + self.reject_command(f'{joint} is disabled') + return + # Teleop's reading may differ by a count or two; the drives get exactly the anchor. + positions[joint], velocities[joint] = self.anchors[joint], 0.0 + counts = self.full_counts() + if counts is None: + self.reject_command('Waiting for drive feedback') + return + measured = self.map.to_positions(counts) for joint, (lower, upper) in self.limits.items(): + if joint in self.disabled: + continue position, actual = positions[joint], measured[joint] # An already-outside encoder may move toward the URDF range, never farther out. if ((position < lower and (actual >= lower or position < actual)) @@ -562,9 +644,12 @@ def tick(self): self.unanswered[index] += 1 self.drain(now) self.check_following() - if not all(self.zeroed) or None in self.counts: + counts = self.full_counts(now) + if not all(self.zeroed[index] for index in self.active()) or counts is None: return - positions = self.map.to_positions(self.counts) + positions = self.map.to_positions(counts) + for joint in self.disabled: + self.last_angle[joint] = positions[joint] if self.commanded is None: # Hold the actual encoder pose while disarmed, including after a host pause. self.commanded = dict(positions) @@ -589,11 +674,21 @@ def lose(self, index, reason): name = self.map.drives[index].name self.lost[index], self.zeroed[index] = True, False self.checks.pop(index, None) + if index in self.idle: + # Nothing is moving because of it, so the arm carries on without it. + self.get_logger().warning(f'{name} {reason}; its joints are disabled, so the arm ' + 'carries on') + return self.stop_all(f'{name} {reason}') self.get_logger().error(f'{name} {reason}; every drive is stopped') def check_following(self): + idle = self.idle for index, (sent, count) in enumerate(zip(self.sent, self.counts)): + if index in idle: + # Its joints are off, so a hand that moved it is no fault. + self.behind[index] = 0 + continue # A stopped drive must stay where it stopped, armed or not, as its firmware can # run on to a kept target after any stop. target = None @@ -631,7 +726,9 @@ def fault(self, index, reason): def stop_drives(self): """Stop every drive with the manual's F5 zero-speed, zero-acceleration frame.""" self.velocities.clear() - self.stopping.update(index for index, sent in enumerate(self.sent) if sent != (None, 0)) + idle = self.idle + self.stopping.update(index for index, sent in enumerate(self.sent) + if sent != (None, 0) and index not in idle) self.send_stops() def send_stops(self): @@ -652,8 +749,16 @@ def send_stops(self): self.start_hold(index, now) def send_targets(self): + idle = self.idle + counts = self.full_counts() + if counts is None: + self.reject_command('Waiting for drive feedback') + return + # A drive with its joints off is never moved, so it must not set the others' speed. + wanted = self.map.to_counts(self.commanded) + counts = [wanted[index] if index in idle else count for index, count in enumerate(counts)] try: - moves = self.map.synchronized(self.commanded, self.counts, self.period, self.max_rpm, + moves = self.map.synchronized(self.commanded, counts, self.period, self.max_rpm, self.velocities) motor_rates = self.map.shaft_rpm(self.velocities) commands = [] @@ -667,6 +772,8 @@ def send_targets(self): return for index, (drive, (axis, speed), rpm, data) in enumerate( zip(self.map.drives, moves, motor_rates, commands)): + if index in idle: + continue ahead, direction = axis - self.counts[index], self.direction[index] if (rpm == 0.0 or self.settling[index] is not None or (direction and ahead * direction < 0)): @@ -857,7 +964,7 @@ def on_reply(self, can_id, data, now): if index in self.checks: self.finish_check(index) # Only stops and holds go out while disarmed, and a released motor refuses those too. - if failed and self.authorized: + if failed and self.authorized and index not in self.idle: self.fault(index, failed) def report(self): @@ -884,14 +991,16 @@ def report(self): statuses.append(status('arm.command_gate', gate_level, 'enabled' if self.authorized else 'stopped', '', self.stop_reason or 'Receiving validated teleop setpoints')) - if not all(self.zeroed): + idle = self.idle + counts = self.full_counts(now) + if not all(self.zeroed[index] for index in self.active(idle)): restoring = any(check['purpose'] == 'restore' for check in self.checks.values()) statuses.append(status( 'arm.zero', DiagnosticStatus.WARN, 'checking' if restoring else 'no', '', 'Checking whether the drives kept their saved zero' if restoring else f'Not zeroed. {self.zero_hint()}')) - elif None not in self.counts: - positions = self.map.to_positions(self.counts) + elif counts is not None: + positions = self.map.to_positions(counts) commanded = self.commanded or {} for joint, position in positions.items(): target = math.degrees(commanded.get(joint, position)) @@ -954,6 +1063,10 @@ def report(self): level = DiagnosticStatus.STALE elif health_state is not DriveHealthState.OK: level = DiagnosticStatus.ERROR + if index in idle: + # Its joints are off: whatever it does is not the arm's fault. + level = min(level, DiagnosticStatus.WARN) + text = f'disabled ({text})' statuses.append(status( f'drive.{drive.name}', level, turns, 'rev', f'CAN ID {drive.can_id}: {text}' @@ -963,6 +1076,66 @@ def report(self): message = DiagnosticArray(status=statuses) message.header.stamp = self.get_clock().now().to_msg() self.diagnostics_publisher.publish(message) + self.publish_joint_control() + + def set_joint_enabled(self, joint, enabled): + """ + Switch one joint on or off while the arm is stopped; return (done, what happened). + + Like zeroing, this waits until teleop has stopped streaming. A joint that is switched + on again needs its drive answering and zeroed before the arm can be enabled. + """ + if joint not in self.map.joints: + return False, f'{joint} has no drive on this arm' + if self.authorized or time.monotonic() - self.command_time < QUIET_BEFORE_ZERO_S: + return False, 'Joint commands are still arriving; disable teleop (Start) first' + word = 'enabled' if enabled else 'disabled' + if enabled != (joint in self.disabled): + return True, f'{joint} is already {word}' + if enabled: + self.disabled.discard(joint) + else: + counts = self.full_counts() + if counts is not None: + self.last_angle[joint] = self.map.to_positions(counts)[joint] + self.disabled.add(joint) + # A hold from before the switch must not move a drive that was left alone meanwhile, + # and a stop that a missing drive never took is no longer anyone's concern. + for index, joints in enumerate(self.drive_joints): + if joint in joints: + self.held[index], self.hold_until[index] = None, -math.inf + self.stopping.difference_update(self.idle) + self.get_logger().info(f'{joint} is {word}') + self.publish_joint_control() + return True, f'{joint} is {word}' + + def on_set_enabled(self, joint, request, response): + response.success, response.message = self.set_joint_enabled(joint, request.data) + return response + + def publish_joint_control(self): + counts = self.full_counts() + positions = self.map.to_positions(counts) if counts is not None else {} + statuses = [] + for joint in sorted({*self.map.joints, *self.locked}): + if joint in self.locked: + angle = self.locked[joint] + state, drives = joint_control.NO_DRIVE, [] + text = f'no drive fitted: locked at {math.degrees(angle):+.1f} deg' + else: + drives = [drive.name for drive, joints in zip(self.map.drives, self.drive_joints) + if joint in joints] + if joint in self.disabled: + angle = self.last_angle.get(joint, positions.get(joint, 0.0)) + state = joint_control.DISABLED + text = f'disabled: held at {math.degrees(angle):+.1f} deg' + else: + angle = positions.get(joint, self.last_angle.get(joint, 0.0)) + state, text = joint_control.ENABLED, 'enabled' + statuses.append(joint_control.joint_status(joint, state, drives, angle, text)) + message = DiagnosticArray(status=statuses) + message.header.stamp = self.get_clock().now().to_msg() + self.joint_control_publisher.publish(message) def on_test_fault_parameter(self, parameters): """Apply a simulator-only ``drive_name:fault`` parameter or clear with ``none``.""" diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 04d2abcc..554c34bb 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -50,6 +50,22 @@ ANSWER_TIMEOUT_S = 0.5 BELL = 0x07 CR = 0x0D +# One read takes whatever has arrived, up to this much. A socket:// port, which is how a carrier +# relay presents the carrier, only ever reports one byte waiting, so asking for that many would +# take a read, and a control tick, for every byte. +READ_CHUNK = 4096 + + +def open_link(port, baudrate): + """Open the carrier's serial port, or a relay's socket:// URL, so no read or write blocks.""" + link = serial.serial_for_url(port, baudrate=baudrate, timeout=0, + write_timeout=WRITE_TIMEOUT_S) + # A socket:// port ignores write_timeout and would hold the control loop for five seconds + # while the relay is not reading. + relay = getattr(link, '_socket', None) + if relay is not None: + relay.settimeout(WRITE_TIMEOUT_S) + return link def parse_line(line): @@ -74,9 +90,7 @@ def __init__(self, port, bitrate, baudrate=DEFAULT_BAUDRATE, open_port=None): if bitrate not in BITRATE_CODES: raise ValueError(f'the carrier runs CAN at {sorted(BITRATE_CODES)} bit/s') self.port, self.bitrate = port, bitrate - self.open_port = open_port or ( - lambda: serial.serial_for_url(port, baudrate=baudrate, timeout=0, - write_timeout=WRITE_TIMEOUT_S)) + self.open_port = open_port or (lambda: open_link(port, baudrate)) self.frames = self.bits = self.errors = self.refused = self.reopens = 0 self.problem = '' self.outgoing, self.incoming, self.replies = bytearray(), bytearray(), deque() @@ -208,7 +222,7 @@ def _read(self): if self.serial is None: return try: - chunk = self.serial.read(self.serial.in_waiting or 1) + chunk = self.serial.read(READ_CHUNK) except (serial.SerialException, OSError) as error: self._lost(error) return diff --git a/waybionic_teleop/waybionic_teleop/teleop.py b/waybionic_teleop/waybionic_teleop/teleop.py index 7a997bc7..f9847984 100644 --- a/waybionic_teleop/waybionic_teleop/teleop.py +++ b/waybionic_teleop/waybionic_teleop/teleop.py @@ -16,6 +16,8 @@ INCISION_LOST = ('The tool is off the incision point; press Y, withdraw it in another group, ' 'then choose the incision group again') INCISION_HELD = 'The tool is inserted; withdraw it to the incision point before pressing Y' +INCISION_JOINT_OFF = ('A joint is switched off with the tool through the incision point; switch ' + 'it back on in Joint control to withdraw the tool') def clamp(value, low, high): @@ -146,11 +148,11 @@ def __init__(self, config, limits, kinematics=None, collision=None, locked=None) self.kinematics = kinematics self.collision = collision # Without kinematics for this arm, the Cartesian and incision groups are left out. - self.groups = [group for group in config.groups - if group.mode not in MOVES or kinematics is not None] - if not self.groups: + self.configured_groups = [group for group in config.groups + if group.mode not in MOVES or kinematics is not None] + if not self.configured_groups: raise ValueError('no joint-space group or compatible Cartesian kinematics') - for group in self.groups: + for group in self.configured_groups: if group.mode in MOVES and ( tuple(group.joints) != kinematics.joints or any(joint not in limits for joint in kinematics.joints)): @@ -162,6 +164,10 @@ def __init__(self, config, limits, kinematics=None, collision=None, locked=None) if joint in self.limits} for joint, angle in self.locked.items(): self.limits[joint] = (angle, angle) + # Joints the operator switched off: each holds the angle it had when teleop was enabled. + self.disabled = set() + self.disabled_angles = {} + self.groups = self.usable_groups() self.enabled = False self.group = 0 self.level = config.speed_level @@ -188,6 +194,60 @@ def __init__(self, config, limits, kinematics=None, collision=None, locked=None) def active_group(self): return self.groups[self.group] + def movable(self, joint): + """Return whether the sticks can move this joint: it is neither locked nor disabled.""" + return joint not in self.locked and joint not in self.disabled + + def group_usable(self, group): + """Return whether a group has something to move: a Cartesian solve needs every joint.""" + if group.mode in MOVES: + return all(self.movable(joint) for joint in group.joints) + return any(self.movable(joint) for joint in group.joints) + + def usable_groups(self, keep=None): + """Return the groups with something to move, and keep, which is not left for one.""" + return [group for group in self.configured_groups + if group is keep or self.group_usable(group)] or [self.configured_groups[0]] + + def inserted(self): + """Return whether the tool is through the incision point, which groups may not leave.""" + if self.active_group.mode != 'incision' or self.incision is None or not self.targets: + return False + miss, depth = self.incision_offset(self.targets) + return miss <= INCISION_TOLERANCE and depth > INSERTED + + def set_disabled(self, joints, measured): + """ + Switch off exactly these joints; return True if that changed anything. + + A disabled joint never moves, so the arm can run without a joint whose drive is faulty + or missing. While enabled, teleop stops where the arm is: the next Start enables the + remaining joints from the measured pose. + """ + joints = {joint for joint in joints if joint in self.limits and joint not in self.locked} + if joints == self.disabled: + return False + if self.enabled: + self.disable(measured, 'Joint enable changed; press Start (Xbox Menu button) to ' + 'enable') + previous = self.active_group + # The other groups, and going home, could drag the tool sideways in the incision, which + # Y and A are refused for, so a tool that is through it stays in its group, unable to move + # until the joint is switched back on. + keep = previous if self.inserted() else None + self.disabled = joints + self.disabled_angles = {joint: angle for joint, angle in self.disabled_angles.items() + if joint in joints} + self.groups = self.usable_groups(keep) + self.group = next((index for index, group in enumerate(self.groups) + if group.name == previous.name), 0) + if self.active_group is not previous and previous.mode == 'incision' and ( + self.incision is not None): + self.withdrawn = self.incision_offset(self.targets)[1] <= INSERTED + if keep is not None and not self.group_usable(keep): + self.note, self.warning = INCISION_JOINT_OFF, True + return True + @property def speed(self): return self.config.max_speed * self.config.speed_levels[self.level] @@ -228,12 +288,11 @@ def update(self, axes, buttons, measured, dt): def change_group(self): """Select the next group, unless the tool is inserted through the incision point.""" if self.active_group.mode == 'incision' and self.incision is not None: - miss, depth = self.incision_offset(self.targets) - if miss <= INCISION_TOLERANCE and depth > INSERTED: + if self.inserted(): # The other groups, and going home, could drag the tool sideways in the incision. self.note, self.warning = INCISION_HELD, True return - self.withdrawn = depth <= INSERTED + self.withdrawn = self.incision_offset(self.targets)[1] <= INSERTED self.group = (self.group + 1) % len(self.groups) self.stop_cartesian() self.velocities = dict.fromkeys(self.limits, 0.0) @@ -261,6 +320,13 @@ def enable(self, measured, axes): if missing: self.note, self.warning = 'Waiting for joint states: ' + ', '.join(missing), True return + if not any(self.movable(joint) for joint in self.limits): + self.note = 'No joint is enabled; switch one on in the Joint control panel' + self.warning = True + return + if not self.group_usable(self.active_group): + self.note, self.warning = INCISION_JOINT_OFF, True + return if self.motion_input_held(axes): # A stuck or held input must never start moving the arm the moment it is enabled. self.note = 'Center the sticks and release the triggers and buttons, then press Start' @@ -268,6 +334,7 @@ def enable(self, measured, axes): return # Start from the measured pose so enabling never makes the arm jump. self.targets = {joint: measured[joint] for joint in self.limits} + self.disabled_angles = {joint: measured[joint] for joint in self.disabled} self.command_targets = dict(self.targets) self.velocities = dict.fromkeys(self.limits, 0.0) self.pin_locked() @@ -289,7 +356,7 @@ def disable(self, measured, note, warning=False): def pin_locked(self): # A solve may leave a locked joint a rounding error off its angle; send it unchanged. - for joint, angle in self.locked.items(): + for joint, angle in {**self.disabled_angles, **self.locked}.items(): self.targets[joint] = self.command_targets[joint] = angle self.velocities[joint] = 0.0 @@ -307,7 +374,7 @@ def move(self, axes, homing, dt): if homing and not incision: self.stop_cartesian() for joint, (lower, upper) in self.limits.items(): - if joint != config.tool_joint: + if joint != config.tool_joint and self.movable(joint): error = clamp(0.0, lower, upper) - self.targets[joint] desired[joint] = clamp(config.home_gain * error, -self.speed, self.speed) elif self.active_group.mode == 'cartesian': @@ -319,9 +386,14 @@ def move(self, axes, homing, dt): else: group = self.active_group for joint, axis, scale in zip(group.joints, group.axes, group.scales): - desired[joint] += scale * self.stick(axes, axis) * self.speed - desired[config.tool_joint] = config.tool_speed * ( - self.trigger(axes, config.tool_close_axis) - self.trigger(axes, config.tool_open_axis)) + # A joint that cannot move is not a limit to hit, so its stick does nothing. + if self.movable(joint): + desired[joint] += scale * self.stick(axes, axis) * self.speed + desired[config.tool_joint] = 0.0 + if self.movable(config.tool_joint): + desired[config.tool_joint] = config.tool_speed * ( + self.trigger(axes, config.tool_close_axis) + - self.trigger(axes, config.tool_open_axis)) step = config.max_accel * dt for joint, goal in desired.items(): velocity = self.velocities[joint] diff --git a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py index 9a5cc3d4..afb1b429 100644 --- a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py +++ b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py @@ -2,7 +2,8 @@ Drive the arm from an Xbox controller: /joy in, /joint_commands out. Mapping and limits come from config/xbox_teleop.yaml and the robot_description joint limits; -a joint the arm profile (``arm_profile``) locks stays at its angle. The logic lives in +a joint the arm profile (``arm_profile``) locks stays at its angle, and so does one the drive +node reports switched off on ``arm/joint_control``. The logic lives in :mod:`waybionic_teleop.teleop`. The node also reports its state on /diagnostics and draws a placeholder end effector and a status label in RViz. """ @@ -19,6 +20,7 @@ from std_msgs.msg import Bool, String from visualization_msgs.msg import Marker, MarkerArray +from waybionic_teleop import joint_control from waybionic_teleop.arm_profile import load_profile from waybionic_teleop.collision import ArmCollision from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS @@ -70,6 +72,8 @@ def __init__(self, **kwargs): self.table_height = float(params.get('table_height', 0.0)) self.clearance = float(params.get('collision_clearance', 0.01)) self.locked = load_profile(params.get('arm_profile', '')).locked_joints + # Joints the drive node says are switched off, even before there is a teleop to tell. + self.disabled = set() self.teleop = None self.problem = 'Waiting for robot_description' self.joy = None @@ -82,6 +86,8 @@ def __init__(self, **kwargs): self.create_subscription(String, 'robot_description', self.load, latched) self.create_subscription(Joy, 'joy', self.on_joy, 10) self.create_subscription(JointState, 'joint_states', self.on_joint_states, 10) + self.create_subscription(DiagnosticArray, joint_control.TOPIC, self.on_joint_control, + latched) self.command_publisher = self.create_publisher(JointState, 'joint_commands', 10) self.enable_publisher = self.create_publisher(Bool, 'teleop_enabled', latched) # game_controller_node rumbles a local controller; joy_udp_receiver passes it on. @@ -135,6 +141,7 @@ def load(self, message): self.get_logger().error(f'Teleop disabled: {error}') return self.problem = '' + self.apply_disabled() self.get_logger().info('Xbox teleop ready (press Start to enable): ' + '; '.join( f'{group.name}: {group.describe()}' for group in self.teleop.groups)) @@ -153,6 +160,22 @@ def on_joy(self, message): self.joy, self.joy_time = message, time.monotonic() self.joy_count += 1 + def on_joint_control(self, message): + self.disabled = joint_control.disabled_joints(message) + self.apply_disabled() + + def apply_disabled(self): + if self.teleop is None: + return + was_enabled = self.teleop.enabled + changed = self.teleop.set_disabled( + self.disabled, self.recent_measurement(time.monotonic())) + if changed and was_enabled: + # Hold the arm where it is until the operator presses Start again. + self.publish_enabled(False) + self.publish_command() + self.get_logger().warning('Joint enable changed: teleop disabled, arm held') + def on_joint_states(self, message): now = time.monotonic() for name, position in zip(message.name, message.position): @@ -318,6 +341,8 @@ def report(self): 'Y switches once the tool is withdrawn') note = teleop.note or ('At limit: ' + ', '.join(teleop.blocked) if teleop.blocked else ('LB moves along one axis; ' if cartesian else '') + hint) + if teleop.disabled: + note = f'Joints off: {", ".join(sorted(teleop.disabled))}; {note}' speed = (f'{1000.0 * teleop.linear_speed:.1f} mm/s' if group.mode != 'joint' else f'{math.degrees(teleop.speed):.0f} deg/s') low, high = self.config.tool_limits