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