diff --git a/.github/workflows/can_drives.yml b/.github/workflows/can_drives.yml index 354683c6..892234a7 100644 --- a/.github/workflows/can_drives.yml +++ b/.github/workflows/can_drives.yml @@ -16,13 +16,16 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 + # Kernels from 6.15 ship vcan in linux-modules; older ones need linux-modules-extra. - name: Create vcan0 run: | - sudo apt-get update - sudo apt-get install -y "linux-modules-extra-$(uname -r)" - sudo modprobe vcan + if ! sudo modprobe vcan; then + sudo apt-get update + sudo apt-get install -y "linux-modules-extra-$(uname -r)" + sudo modprobe vcan + fi sudo ip link add dev vcan0 type vcan sudo ip link set up vcan0 diff --git a/.github/workflows/firmware.yml b/.github/workflows/firmware.yml index 6e0d2316..b2e001a9 100644 --- a/.github/workflows/firmware.yml +++ b/.github/workflows/firmware.yml @@ -16,7 +16,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Compile for the UNO R4 WiFi uses: arduino/compile-sketches@v1 @@ -41,7 +41,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Install Arduino CLI uses: arduino/setup-arduino-cli@v2 diff --git a/.github/workflows/ros2_build_test.yml b/.github/workflows/ros2_build_test.yml index 84ebda71..b4c34f3c 100644 --- a/.github/workflows/ros2_build_test.yml +++ b/.github/workflows/ros2_build_test.yml @@ -21,7 +21,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Build and Test with Docker Compose run: docker compose --progress plain build test @@ -32,7 +32,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Build and Test with Docker Compose run: docker compose --progress plain build test @@ -49,7 +49,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 # No registry cache: a published layer must come from this build, not from :jazzy. - name: Build and Test with Docker Compose @@ -85,7 +85,7 @@ jobs: steps: - name: Checkout Repository - uses: actions/checkout@v4 + uses: actions/checkout@v7 - name: Build and Test with Docker Compose run: docker compose --progress plain build --no-cache test diff --git a/docs/operator_guide.md b/docs/operator_guide.md index 9f21a7ab..599be972 100644 --- a/docs/operator_guide.md +++ b/docs/operator_guide.md @@ -90,10 +90,10 @@ before starting the SDL bridge. | Start (Xbox Menu button, three lines) | Enable or disable; the arm starts disabled | | B | Stop and hold the current pose | | Y | Switch group: base (joints 1-3), upper (joints 2-5), Cartesian (tool tip) or incision | -| Base group: left stick | Base yaw (left/right) and shoulder (up/down) | -| Base group: right stick up/down | Elbow | -| Upper group: left stick | Shoulder (left/right) and elbow (up/down) | -| Upper group: right stick | Wrist roll (left/right) and wrist pitch (up/down) | +| Base group: left stick | Base yaw (left/right; right turns joint 1 positive, counter-clockwise from above) and shoulder (up/down) | +| Base group: right stick up/down | Elbow (up lifts the elbow, joint 3 negative) | +| Upper group: left stick | Shoulder (left/right) and elbow (up/down; up lifts the elbow, joint 3 negative, as in the base group) | +| Upper group: right stick | Wrist roll (left/right; right turns joint 5 positive, counter-clockwise from above at the zero pose) and wrist pitch (up/down; up turns joint 4 negative) | | Cartesian group: left stick | Tool tip left/right and forward/back, in straight lines | | Cartesian group: right stick | Tool roll (left/right) and tool tip up/down | | Cartesian group: LB (hold) | Move along one axis only: the stick direction pushed furthest | @@ -333,7 +333,10 @@ then run these from the repository root. 1. **Flash the carrier** once, and again after carrier firmware changes. Plug in only the carrier, so its port is the only `/dev/cu.usbmodem*`, or set - `WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. + `WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. This uploads `carrier_bridge_mcp2515`, + for the arm's MCP2515 module; `./scripts/macos.sh flash carrier_bridge` is only for + a carrier using the R4's own CAN with a TJA1051T. The wrong sketch leaves every + drive silent. ```bash brew install arduino-cli @@ -367,6 +370,11 @@ then run these from the repository root. ./scripts/macos.sh run ros2 service call /sim_arm_drives/zero std_srvs/srv/Trigger ``` + `arm` saves the zero in `~/.waybionic/drive_zero.yaml`. While the drives stay + powered, the next `arm` keeps it, so the arm needs no zero pose and no service + call: wait for `Every drive kept its zero`, then press Start. After the drives lose + power, zero again. See [Zeroing and stops](#zeroing-and-stops). + 5. **Check each joint** at the slowest speed in the `upper` group. If a drive turns the wrong way, negate its `factors` in `arm_drives.yaml` and rebuild. Then move each joint a known angle, such as 10 degrees in RViz, and measure it on the arm; a @@ -433,7 +441,7 @@ Then press Start. Real drives take commands through the same gate as the simulat ones. Every drive stops, and the arm must be zeroed again, when: - a drive stops answering, for example because the E-stop cut its power or the - carrier was unplugged; + carrier was unplugged (unless the zero is saved and the drive kept it, as below); - a drive's encoder count jumps further than `max_rpm` allows between two readings, as after a brief power loss; - a drive reports a failed move (as when its stall protection releases the motor) @@ -441,6 +449,36 @@ ones. Every drive stops, and the arm must be zeroed again, when: - a drive stays more than `following_error_counts` from its target for `following_error_ticks` ticks. Both are provisional values in `arm_drives.yaml`. +**A saved zero.** With `drive_zero_state:=` (`./scripts/macos.sh arm` uses +`~/.waybionic/drive_zero.yaml`), each zero is saved to the file once every drive has +reported it. A restart of the station, or a drive that answers again after it went +quiet, keeps the zero of each drive that shows it didn't lose power since. MKS firmware +V1.0.9 reports that in two reads, checked on the bench on all four drives: + +- The zero status (3Bh) says whether the drive was zeroed since power-on. Power-on + clears it, and the host's setup frames don't. +- The raw encoder (35h) counts from power-on, and a zero leaves it alone. So it minus + the zeroed count (31h) stays the same from one zero until the drive loses power. A + zero made elsewhere, such as by `mks_setup`, changes it. + +A drive whose status shows no zero, or whose offset is more than 16 counts from the +saved one, isn't zeroed, and the log says why. A new zero, a failed move and a +following error delete the file. + +A drive that turns more than `following_error_counts` after its stop, for +`following_error_ticks` ticks, also stops every drive, with teleop enabled or not. That +drive gets another stop. The arm keeps its zero, since that drive's encoder still counts +true. + +When the stick reverses a joint, its drive stops and settles (typically 17 ms, at most +about 40 ms on the bench) before it turns back. MKS firmware V1.0.9 keeps a target sent +while the drive is reversing, and now and then one sent mid-stroke, and runs back to it, up +to 12°, at the next stop. So right behind every stop of a running move, including a +Start or B press, the drive also gets a 60 rpm move to where it's to stay. That's the end +of its last move, at most two ticks of travel ahead. The move is sent again every tick +for 0.25 s. On the bench this kept every stop within 0.1° of base travel. See +[F5h on firmware V1.0.9](../waybionic_can/arduino/README.md#f5h-on-firmware-v109). + Once the carrier's E-stop sense is wired, pressing the E-stop also stops every drive at once, and Start is refused until it's released. If the joint commands stop for 0.5 s, every drive stops where it is, and if the host stops, the drives' heartbeat @@ -452,6 +490,61 @@ 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. +### Powered hand-guiding + +Powered hand-guiding is not enabled yet. A stopped drive holds position; disabling +teleop does not release it or turn a push into a movement command. + +The intended workflow is an explicitly selected Hand Guide mode: a deliberate push +starts bounded assistance, then release and stillness for a provisional two seconds +capture the new holding position. This changes the holding target, not the calibrated +zero. Stop must leave the mode disarmed rather than let another push restart it. + +The existing-hardware approach is being evaluated with passive encoder recordings +before adding assistance. Encoder displacement and position error are not force +measurements: gravity, friction, settling and externally applied pressure can all +affect them. Initial base-pressure recordings showed a small, direction-dependent +response that did not consistently separate from untouched encoder jitter. + +The drive's `0.00err` display is motor-shaft angular error, not by itself a fault code. +CAN command `39h` reads signed 32-bit position error: 51200 units per motor turn +(not the encoder's 16384 counts per turn). To read it without changing motor settings, +first stop the ground station so only one process owns the carrier, then run: + +```bash +./scripts/macos.sh drives read-error 3 +``` + +This reads the elbow (CAN ID 3). It reports motor degrees, not joint degrees or force; +the display and CAN readback should be compared before using the signal for hand-guiding. +Motor-generated tracking error must not be mistaken for continued hand pressure. + +An elbow press-hold-release recording received all 1424 requested `39h` replies. +Using the manual's scale, it captured brief excursions of +1.73 and -4.25 motor +degrees, with near-zero error between them and after release. The operator also +observed `Err` returning toward zero while still pressing. Thus zero error does not +prove pressure was released, and an opposite-sign transient must not automatically +trigger assistance in the opposite direction. These observations do not validate an +active hand-guiding controller. + +For the configured MKS `SR_vFOC` mode, the V1.0.9 manual describes `Ma` as the maximum +operating current, and its configuration readback is not measured load current. +`Hold Ma` does not apply in vFOC mode (manual sections 3.2-3.4 and 5.1.10). +Reducing current or changing drive PID gains is not a validated hand-guiding shortcut, +particularly for joints supporting the arm's weight. + +Gravity compensation like Seeed's reBot-DevArm (a torque feed-forward from the arm's +model, so the arm floats under the hand) needs torque-controlled actuators. The MKS +drives accept only position and speed commands and report no current or torque, so +it is not possible on this arm without different motors or a force/torque sensor. + +Bench test of a sensorless workaround, base yaw (CAN ID 1, no gravity load), firmware +V1.0.9, factory vFOC gains Kp=220, Ki=100, Kd=270, Kv=320 on every drive: writing Ki=0 +or Ki=1 with `96h` returns "set success", but `00 96 00` still reads Ki=100, also after +disabling and re-enabling the drive. Held pushes decayed back to near-zero `39h` error +within 1-3 seconds with and without the write, so the position error cannot stand in +for a torque sensor. The drives were restored to Ki=100 and read back. + ### Engineering monitor With `teleop:=true`, the diagnostics panel shows live rows: @@ -464,7 +557,7 @@ With `teleop:=true`, the diagnostics panel shows live rows: | `can.carrier` | The carrier's USB link (reopened every second if unplugged), E-stop and supply (once wired), CAN controller errors, and frames the carrier refused | | `can.bus` | Frames per second and bus load | | `drive.*` | Each drive's reply state and encoder, and its health: `OK`, `FOLLOWING_ERROR`, `STALLED`, `NOT_RESPONDING` or `DISABLED`, with its following error and reply age | -| `arm.*` | Each joint against its target, and whether the arm is zeroed | +| `arm.*` | Each joint against its target, and whether the arm is zeroed or its saved zero is being checked | To try each drive fault in simulation, see [recording drive health sessions](../waybionic_rviz_plugins/README.md#task-7-record-simulated-arm-drive-health-sessions) diff --git a/scripts/carrier_usb.py b/scripts/carrier_usb.py new file mode 100644 index 00000000..26805e63 --- /dev/null +++ b/scripts/carrier_usb.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +""" +Find the carrier (Arduino UNO R4) on USB and get it ready for an upload. + +On the UNO R4 WiFi the carrier firmware moves the USB-C port from the ESP32-S3 bridge to the +RA4M1's own USB (waybionic_can/arduino/README.md, "USB link"), but uploads still go through +the bridge. This hands the port back when needed and prints the port to upload to: + + python scripts/carrier_usb.py upload-port [--port PORT] +""" + +import argparse +import sys +import time + +from serial import Serial +from serial.tools import list_ports + +ARDUINO_VID = 0x2341 +WIFI_BRIDGE_PID = 0x1002 +WIFI_NATIVE_PID = 0x006D +MINIMA_PID = 0x0069 +BOARD_PIDS = { + WIFI_BRIDGE_PID: 'UNO R4 WiFi (USB bridge)', + WIFI_NATIVE_PID: 'UNO R4 WiFi (carrier firmware)', + MINIMA_PID: 'UNO R4 Minima', +} +# The carrier hands the port back when it sees this baud rate with DTR still high +# (UsbHandBack.h); about half a second on the bench. +HAND_BACK_BAUD = 1200 +HAND_BACK_TIMEOUT_S = 10.0 + + +def boards(): + return [port for port in list_ports.comports() + if port.vid == ARDUINO_VID and port.pid in BOARD_PIDS] + + +def describe(ports): + return ', '.join(f'{port.device} [{BOARD_PIDS[port.pid]}]' for port in ports) or 'none' + + +def only_board(device=None): + found = boards() + if device: + found = [port for port in found if port.device == device] + if len(found) != 1: + wanted = f' at {device}' if device else '' + sys.exit(f'error: expected one UNO R4{wanted}; found {describe(boards())}') + return found[0] + + +def bridges(): + return [port for port in boards() if port.pid == WIFI_BRIDGE_PID] + + +def handed_back_bridge(carrier, already_bridged): + """Return the device of the bridge that took over the carrier's USB port, once it has.""" + if carrier.location: + found = [port for port in bridges() if port.location == carrier.location] + else: + found = [port for port in bridges() if port.device not in already_bridged] + return found[0].device if len(found) == 1 else None + + +def hand_back(carrier): + """Ask the carrier firmware on this port to give the USB port back to the bridge.""" + # Another UNO R4 WiFi may already be in bridge mode: it is not the one handed back. + already_bridged = {port.device for port in bridges()} + link = Serial() + link.port = carrier.device + link.baudrate = HAND_BACK_BAUD + link.dtr = True + link.open() + try: + deadline = time.monotonic() + HAND_BACK_TIMEOUT_S + while time.monotonic() < deadline: + bridge = handed_back_bridge(carrier, already_bridged) + if bridge: + return bridge + time.sleep(0.05) + finally: + try: + link.close() + except OSError: + pass + sys.exit(f'error: the carrier at {carrier.device} did not hand USB back to its bridge within ' + f'{HAND_BACK_TIMEOUT_S:.0f} s; unplug it, plug it back in and try again') + + +def upload_port(device=None): + board = only_board(device) + if board.pid == WIFI_NATIVE_PID: + return hand_back(board) + return board.device + + +def main(): + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument('command', choices=['upload-port']) + parser.add_argument('--port', help='the board to use when several are plugged in') + args = parser.parse_args() + print(upload_port(args.port)) + + +if __name__ == '__main__': + main() diff --git a/scripts/macos.sh b/scripts/macos.sh index 81ecb53b..9ef21c7e 100755 --- a/scripts/macos.sh +++ b/scripts/macos.sh @@ -20,12 +20,18 @@ Commands: setup Create/update the RoboStack environment and build the workspace build Build the workspace launch Launch the ground station visualization - flash Compile and upload carrier_bridge to the UNO R4 WiFi (needs arduino-cli) + flash Compile and upload the carrier firmware to the UNO R4 WiFi (needs arduino-cli): + carrier_bridge_mcp2515 (default, the arm's MCP2515 module) or carrier_bridge + (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 run Run any command inside the ROS workspace The carrier is found as the only /dev/cu.usbmodem* port; set WAYBIONIC_CARRIER to choose. +arm uses the arm profile at ~/.waybionic/arm_profile.yaml when it exists (its fitted drives +and locked joints); set WAYBIONIC_ARM_PROFILE to use another file. arm saves each zero in +~/.waybionic/drive_zero.yaml and keeps it on the next start while the drives stay powered; +set WAYBIONIC_DRIVE_ZERO to use another file. EOF } @@ -72,12 +78,45 @@ select_manager() { prepare() { check_host select_manager + SYSROOT_FROM_USER=true if [[ -z "${CONDA_BUILD_SYSROOT:-}" ]]; then CONDA_BUILD_SYSROOT="$(xcrun --show-sdk-path)" + SYSROOT_FROM_USER=false export CONDA_BUILD_SYSROOT fi } +sdk_links() { + # shellcheck disable=SC2016 + run_environment bash -c 'out="$(mktemp)" + printf "int main(void) { return 0; }\n" \ + | CONDA_BUILD_SYSROOT="$1" "${CC:-clang}" -x c - -isysroot "$1" -o "$out" \ + >/dev/null 2>&1 + status=$? + rm -f "$out" + exit "$status"' _ "$1" &2 + CONDA_BUILD_SYSROOT="$sdk" + export CONDA_BUILD_SYSROOT + return + fi + done < <(find /Library/Developer/CommandLineTools/SDKs -maxdepth 1 -name 'MacOSX*.sdk' \ + 2>/dev/null | sort -rV) + echo "warning: no macOS SDK links with the environment's compiler; set" \ + "CONDA_BUILD_SYSROOT to one that does" >&2 +} + setup_environment() { if [[ "$ENV_EXISTS" == true ]]; then echo "Updating $ENV_NAME with $MANAGER..." @@ -109,6 +148,7 @@ run_environment() { build_workspace() { ensure_environment + select_sysroot echo "Building workspace..." ( cd "$ROOT" @@ -157,20 +197,25 @@ find_carrier() { } flash_carrier() { + local name="${1:-carrier_bridge_mcp2515}" local fqbn="arduino:renesas_uno:unor4wifi" - local sketch="$ROOT/waybionic_can/arduino/carrier_bridge" + local sketch="$ROOT/waybionic_can/arduino/$name" local library="$ROOT/waybionic_can/arduino/libraries/WaybionicCan" + local port - [[ -f "$sketch/carrier_bridge.ino" ]] \ - || fail "carrier_bridge is not in this checkout yet: it comes with PR #40 (waybionic_can)" + [[ "$name" == carrier_bridge* && -f "$sketch/$name.ino" ]] \ + || fail "unknown carrier sketch $name: use carrier_bridge or carrier_bridge_mcp2515" command -v arduino-cli >/dev/null 2>&1 \ || fail "install arduino-cli first: brew install arduino-cli" - find_carrier + ensure_environment arduino-cli core update-index arduino-cli core install arduino:renesas_uno arduino-cli compile --fqbn "$fqbn" --library "$library" "$sketch" - arduino-cli upload --fqbn "$fqbn" --port "$CARRIER" "$sketch" - echo "Flashed carrier_bridge to $CARRIER" + # Running carrier firmware has the board's own USB port; uploads go through the WiFi bridge. + port="$(run_environment python "$ROOT/scripts/carrier_usb.py" upload-port \ + ${WAYBIONIC_CARRIER:+--port "$WAYBIONIC_CARRIER"})" + arduino-cli upload --fqbn "$fqbn" --port "$port" "$sketch" + echo "Flashed $name" } command_name="${1:-help}" @@ -199,8 +244,8 @@ case "$command_name" in ros2 launch waybionic_bringup ground_station.launch.py "$@" ;; flash) - check_host - flash_carrier + prepare + flash_carrier "$@" ;; drives) [[ $# -gt 0 ]] || fail "drives needs an mks_setup command, such as scan" @@ -212,9 +257,19 @@ case "$command_name" in prepare find_carrier echo "Carrier: $CARRIER" + profile="${WAYBIONIC_ARM_PROFILE:-$HOME/.waybionic/arm_profile.yaml}" + if [[ -f "$profile" ]]; then + echo "Arm profile: $profile" + elif [[ -n "${WAYBIONIC_ARM_PROFILE:-}" ]]; then + fail "arm profile not found: $profile" + else + profile="" + fi + zero_state="${WAYBIONIC_DRIVE_ZERO:-$HOME/.waybionic/drive_zero.yaml}" run_workspace env RMW_IMPLEMENTATION="${RMW_IMPLEMENTATION:-rmw_cyclonedds_cpp}" \ ros2 launch waybionic_bringup ground_station.launch.py teleop:=true \ - joy_source:=device drive_interface:=slcan drive_channel:="$CARRIER" "$@" + joy_source:=device drive_interface:=slcan drive_channel:="$CARRIER" \ + arm_profile:="$profile" drive_zero_state:="$zero_state" "$@" ;; run) [[ $# -gt 0 ]] || fail "run requires a command" diff --git a/waybionic_bringup/README.md b/waybionic_bringup/README.md index 6fe2bf8c..35f19095 100644 --- a/waybionic_bringup/README.md +++ b/waybionic_bringup/README.md @@ -8,10 +8,16 @@ ros2 launch waybionic_bringup ground_station.launch.py The default starts the new five-joint arm, joint-state GUI, camera follower, and RViz using `waybionic_unified.rviz` with its internal mock diagnostics panel. +RViz starts maximized to the current screen, keeping diagnostics, menus and +controls visible. Use `rviz_maximized:=false` to use the layout's saved window +size instead (1280 x 800 for the bundled layout). +RViz's separate F11 fullscreen mode hides panels and controls; it is not used +for ground station startup. | Argument | Default | Purpose | | --- | --- | --- | | `launch_rviz` | `true` | Start RViz. | +| `rviz_maximized` | `true` | Fill the current screen without hiding panels; false uses the layout's window geometry. Unused when RViz is disabled. | | `use_joint_state_publisher_gui` | `true` | Start the separate joint-state GUI. | | `use_diagnostics` | `true` | Enable the RViz diagnostics panel and permit the demo publisher. | | `use_mock_diagnostics` | `true` | Select internal mock data rather than live topics in the panel; demo mode, teleop and the camera always use live topics. | @@ -21,6 +27,7 @@ RViz using `waybionic_unified.rviz` with its internal mock diagnostics panel. | `teleop` | `false` | Drive the arm with a controller through simulated or real CAN drives. | | `drive_interface` | `sim` | Drive bus: `sim`, or a python-can interface such as `socketcan` or `slcan` for the real MKS drives. | | `drive_channel` | empty | CAN channel for a real drive bus, such as `can0` or `/dev/ttyACM0`. | +| `arm_profile` | empty | YAML file listing this arm's fitted drives and the angles of joints locked without one (`waybionic_teleop/arm_profile.py`); empty means every drive is fitted. | | `joy_source` | `device` | Controller input: local device, UDP host bridge, or none. | | `autoplay` | `false` | Play a scripted demo whenever the controller is left idle. | | `joy_udp_bind` | `127.0.0.1` | UDP receiver bind address; use `0.0.0.0` inside Docker. | diff --git a/waybionic_bringup/launch/ground_station.launch.py b/waybionic_bringup/launch/ground_station.launch.py index dfb8c58f..10134382 100644 --- a/waybionic_bringup/launch/ground_station.launch.py +++ b/waybionic_bringup/launch/ground_station.launch.py @@ -25,6 +25,7 @@ BOOLEAN_CHOICES = ['true', 'false', 'True', 'False', '1', '0'] BOOLEAN_OPTIONS = { 'launch_rviz': 'true', + 'rviz_maximized': 'true', 'use_joint_state_publisher_gui': 'true', 'use_diagnostics': 'true', 'use_mock_diagnostics': 'true', @@ -124,6 +125,28 @@ def check_files_exist(context, *args, **kwargs): return actions +def _launch_rviz(context): + maximized = IfCondition(LaunchConfiguration('rviz_maximized')).evaluate(context) + # Demo mode, teleop and the camera report on live topics. + live_diagnostics = OrSubstitution( + OrSubstitution(LaunchConfiguration('demo_mode'), LaunchConfiguration('teleop')), + LaunchConfiguration('camera')) + return [Node( + package='waybionic_rviz_plugins' if maximized else 'rviz2', + executable='ground_station_rviz' if maximized else 'rviz2', + name='rviz2', output='screen', + arguments=['-d', LaunchConfiguration('effective_rvizconfig')], + condition=IfCondition(LaunchConfiguration('launch_rviz')), + parameters=[ + {'use_sim_time': LaunchConfiguration('use_sim_time')}, + {'use_mock_diagnostics': AndSubstitution( + LaunchConfiguration('use_mock_diagnostics'), + NotSubstitution(live_diagnostics))}, + {'diagnostics_topic': LaunchConfiguration('diagnostics_topic')} + ] + )] + + def generate_launch_description(): waybionic_desc_dir = get_package_share_directory('waybionic_description') waybionic_bringup_dir = get_package_share_directory('waybionic_bringup') @@ -180,6 +203,23 @@ def generate_launch_description(): description='The carrier serial port or CAN channel, such as /dev/cu.usbmodem1101, ' '/dev/ttyACM0 or can0') + drive_frame_log_arg = DeclareLaunchArgument( + 'drive_frame_log', default_value='', + description='File to append every drive frame sent, received or refused to, with its ' + 'host time (waybionic_teleop/frame_log.py); empty records nothing') + + drive_zero_state_arg = DeclareLaunchArgument( + 'drive_zero_state', default_value='', + description='File to save the drive zero in, so a restart keeps it while the drives ' + 'stay powered (SimArmDrives.check_zero); empty saves nothing') + + arm_profile_arg = DeclareLaunchArgument( + 'arm_profile', default_value='', + description="YAML file with this arm's fitted drives and locked joints " + '(waybionic_teleop/arm_profile.py); empty for every drive fitted') + arm_profile = {'arm_profile': ParameterValue(LaunchConfiguration('arm_profile'), + value_type=str)} + joy_source_arg = DeclareLaunchArgument( 'joy_source', default_value='device', description='Controller input: device (local joystick), udp (host bridge) or none') @@ -221,6 +261,10 @@ def generate_launch_description(): 'launch_rviz', default_value='true', choices=BOOLEAN_CHOICES, description='Launch RViz (set false for headless validation)') + rviz_maximized_arg = DeclareLaunchArgument( + 'rviz_maximized', default_value='true', choices=BOOLEAN_CHOICES, + description='Fill the screen with RViz while keeping its panels and controls visible') + rviz_config_arg = DeclareLaunchArgument( 'rvizconfig', default_value=default_rviz_config_path, description='Absolute path to rviz config file') @@ -285,7 +329,7 @@ def generate_launch_description(): package='waybionic_teleop', executable='xbox_teleop', name='xbox_teleop', output='screen', condition=IfCondition(teleop), parameters=[os.path.join(teleop_config_dir, 'xbox_teleop.yaml'), diagnostics_topic, - sim_time] + arm_profile, sim_time] ) drives_node = Node( @@ -295,8 +339,12 @@ def generate_launch_description(): {'interface': ParameterValue(LaunchConfiguration('drive_interface'), value_type=str), 'channel': ParameterValue(LaunchConfiguration('drive_channel'), - value_type=str)}, - sim_time] + value_type=str), + 'frame_log': ParameterValue(LaunchConfiguration('drive_frame_log'), + value_type=str), + 'zero_state': ParameterValue(LaunchConfiguration('drive_zero_state'), + value_type=str)}, + arm_profile, sim_time] ) # RViz orbits view_focus, so the follower also runs for the fixed view. @@ -346,27 +394,18 @@ def generate_launch_description(): }.items() ) - # Demo mode, teleop and the camera report on /diagnostics, so the panel listens to them. - rviz_node = Node( - package='rviz2', executable='rviz2', name='rviz2', output='screen', - arguments=['-d', LaunchConfiguration('effective_rvizconfig')], - condition=IfCondition(LaunchConfiguration('launch_rviz')), - parameters=[ - {'use_sim_time': LaunchConfiguration('use_sim_time')}, - {'use_mock_diagnostics': AndSubstitution( - LaunchConfiguration('use_mock_diagnostics'), - NotSubstitution(OrSubstitution(simulated_joints, camera)))}, - {'diagnostics_topic': LaunchConfiguration('diagnostics_topic')} - ] - ) + rviz_node = OpaqueFunction(function=_launch_rviz) return LaunchDescription([ model_arg, use_mock_diag_arg, diag_topic_arg, start_temp_pub_arg, use_jsp_gui_arg, use_diagnostics_arg, demo_mode_arg, demo_speed_arg, teleop_arg, - drive_interface_arg, drive_channel_arg, joy_source_arg, autoplay_arg, + drive_interface_arg, drive_channel_arg, drive_frame_log_arg, drive_zero_state_arg, + arm_profile_arg, + 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_config_arg, file_check, rsp_node, jsp_gui_node, joint_demo_node, + launch_rviz_arg, rviz_maximized_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, 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 47796106..5b59a973 100644 --- a/waybionic_bringup/rviz/waybionic_unified.rviz +++ b/waybionic_bringup/rviz/waybionic_unified.rviz @@ -210,10 +210,10 @@ Window Geometry: collapsed: false Displays: collapsed: false - Height: 2055 + Height: 800 Hide Left Dock: false Hide Right Dock: false - QMainWindow State: 000000ff00000000fd0000000400000000000001a400000774fc020000000bfb0000001200530065006c0065006300740069006f006e00000001e10000009b0000005c00fffffffb0000001e0054006f006f006c002000500072006f007000650072007400690065007302000001ed000001df00000185000000a3fb000000120056006900650077007300200054006f006f02000001df000002110000018500000122fb000000200054006f006f006c002000500072006f0070006500720074006900650073003203000002880000011d000002210000017afb000000100044006900730070006c006100790073010000003b000000c7000000c700fffffffb0000002000730065006c0065006300740069006f006e00200062007500660066006500720200000138000000aa0000023a00000294fb00000014005700690064006500530074006500720065006f02000000e6000000d2000003ee0000030bfb0000000c004b0069006e0065006300740200000186000001060000030c00000261fb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000108000002330000023400fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000341000002340000023400fffffffb000000200044006900610067006e006f0073007400690063007300500061006e0065006c010000057b000002340000023400ffffff000000010000010f00000774fc0200000003fb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000041000000780000000000000000fb0000000a00560069006500770073010000003b00000774000000a000fffffffb0000001200530065006c0065006300740069006f006e010000025a000000b200000000000000000000000200000490000000a9fc0100000001fb0000000a00560069006500770073030000004e00000080000002e10000019700000003000002ea00000037fc0100000002fb0000000800540069006d00650100000000000002ea0000025300fffffffb0000000800540069006d006501000000000000045000000000000000000000002b0000077500000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 + QMainWindow State: 000000ff00000000fd0000000300000000000000fa000002d9fc0200000001fc00000014000002d90000003a01000023fa000000000200000004fb000000100044006900730070006c0061007900730100000000ffffffff0000001600fffffffb0000000a005600690065007700730100000000ffffffff0000001600fffffffb0000001200530065006c0065006300740069006f006e0100000000ffffffff0000001600fffffffb0000001e0054006f006f006c002000500072006f00700065007200740069006500730100000000ffffffff0000001600ffffff00000001000001b8000002d9fc0200000001fb000000200044006900610067006e006f0073007400690063007300500061006e0065006c0100000014000002d90000001600ffffff00000003000005000000002dfc0100000001fb0000000800540069006d00650100000000000005000000003d00ffffff00000242000002d900000004000000040000000800000008fc0000000100000002000000010000000a0054006f006f006c00730100000000ffffffff0000000000000000 Selection: collapsed: false Time: @@ -222,6 +222,6 @@ Window Geometry: collapsed: false Views: collapsed: false - Width: 746 - X: 57 - Y: 4 + Width: 1280 + X: 0 + Y: 0 diff --git a/waybionic_bringup/scripts/camera_follower.py b/waybionic_bringup/scripts/camera_follower.py index a8113e3f..4c35c22b 100755 --- a/waybionic_bringup/scripts/camera_follower.py +++ b/waybionic_bringup/scripts/camera_follower.py @@ -5,11 +5,11 @@ from geometry_msgs.msg import TransformStamped import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.time import Time import tf2_ros +from waybionic_teleop.ros_shutdown import is_shutdown_error class CameraFollower(Node): @@ -66,19 +66,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise - except RuntimeError as error: - # A TF subscription can surface this Jazzy binding error if its ROS context is - # already invalidated during SIGINT. Other runtime errors must still fail. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): - raise - except TypeError as error: - # tf2 can no longer read the lookup time once SIGINT has invalidated the context. - if rclpy.ok() or not str(error).startswith('time must have sec and nanosec'): + except (RuntimeError, TypeError) as error: + if not is_shutdown_error(error): raise finally: node.destroy_node() diff --git a/waybionic_bringup/scripts/joint_demo.py b/waybionic_bringup/scripts/joint_demo.py index 9234c90e..fb9cc552 100755 --- a/waybionic_bringup/scripts/joint_demo.py +++ b/waybionic_bringup/scripts/joint_demo.py @@ -6,7 +6,6 @@ from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.qos import DurabilityPolicy, QoSProfile @@ -14,6 +13,7 @@ from sensor_msgs.msg import JointState from std_msgs.msg import String import tf2_ros +from waybionic_teleop.ros_shutdown import is_shutdown_error ANGLE_TOLERANCE = math.radians(0.1) OFFSET_TOLERANCE = 1e-4 @@ -256,18 +256,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise - except RuntimeError as error: - # Jazzy's binding error when a subscription's context is invalidated during SIGINT. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): - raise - except TypeError as error: - # tf2 can no longer read the lookup time once SIGINT has invalidated the context. - if rclpy.ok() or not str(error).startswith('time must have sec and nanosec'): + except (RuntimeError, TypeError) as error: + if not is_shutdown_error(error): raise finally: node.destroy_node() diff --git a/waybionic_bringup/test/test_launch_options.py b/waybionic_bringup/test/test_launch_options.py index df2263f4..8802457a 100644 --- a/waybionic_bringup/test/test_launch_options.py +++ b/waybionic_bringup/test/test_launch_options.py @@ -2,9 +2,11 @@ import importlib.util from pathlib import Path +from unittest.mock import patch from launch import LaunchContext from launch.actions import DeclareLaunchArgument, RegisterEventHandler +from launch.conditions import IfCondition from launch.events import Shutdown from launch_ros.actions import Node import pytest @@ -63,7 +65,7 @@ def test_carried_over_options_and_arm_default(): for name in ( 'demo_mode', 'demo_speed', 'teleop', 'joy_source', 'joy_udp_bind', 'joy_udp_port', 'follow_camera', 'use_diagnostics', 'drive_interface', - 'drive_channel', 'autoplay', 'camera', 'camera_bind', 'camera_log', + 'drive_channel', 'arm_profile', 'autoplay', 'camera', 'camera_bind', 'camera_log', ): assert name in args assert args['model'].default_value[0].text.endswith('waybionic_arm.urdf') @@ -76,10 +78,55 @@ def test_headless_ignores_unused_rviz_file(context): }) MODULE.check_files_exist(context) assert context.launch_configurations['effective_rvizconfig'] == '/missing/layout.rviz' - assert not node('rviz2').condition.evaluate(context) + assert not MODULE._launch_rviz(context)[0].condition.evaluate(context) assert not node('joint_state_publisher_gui').condition.evaluate(context) +@pytest.mark.parametrize('value', MODULE.BOOLEAN_CHOICES) +def test_rviz_maximized_argument(context, value): + context.launch_configurations['rviz_maximized'] = value + MODULE.check_files_exist(context) + with patch.object(MODULE, 'Node') as constructor: + MODULE._launch_rviz(context) + options = constructor.call_args.kwargs + maximized = value in ('true', 'True', '1') + assert options['package'] == ('waybionic_rviz_plugins' if maximized else 'rviz2') + assert options['executable'] == ('ground_station_rviz' if maximized else 'rviz2') + arguments = options['arguments'] + assert arguments[0] == '-d' + assert arguments[1].perform(context) == ( + context.launch_configurations['effective_rvizconfig']) + assert len(arguments) == 2 + + +def test_rviz_defaults_to_maximized(): + assert declarations()['rviz_maximized'].default_value[0].text == 'true' + + +@pytest.mark.parametrize('mock', ['true', 'false']) +@pytest.mark.parametrize('mode', [None, 'demo_mode', 'teleop', 'camera']) +def test_rviz_keeps_live_diagnostics_selection(context, mock, mode): + context.launch_configurations['use_mock_diagnostics'] = mock + if mode: + context.launch_configurations[mode] = 'true' + with patch.object(MODULE, 'Node') as constructor: + MODULE._launch_rviz(context) + parameters = constructor.call_args.kwargs['parameters'] + use_mock = parameters[1]['use_mock_diagnostics'] + assert IfCondition(use_mock).evaluate(context) == (mock == 'true' and mode is None) + + +def test_default_window_geometry(): + config = yaml.safe_load((ROOT / 'rviz/waybionic_unified.rviz').read_text()) + geometry = config['Window Geometry'] + assert (geometry['Width'], geometry['Height']) == (1280, 800) + state = bytes.fromhex(geometry['QMainWindow State']) + for panel in config['Panels']: + assert state.count(panel['Name'].encode('utf-16-be')) == 1 + assert sum(panel['Class'] == 'waybionic_rviz_plugins/DiagnosticsPanel' + for panel in config['Panels']) == 1 + + @pytest.mark.parametrize('argument', ['model', 'rvizconfig']) def test_missing_required_file(context, argument): context.launch_configurations[argument] = '/missing/file' diff --git a/waybionic_bringup/test/test_teleop_launch.py b/waybionic_bringup/test/test_teleop_launch.py index b623676c..36c5458b 100644 --- a/waybionic_bringup/test/test_teleop_launch.py +++ b/waybionic_bringup/test/test_teleop_launch.py @@ -82,21 +82,23 @@ def hold(seconds, *pressed, **axes): 'teleop never received the controller packets') self.assertEqual(diagnostics['arm.command_gate'].level, DiagnosticStatus.WARN, 'the drives never loaded the robot description') - hold(1.0, left_x=1.0) + # Joy axes are positive left and up: left stick right turns joint_1 positive. + hold(1.0, left_x=-1.0) self.assertAlmostEqual(joints['joint_1'], 0.0, places=3, msg='moved while disabled') hold(0.2, 'start') - hold(1.0, left_x=1.0) + hold(1.0, left_x=-1.0) self.assertGreater(joints['joint_1'], 0.2) hold(0.3, 'y') yaw = joints['joint_1'] - hold(1.0, left_x=1.0, right_y=1.0) + # In the upper group, right stick down tips the wrist down (joint_4 positive). + hold(1.0, left_x=1.0, right_y=-1.0) self.assertAlmostEqual(joints['joint_1'], yaw, places=2) self.assertGreater(joints['joint_4'], 0.2) hold(0.8, right_trigger=-1.0) self.assertGreater(joints['tool_grip'], 0.3) hold(0.2, 'b') pitch = joints['joint_4'] - hold(0.75, right_y=1.0) + hold(0.75, right_y=-1.0) self.assertAlmostEqual(joints['joint_4'], pitch, places=2, msg='moved after B') self.assertEqual(diagnostics['teleop.state'].values[0].value, 'disabled') for drive in ('base_yaw', 'shoulder', 'elbow', 'wrist_left', 'wrist_right', 'tool'): @@ -105,7 +107,7 @@ def hold(seconds, *pressed, **axes): stop = mks_can.hex_frame(can_id, mks_can.absolute_axis(can_id, 0, 0, 0)) self.assertEqual(values['last_command'], stop, f'{drive} did not stop') hold(0.2, 'start') - hold(0.9, right_y=1.0) + hold(0.9, right_y=-1.0) self.assertGreater(joints['joint_4'], pitch + 0.05, 'Start did not re-arm') self.assertEqual(diagnostics['teleop.state'].values[0].value, 'enabled') self.assertEqual(diagnostics['can.bus'].level, b'\x00') diff --git a/waybionic_can/CMakeLists.txt b/waybionic_can/CMakeLists.txt index 1c224ac0..f29e37de 100644 --- a/waybionic_can/CMakeLists.txt +++ b/waybionic_can/CMakeLists.txt @@ -15,6 +15,7 @@ set(COMMON_SOURCES ${ARDUINO_LIB_SRC}/common/BusLoad.cpp ${ARDUINO_LIB_SRC}/common/Candump.cpp ${ARDUINO_LIB_SRC}/common/GatewayLogic.cpp + ${ARDUINO_LIB_SRC}/common/Mcp2515CanTransport.cpp ${ARDUINO_LIB_SRC}/common/MksFrame.cpp ${ARDUINO_LIB_SRC}/common/NodeLogic.cpp ${ARDUINO_LIB_SRC}/common/SlcanBridge.cpp @@ -68,7 +69,7 @@ if(BUILD_TESTING) set(UNIT_TESTS test_mks_frame test_node_logic test_gateway_logic test_bringup_console test_slcan_bridge - test_bus_load) + test_bus_load test_mcp2515_transport) foreach(test_name ${UNIT_TESTS}) ament_add_gtest(${test_name} tests/unit/${test_name}.cpp) if(TARGET ${test_name}) diff --git a/waybionic_can/arduino/README.md b/waybionic_can/arduino/README.md index e2a6f28b..62a9bb45 100644 --- a/waybionic_can/arduino/README.md +++ b/waybionic_can/arduino/README.md @@ -1,11 +1,16 @@ -# CAN bench firmware (UNO R4 + TJA1051T + MKS SERVO42D/57D) +# CAN bench firmware (UNO R4 + MKS SERVO42D/57D) This folder holds the Arduino firmware for bringing up the arm's MKS drives on a real classic CAN bus. The shared MKS subset is ported from `waybionic_teleop/mks_can.py` (merged through PR #28) and checked against it byte for byte. The host build in `../CMakeLists.txt` compiles and unit-tests the same library files. -For the supervised session with all five arm drives, use the +There are **two different carrier topologies**: the R4's built-in CAN controller with a +TJA1051T transceiver, and the arm's external [MCP2515 SPI module](#mcp2515-carrier). +Select the matching sketch before flashing; identical host protocols do not make the +hardware interchangeable. + +For a supervised built-in-CAN session with all five arm drives, use the [five-drive hardware checklist](../docs/HARDWARE_BRINGUP_CHECKLIST.md). | Sketch | Board role | Moves anything? | @@ -14,7 +19,8 @@ For the supervised session with all five arm drives, use the | `four_node_bench/gateway/` | Arduino 1 of the four-node bench: the laptop types commands, the board puts them on the bus and tracks which receiver answered | Only when typed | | `four_node_bench/receiver/` | Arduinos 2-4: answer MKS frames like a drive, with a software-only actuator | No (software only) | | `carrier_bridge/` | Laptop USB serial ↔ CAN bridge speaking a subset of SLCAN, so python-can can use it | Forwards whatever the host sends | -| `libraries/WaybionicCan/` | Shared code: MKS framing, receiver/gateway logic, console, SLCAN, UNO R4 CAN transport | - | +| `carrier_bridge_mcp2515/` | Same host protocol, using the external MCP2515 SPI module rather than the R4's built-in CAN controller | Forwards whatever the host sends | +| `libraries/WaybionicCan/` | Shared code: MKS framing, receiver/gateway logic, console, SLCAN, built-in and MCP2515 CAN transports | - | ## Safety rules (read before powering a drive) @@ -30,12 +36,13 @@ For the supervised session with all five arm drives, use the -0x800000..0x7FFFFF, 0-3000 rpm, acc 0-255). They are constants in the sketch (`benchPolicy()` / `MotionPolicy`). Change them only with the leads, then re-upload. - The human-readable bench sketches stay at the drive's factory **500 kbit/s**. The real-arm - host and `carrier_bridge` select **1 Mbit/s CAN** after each drive is configured. + built-in-CAN configuration targets **1 Mbit/s CAN** after each drive is configured. + The MCP2515 arm configuration stays at **500 kbit/s**. - `estop ` sends the manual's F7h immediate emergency-stop command. It is a software command and does not replace the physical E-stop. Drive-ID (8Bh) and bitrate (8Ah) are not implemented in the merged `mks_can.py` or this shared library. -## Hardware topology +## Built-in CAN hardware topology ```text laptop (USB serial: 1000000 baud for carrier_bridge, 115200 for the consoles) @@ -50,12 +57,90 @@ UNO R4 WiFi -- CAN TX = D10 --> TJA1051T TXD 24 V supply, current limited ``` -- **The UNO R4 has a CAN controller built in.** The TJA1051T is only a **transceiver**: it turns the controller's TX/RX logic signals into the differential CAN_H/CAN_L pair. No MCP2515 is used. +- **The UNO R4 has a CAN controller built in.** The TJA1051T is only a **transceiver**: it turns the controller's TX/RX logic signals into the differential CAN_H/CAN_L pair. No MCP2515 is used in this variant. - **Pins:** on the **UNO R4 WiFi**, CAN TX = **D10** and CAN RX = **D13**, as in the official core (`variants/UNOWIFIR4/pins_arduino.h`: `PIN_CAN0_TX 10`, `PIN_CAN0_RX 13`). The **UNO R4 Minima** uses different pins, D4 (TX) and D5 (RX), per `variants/MINIMA/pins_arduino.h`. The sketches use the core's `CAN` object, so they pick the right pins for whichever board you compile for, and they print those pins at boot. - **Termination:** one 120 Ω resistor across CAN_H/CAN_L at **each of the two physical ends** of the bus, and nowhere else. With power off, CAN_H to CAN_L should measure about 60 Ω. - **Bus wiring:** CAN_H to CAN_H and CAN_L to CAN_L on every node. - **Not yet specified by Electrical (TBD, ask Yassin):** how the TJA1051T module is powered, how its mode pin is strapped (it must be in normal mode, not silent), the ground reference between the Arduino, the transceiver and the drive, and the connector pinout on the drive side. This README doesn't guess at them. +## MCP2515 carrier + +The arm's carrier uses `carrier_bridge_mcp2515`: UNO R4 WiFi hardware SPI on D11 +(MOSI), D12 (MISO), D13 (SCK), with CS on D10 and INT on D2. The configured module +oscillator is 8 MHz and CAN runs at 500 kbit/s. D13 is **SPI clock in this topology**, +not a transceiver RXD pin. A pin-level diagnosis for the built-in-CAN topology does +not apply to this carrier. + +`scripts/macos.sh flash` selects this sketch by default. The built-in-CAN sketch +requires `scripts/macos.sh flash carrier_bridge`. Neither operation should be +used as a diagnostic probe without confirming the connected hardware and a safe bench state. + +The MCP2515 receive configuration uses **RXM=00 and explicitly zeroed acceptance +masks/filters**, retaining all standard IDs/data bytes while requiring valid CAN messages. +Do not use RXM=11 as a shortcut for accepting all IDs: according to the +[MCP2515 datasheet, sections 4.1.3 and 4.2.2, page 23](https://ww1.microchip.com/downloads/en/DeviceDoc/MCP2515-Stand-Alone-CAN-Controller-with-SPI-20001801J.pdf#page=23), +that debug mode also delivers partially assembled messages when CAN errors occur. +The MKS eight-bit checksum can accidentally accept corrupted data; it does not +replace the controller's CAN validation. +All filters use EXIDE=0, so reception is limited to standard frames. Software also +defensively rejects extended and remote frames if they reach the receive buffers. + +RXnIF locks each receive buffer until the firmware clears it **after** copying the +frame. Slow, separate register reads can contribute to overflow of the other +buffer, but do not by themselves cause a pending frame to be overwritten mid-read. +The existing bench-tested SPI read conditioning is retained. Controller errors +remain counted; no encoder-jump or motion-stop checks are relaxed. + +The previous RXM=11 setting is a confirmed software defect. It is not proof that +every historical corrupt host-log entry originated there: those logs contain +neither the CAN wire traffic nor the SPI transactions. A host fault message alone +does not establish a wiring or transceiver fault. + +### Stationary validation of valid-only reception + +The corrected sketch was uploaded to the UNO R4 WiFi and checked on 2026-10-31, +with the arm supported and the operator present. The five-minute check sent only +31h encoder requests to drives 1, 3, 4 and 5 at 500 kbit/s; it sent no enable, zero, +stop or position commands. + +- **143,985 requests and matching replies**, approximately 119.99 Hz per drive. +- Per-drive p95 host-queue-to-next-matching-reply time: **3.96-4.37 ms**. +- No bad MKS checksums; the largest successive count change was **one count**. +- No new host errors, refusals, reopen events, or carrier-counter increases during + the measurement. A separate audit of the raw serial records confirmed the + encoder-only command whitelist and reply totals. + +Carrier counters are cumulative across serial sessions. The refused-line count +increased between sessions from 0 to 1 to 2, before any encoder requests in those +new sessions, and stayed at 2 throughout the five-minute measurement. The initial +absolute-counter check stopped before polling, and the later measurement explicitly +recorded its baseline rather than resetting the counter. The subsequent +[serial-close check](#serial-close-acknowledgement) isolated a host lifecycle issue, +not evidence of a CAN wiring fault. + +E-stop and supply-voltage telemetry reported **unknown**, not healthy or faulty. +The operator's physical power cutoff, not those unavailable telemetry inputs, was +the safeguard for this stationary check. + +This validates stationary request/reply traffic only. It does **not** establish +calibration accuracy, motion safety, or the source of every historical corrupt +frame. Comparable motion-traffic testing and, if corruption recurs, independent +CAN/SPI capture remain necessary before declaring that failure resolved. + +### Serial-close acknowledgement + +A control-only bench comparison reproduced a refused-line increment when USB was +closed immediately after writing SLCAN `C`. The tested in-band close/open, +flush-before-close and acknowledged-close cycles did not increment it. The host +now waits up to 250 ms for the carrier's close acknowledgement before releasing +USB, rather than treating `write()` as proof that the final line was received. +Timeouts, refusals and disconnects are reported; the port is still released. + +With the corrected host, **30 USB close/reopen cycles and 120 encoder requests** +completed with matching replies and no counter increase. Close acknowledgements +took at most **2.90 ms** in that run. This change does not alter the drive node's +stop/hold sequence and does not send additional motor commands. + ## Bitrate | Where | Bitrate | Status | @@ -63,10 +148,13 @@ UNO R4 WiFi -- CAN TX = D10 --> TJA1051T TXD | MKS drives as shipped | 500 kbit/s | Factory default | | Bench sketches (`kCanBitrate`) | 500 kbit/s | Match drives as shipped | | Real-arm host through `carrier_bridge` | 1 Mbit/s | Target for the five arm drives | +| Real-arm host through `carrier_bridge_mcp2515` | 500 kbit/s | Current 8 MHz MCP2515 arm configuration | | Carrier USB serial | 1,000,000 baud | Separate serial-link setting, not CAN bitrate | -Configure each drive alone before using the real-arm host. The carrier keeps the CAN rate at -which it first opened until reset, so replug it before checking the shared 1 Mbit/s bus: +The following migration is **only for the built-in-CAN 1 Mbit/s topology**, not the +8 MHz MCP2515 carrier (which cannot use 1 Mbit/s with this driver). Configure each +drive alone. The carrier keeps the CAN rate at which it first opened until reset, +so replug it before checking the shared 1 Mbit/s bus: ```bash ./scripts/macos.sh drives set-bitrate 3 1000000 @@ -285,6 +373,7 @@ must remain effective with the carrier absent or failed. | Command | Status | Source | | --- | --- | --- | | 31h READ_ENCODER + 6-byte signed reply | Implemented and verified against merged vectors and an ~81k-case cross-check with `mks_can.py` | `mks_can.py`, `test_mks_can.py` | +| 39h READ_POSITION_ERROR + signed int32 | Python decoder and read-only `mks_setup read-error` query; 1424 matching replies in an elbow pressure recording | `mks_can.py`, `mks_setup.py`, their unit tests | | 82h SET_MODE (05h SR_vFOC) | Implemented and verified | same | | 8Ch SET_RESPONSE | Implemented and verified | same | | 98h SET_HEARTBEAT | Implemented and verified | same | @@ -297,6 +386,50 @@ must remain effective with the carrier absent or failed. "Verified" means checked against the repo's reference implementation and its manual vectors. The real-hardware check is the frame log from the bench session. +The observed `39h` reply has DLC 6: command byte, four signed error bytes, and checksum. +Its scale is 51200 units per motor turn, unlike the `31h` encoder's 16384 counts per +turn. It is motor-shaft position error, not a fault code or a measured force. See +[powered hand-guiding](../../docs/operator_guide.md#powered-hand-guiding) for the limits +of using it to infer a push. + +### F5h on firmware V1.0.9 + +The bench drives (SERVO42D_CAN, firmware V1.0.9, hardware 2) take the F5h frames above as the +manual says, with one exception found with `waybionic_teleop`'s 120 Hz target stream. A target +sent while a running move is reversing or slowing to turn back can be kept, and so can an +occasional target sent mid-stroke in the same direction. Once the moves stop (F5h speed 0, +F7h, or the last target reached), the drive runs to that kept target at the old speed, up to +12° of base travel and 0.07-0.9 s after the frame. Frame logs show the run starting 3-5 ms +after the stop. Each runaway ended 1-8 counts from a target sent earlier. The exact trigger +isn't known. + +The drive node avoids this in two ways. + +- **No target behind a running move.** When the commanded target passes the last encoder + reading against the drive's direction, the node sends an F5h stop (speed 0, acc 0). It + sends no new target until the drive has settled: 12 ms after the stop, with no encoder + step in the old direction; or a run-complete reply after the stop, with a step under 5 + counts. The bench pause before the drive turns back is 17 ms median, 42 ms worst case. + Over the same random stick profiles on the base, streaming straight through each reversal + ran away 7 times in 80 cycles; the stop and settle ran away 0 times in 80 (p≈0.007). +- **A hold right behind every stop.** Every stop of a running move is followed at once by an + F5h to where the drive is to stay, at 60 rpm. That is the stopped move's last target, at + most two ticks of travel past the last encoder reading. The hold goes out again every tick + for 0.25 s. A drive that may have lost its zero (lost, faulted, being zeroed) or whose + E-stop is pressed gets no hold. Bench, base, 80 ramped-down stops per variant: + + | After the stop | Runs to a kept target | Worst excursion | + | --- | --- | --- | + | One re-target once a run showed | 7 | 2515 counts (2.1°) | + | Hold every tick from 8 ms | 8 | 1282 counts (1.1°) | + | Hold 1 ms after the stop, then every tick | 5, each caught | 437 counts (0.37°) | + | **Hold right behind the stop, then every tick** (the node) | **0** | **107 counts (0.09°)** | + +`sim_drives.py` models the kept target so the tests catch any regression. + +The speed-0, acc-0 stop itself overshoots by about 100 counts on the base, then creeps back to +the last F5h target. + ## Verification status | What | Status | diff --git a/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino b/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino index fe397e51..a81f5b26 100644 --- a/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino +++ b/waybionic_can/arduino/carrier_bridge/carrier_bridge.ino @@ -1,8 +1,9 @@ /* WayBionic carrier bridge prototype: laptop USB serial <-> UNO R4 <-> TJA1051T <-> CAN bus. - Speaks a documented SUBSET of the Lawicel SLCAN protocol (see SlcanBridge.h). The real-arm - host opens it at 1,000,000 baud over USB serial and selects the CAN bus bitrate separately. + Speaks a documented SUBSET of the Lawicel SLCAN protocol (see SlcanBridge.h) over the RA4M1's + own USB port, so the serial baud rate the host opens it at does not matter, except 1200: that + hands the port back for an upload (UsbHandBack.h). The host selects the CAN bus bitrate with Sn. Standard 11-bit data frames only. The CAN controller stays off until the host sends 'O', so the board puts nothing on the bus by itself. Host frames wait in a bounded queue while the @@ -19,8 +20,15 @@ #include -// This is the USB serial baud rate, not the CAN bus bitrate. Both ends must use this value. -static const unsigned long kSerialBaud = 1000000; +#if defined(ARDUINO_UNOWIFIR4) +// The UNO R4 WiFi's USB-C port normally belongs to its ESP32-S3, whose USB bridge firmware stops +// passing bytes on for good, in one direction or the other, under steady two-way traffic. +// Defining this hands the port to the RA4M1's own USB at boot (pin P408), as on the UNO R4 Minima, +// so SerialUSB below reaches the host directly. See README.md, "USB link". +void __USBStart(); +void __maybe_start_usb() {__USBStart();} +#endif + static const uint32_t kStatusPeriodMs = 100; static waybionic::R4CanTransport can; @@ -34,7 +42,7 @@ public: class SerialSlcanOutput : public waybionic::SlcanOutput { public: - void write(const char * text) override {Serial.print(text);} + void write(const char * text) override {SerialUSB.print(text);} }; static R4Starter starter; @@ -44,13 +52,15 @@ static uint32_t lastStatusMs = 0; void setup() { - Serial.begin(kSerialBaud); + // USB ignores the baud rate. + SerialUSB.begin(0); } void loop() { - while (Serial.available() > 0) { - bridge.handleChar(static_cast(Serial.read()), millis()); + waybionic::handBackUsbWhenAsked(); + while (SerialUSB.available() > 0) { + bridge.handleChar(static_cast(SerialUSB.read()), millis()); } bridge.drainTransmit(millis()); bridge.pollCan(); diff --git a/waybionic_can/arduino/carrier_bridge_mcp2515/carrier_bridge_mcp2515.ino b/waybionic_can/arduino/carrier_bridge_mcp2515/carrier_bridge_mcp2515.ino new file mode 100644 index 00000000..330dda2e --- /dev/null +++ b/waybionic_can/arduino/carrier_bridge_mcp2515/carrier_bridge_mcp2515.ino @@ -0,0 +1,90 @@ +/* + WayBionic carrier bridge for an MCP2515 CAN module: laptop USB serial <-> UNO R4 <-> SPI <-> + MCP2515 + TJA1050 module <-> CAN bus. + + Same SLCAN subset, USB link and carrier status frame as carrier_bridge.ino (see + SlcanBridge.h), so the ground station cannot tell the two apart. Only the CAN controller + differs: this one is the external MCP2515 the arm's bench uses instead of the R4's own. + + Wiring (UNO R4 WiFi): + MCP2515 CS -> D10 MCP2515 SO (MISO) -> D12 + MCP2515 INT -> D2 MCP2515 SI (MOSI) -> D11 + MCP2515 SCK -> D13 VCC 5 V, GND + kCrystalHz must match the oscillator printed on the module's can (8.000 MHz on the bench). + + Each 'O' from the host makes Mcp2515CanTransport check the chip and run its loopback + self-test before joining the bus; a link that fails is answered with BELL. Its controller + errors and failed link checks are both reported as CAN errors in the status frame. + + As in carrier_bridge.ino, nothing else is printed on the serial port, and the CAN controller + stays in configuration mode (off the bus) until the host sends 'O'. +*/ + +#include + +#if defined(ARDUINO_UNOWIFIR4) +// Take the USB-C port off the WiFi board's ESP32-S3 bridge, as carrier_bridge.ino explains. +void __USBStart(); +void __maybe_start_usb() {__USBStart();} +#endif + +static const uint32_t kStatusPeriodMs = 100; +static const uint8_t kChipSelectPin = 10; +static const uint8_t kInterruptPin = 2; +static const uint32_t kCrystalHz = 8000000; + +static waybionic::ArduinoMcp2515Spi spi(kChipSelectPin, kInterruptPin); +static waybionic::Mcp2515CanTransport can(spi, kCrystalHz); + +class Mcp2515Starter : public waybionic::CanStarter +{ +public: + bool start(uint32_t bitrate) override {return can.begin(bitrate);} +}; + +class SerialSlcanOutput : public waybionic::SlcanOutput +{ +public: + void write(const char * text) override {SerialUSB.print(text);} +}; + +static Mcp2515Starter starter; +static SerialSlcanOutput serialOutput; +static waybionic::SlcanBridge bridge(can, starter, serialOutput); +static uint32_t lastStatusMs = 0; + +void setup() +{ + // USB ignores the baud rate. + SerialUSB.begin(0); + spi.begin(); + // A board reset leaves the MCP2515 as it was, possibly still on the bus: take it off. + can.end(); +} + +void loop() +{ + waybionic::handBackUsbWhenAsked(); + while (SerialUSB.available() > 0) { + bridge.handleChar(static_cast(SerialUSB.read()), millis()); + } + can.service(); + bridge.drainTransmit(millis()); + // Each receive() empties the MCP2515's two buffers before taking the next frame. + bridge.pollCan(); + + const uint32_t now = millis(); + if (now - lastStatusMs >= kStatusPeriodMs) { + lastStatusMs = now; + const waybionic::BenchTelemetry bench = waybionic::readBenchTelemetry(); + waybionic::CarrierStatus status; + status.estop_wired = bench.estop != waybionic::EstopState::kUnknown; + status.estop_pressed = bench.estop == waybionic::EstopState::kPressed; + status.supply_wired = bench.supply_known; + status.supply_millivolts = static_cast( + bench.supply_millivolts > 0xFFFF ? 0xFFFF : bench.supply_millivolts); + status.can_errors = can.errorEvents() + can.linkFaults(); + status.failed_writes = can.failedWrites(); + bridge.reportStatus(status); + } +} diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h b/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h index e633b837..b0cba287 100644 --- a/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/WaybionicCan.h @@ -2,7 +2,8 @@ // Arduino entry point for the WayBionic CAN code. Everything under common/ is plain C++ with // no Arduino, Linux or ROS headers, no heap and no exceptions; the waybionic_can CMake build -// compiles and tests the same files on the host. r4/ is the only board-specific part. +// compiles and tests the same files on the host. r4/ (the UNO R4's built-in CAN controller) and +// mcp2515/ (an MCP2515 module on SPI) are the only board-specific parts. #include "common/BenchTelemetry.h" #include "common/BringupConsole.h" @@ -12,9 +13,12 @@ #include "common/GatewayLogic.h" #include "common/IActuator.h" #include "common/ICanTransport.h" +#include "common/Mcp2515CanTransport.h" #include "common/MksFrame.h" #include "common/NodeLogic.h" #include "common/SlcanBridge.h" #include "common/SoftwareActuator.h" +#include "mcp2515/ArduinoMcp2515Spi.h" #include "r4/R4CanTransport.h" +#include "r4/UsbHandBack.h" diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp new file mode 100644 index 00000000..be38f28c --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.cpp @@ -0,0 +1,543 @@ +#include "common/Mcp2515CanTransport.h" + +namespace waybionic +{ +namespace +{ + +// SPI instructions +constexpr uint8_t kReset = 0xC0; +constexpr uint8_t kRead = 0x03; +constexpr uint8_t kWrite = 0x02; +constexpr uint8_t kBitModify = 0x05; +constexpr uint8_t kRequestToSend0 = 0x81; + +// Registers +constexpr uint8_t kCanStat = 0x0E; +constexpr uint8_t kCanCtrl = 0x0F; +constexpr uint8_t kTec = 0x1C; +constexpr uint8_t kRec = 0x1D; +constexpr uint8_t kCnf3 = 0x28; +constexpr uint8_t kCnf2 = 0x29; +constexpr uint8_t kCnf1 = 0x2A; +constexpr uint8_t kCanIntE = 0x2B; +constexpr uint8_t kCanIntF = 0x2C; +constexpr uint8_t kEflg = 0x2D; +constexpr uint8_t kTxb0Ctrl = 0x30; +constexpr uint8_t kTxb0Sidh = 0x31; +constexpr uint8_t kTxb2Data = 0x56; +constexpr uint8_t kRxb0Ctrl = 0x60; +constexpr uint8_t kRxb0Sidh = 0x61; +constexpr uint8_t kRxb1Ctrl = 0x70; +constexpr uint8_t kRxb1Sidh = 0x71; +// Six acceptance filters and two masks, four registers each. +constexpr uint8_t kAcceptanceBases[] = {0x00, 0x04, 0x08, 0x10, 0x14, 0x18, 0x20, 0x24}; + +// TXB2's data bytes are never transmitted. They hold zeros so that reading two of them leaves +// the chip's SO output low before the read that matters. +constexpr uint8_t kZeroScratch = kTxb2Data + 2; + +constexpr uint8_t kModeMask = 0xE0; +constexpr uint8_t kModeNormal = 0x00; +constexpr uint8_t kModeLoopback = 0x40; +constexpr uint8_t kModeConfig = 0x80; + +constexpr uint8_t kRx0If = 0x01; +constexpr uint8_t kRx1If = 0x02; +constexpr uint8_t kTxReq = 0x08; +constexpr uint8_t kSidlSrr = 0x10; +constexpr uint8_t kSidlIde = 0x08; +constexpr uint8_t kRx0Ovr = 0x40; +constexpr uint8_t kRx1Ovr = 0x80; +constexpr uint8_t kErrorStateMask = 0x3F; // EWARN, RXWAR, TXWAR, RXEP, TXEP, TXBO + +constexpr uint8_t kRxModeMask = 0x60; +constexpr uint8_t kRollover = 0x04; + +constexpr uint32_t kOscillatorStartMs = 5; +constexpr uint32_t kModeChangeMs = 10; +constexpr uint32_t kSelfTestWaitMs = 5; + +uint32_t nextRandom(uint32_t & state) +{ + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + return state; +} + +// The patterns the bench link got wrong most: all ones, alternating bits, a single set MSB, the +// drives' 31h replies around zero, and random bytes. +void selfTestFrame(const uint16_t n, uint32_t & random, Frame & frame) +{ + frame = Frame{}; + frame.id = static_cast((n * 0x2B5u + 1u) & kMaxStandardCanId); + frame.dlc = (n % 8 == 7) ? static_cast(n % (kMaxCanDataBytes + 1)) : kMaxCanDataBytes; + for (uint8_t i = 0; i < kMaxCanDataBytes; ++i) { + uint8_t value = 0; + switch (n % 6) { + case 0: value = 0xFF; break; + case 1: value = 0x00; break; + case 2: value = (i % 2) ? 0x55 : 0xAA; break; + case 3: value = static_cast(0x80u >> i); break; + case 4: value = (i == 0) ? 0x31 : ((n / 6) % 2 ? 0xFF : 0x00); break; + default: value = static_cast(nextRandom(random)); break; + } + frame.data[i] = i < frame.dlc ? value : 0; + } + if (n % 6 == 4 && frame.dlc == kMaxCanDataBytes) { + uint32_t sum = frame.id; + for (uint8_t i = 0; i + 1 < kMaxCanDataBytes; ++i) { + sum += frame.data[i]; + } + frame.data[kMaxCanDataBytes - 1] = static_cast(sum); + } +} + +bool sameFrame(const Frame & a, const Frame & b) +{ + if (a.id != b.id || a.dlc != b.dlc) { + return false; + } + for (uint8_t i = 0; i < a.dlc; ++i) { + if (a.data[i] != b.data[i]) { + return false; + } + } + return true; +} + +} // namespace + +Mcp2515CanTransport::Mcp2515CanTransport(Mcp2515Spi & spi, const uint32_t crystal_hz) +: spi_(spi), crystal_hz_(crystal_hz) +{ +} + +bool Mcp2515CanTransport::timing( + const uint32_t crystal_hz, const uint32_t bitrate, uint8_t & cnf1, uint8_t & cnf2, + uint8_t & cnf3) +{ + // One time quantum is 2 * (BRP + 1) oscillator periods and a bit is 8 quanta: sync 1, + // propagation 2, phase 1 3, phase 2 2. + constexpr uint32_t kQuantaPerBit = 8; + if (bitrate == 0 || crystal_hz % (2 * kQuantaPerBit * bitrate) != 0) { + return false; + } + const uint32_t prescaler = crystal_hz / (2 * kQuantaPerBit * bitrate); + if (prescaler < 1 || prescaler > 64) { + return false; + } + cnf1 = static_cast(prescaler - 1); // SJW 1 quantum + cnf2 = 0x91; // BTLMODE, phase 1 = 3, propagation = 2 + cnf3 = 0x01; // phase 2 = 2 + return true; +} + +uint8_t Mcp2515CanTransport::readRegister(const uint8_t address) +{ + spi_.select(); + spi_.transfer(kRead); + spi_.transfer(kZeroScratch); + spi_.transfer(0x00); + spi_.transfer(0x00); + spi_.deselect(); + + spi_.select(); + spi_.transfer(kRead); + spi_.transfer(address); + const uint8_t value = spi_.transfer(0x00); + spi_.deselect(); + return value; +} + +void Mcp2515CanTransport::writeRegisters( + const uint8_t address, const uint8_t * data, const uint8_t length) +{ + spi_.select(); + spi_.transfer(kWrite); + spi_.transfer(address); + for (uint8_t i = 0; i < length; ++i) { + spi_.transfer(data[i]); + } + spi_.deselect(); +} + +void Mcp2515CanTransport::bitModify(const uint8_t address, const uint8_t mask, const uint8_t value) +{ + spi_.select(); + spi_.transfer(kBitModify); + spi_.transfer(address); + spi_.transfer(mask); + spi_.transfer(value); + spi_.deselect(); +} + +void Mcp2515CanTransport::instruction(const uint8_t code) +{ + spi_.select(); + spi_.transfer(code); + spi_.deselect(); +} + +bool Mcp2515CanTransport::setMode(const uint8_t mode) +{ + bitModify(kCanCtrl, kModeMask, mode); + const uint32_t start = spi_.millis(); + do { + if ((readRegister(kCanStat) & kModeMask) == mode) { + return true; + } + } while (spi_.millis() - start < kModeChangeMs); + return false; +} + +bool Mcp2515CanTransport::configure(const uint8_t mode) +{ + instruction(kReset); + spi_.delayMs(kOscillatorStartMs); + // The zero scratch first: every read below depends on it. + static const uint8_t kZeros[kMaxCanDataBytes] = {}; + writeRegisters(kTxb2Data, kZeros, kMaxCanDataBytes); + if ((readRegister(kCanStat) & kModeMask) != kModeConfig) { + return false; // no chip, or it does not answer + } + const uint8_t cnf[3] = {cnf_[2], cnf_[1], cnf_[0]}; // CNF3, CNF2, CNF1 are consecutive + writeRegisters(kCnf3, cnf, 3); + // RXM=11 also accepts partial, errored messages (DS20001801J, section 4.2.2). + // RXM=00, standard-frame filters and zero masks accept every standard ID/data byte, + // but only valid CAN messages. + for (const uint8_t base : kAcceptanceBases) { + writeRegisters(base, kZeros, 4); + } + writeRegister(kRxb0Ctrl, kRollover); + writeRegister(kRxb1Ctrl, 0x00); + writeRegister(kCanIntE, kRx0If | kRx1If); + writeRegister(kCanIntF, 0x00); + writeRegister(kEflg, 0x00); + return linkHealthy(kModeConfig) && setMode(mode); +} + +bool Mcp2515CanTransport::linkHealthy(const uint8_t mode) +{ + if (!(readRegister(kCnf1) == cnf_[0] && readRegister(kCnf2) == cnf_[1] && + readRegister(kCnf3) == cnf_[2] && readRegister(kZeroScratch) == 0 && + readRegister(kZeroScratch + 1) == 0 && (readRegister(kCanStat) & kModeMask) == mode && + (readRegister(kRxb0Ctrl) & (kRxModeMask | kRollover)) == kRollover && + (readRegister(kRxb1Ctrl) & kRxModeMask) == 0)) + { + return false; + } + // Masks and filters read as zero outside configuration mode, irrespective of their values. + if (mode == kModeConfig) { + for (const uint8_t base : kAcceptanceBases) { + for (uint8_t i = 0; i < 4; ++i) { + if (readRegister(static_cast(base + i)) != 0) { + return false; + } + } + } + } + return true; +} + +bool Mcp2515CanTransport::start() +{ + tx_pending_ = false; + tx_aborting_ = false; + link_suspect_ = false; + // Frames read since the last good link check may have been read wrong. + clearReceived(); + if (!configure(kModeLoopback)) { + ++link_faults_; + instruction(kReset); + return false; + } + self_test_ = runSelfTest(kSelfTestFrames); + writeRegister(kCanIntF, 0x00); + writeRegister(kEflg, 0x00); + rxb1_older_ = false; + if (!self_test_.passed() || !setMode(kModeNormal)) { + ++link_faults_; + instruction(kReset); + return false; + } + const uint32_t now = spi_.millis(); + last_error_sample_ms_ = now; + last_link_check_ms_ = now; + tec_ = 0; + rec_ = 0; + eflg_ = 0; + return true; +} + +bool Mcp2515CanTransport::begin(const uint32_t bitrate) +{ + uint8_t cnf1 = 0; + uint8_t cnf2 = 0; + uint8_t cnf3 = 0; + if (!timing(crystal_hz_, bitrate, cnf1, cnf2, cnf3)) { + return false; + } + if (open_ && bitrate == bitrate_) { + return true; + } + open_ = false; + bitrate_ = bitrate; + cnf_[0] = cnf1; + cnf_[1] = cnf2; + cnf_[2] = cnf3; + open_ = start(); + // Only a transport that was running gets restarted by service(); the host retries a failed + // open itself. + running_ = open_; + bus_load_.reset(bitrate_, spi_.millis()); + return open_; +} + +void Mcp2515CanTransport::end() +{ + instruction(kReset); + spi_.delayMs(kOscillatorStartMs); + open_ = false; + running_ = false; + tx_pending_ = false; + tx_aborting_ = false; + clearReceived(); +} + +void Mcp2515CanTransport::loadTransmit(const Frame & frame) +{ + uint8_t buffer[5 + kMaxCanDataBytes] = {}; + buffer[0] = static_cast(frame.id >> 3); + buffer[1] = static_cast((frame.id & 0x07) << 5); + buffer[4] = frame.dlc; + for (uint8_t i = 0; i < frame.dlc; ++i) { + buffer[5 + i] = frame.data[i]; + } + writeRegisters(kTxb0Sidh, buffer, static_cast(5 + frame.dlc)); + instruction(kRequestToSend0); +} + +bool Mcp2515CanTransport::transmitIdle(const uint32_t now_ms) +{ + if (!tx_pending_) { + return true; + } + if ((readRegister(kTxb0Ctrl) & kTxReq) == 0) { + tx_pending_ = false; + tx_aborting_ = false; + return true; + } + if (!tx_aborting_ && now_ms - tx_started_ms_ >= kTransmitTimeoutMs) { + // A frame nobody acknowledged would otherwise be retried until someone does, and a stale + // motion command must not reach a drive that comes back later. + bitModify(kTxb0Ctrl, kTxReq, 0x00); + tx_aborting_ = true; + ++failed_writes_; + if ((readRegister(kTxb0Ctrl) & kTxReq) == 0) { + tx_pending_ = false; + tx_aborting_ = false; + return true; + } + } + return false; +} + +bool Mcp2515CanTransport::send(const Frame & frame) +{ + if (!open_ || !isValidFrame(frame)) { + return false; + } + const uint32_t now = spi_.millis(); + if (!transmitIdle(now)) { + return false; + } + loadTransmit(frame); + tx_pending_ = true; + tx_started_ms_ = now; + bus_load_.note(frame, now); + return true; +} + +Mcp2515CanTransport::ReadResult Mcp2515CanTransport::readReceived(Frame & frame) +{ + const uint8_t flags = readRegister(kCanIntF) & (kRx0If | kRx1If); + if (flags == 0) { + return ReadResult::kNone; + } + // With rollover a frame goes to RXB0, or to RXB1 while RXB0 is full, so RXB0 holds the older + // frame when both are full. Once RXB0 is emptied ahead of a waiting RXB1, the next frame to + // reach RXB0 is newer than RXB1's. + const bool first = (flags & kRx0If) != 0 && !(rxb1_older_ && (flags & kRx1If) != 0); + const uint8_t base = first ? kRxb0Sidh : kRxb1Sidh; + const uint8_t sidh = readRegister(base); + const uint8_t sidl = readRegister(static_cast(base + 1)); + ReadResult result = ReadResult::kDropped; + if ((sidl & (kSidlIde | kSidlSrr)) == 0) { + Frame got; + got.id = static_cast((static_cast(sidh) << 3) | (sidl >> 5)); + const uint8_t dlc = readRegister(static_cast(base + 4)) & 0x0F; + got.dlc = dlc > kMaxCanDataBytes ? kMaxCanDataBytes : dlc; + for (uint8_t i = 0; i < got.dlc; ++i) { + got.data[i] = readRegister(static_cast(base + 5 + i)); + } + frame = got; + result = ReadResult::kFrame; + } else { + ++dropped_frames_; + } + // RXnIF locks this buffer until cleared (DS20001801J, section 4.1.3), including between + // the separate SPI register reads above. + bitModify(kCanIntF, first ? kRx0If : kRx1If, 0x00); + // RXB1 only fills while RXB0 is full, which includes the reads above, so a frame waiting in + // RXB1 once RXB0 is released is older than whatever RXB0 takes next. Two frames cannot + // arrive within this one SPI read, so RXB1's is not a newer overflow from after the release. + rxb1_older_ = first && (readRegister(kCanIntF) & kRx1If) != 0; + return result; +} + +void Mcp2515CanTransport::collectReceived() +{ + for (uint8_t reads = 0; reads < kMaxReadsPerCall && rx_count_ < kReceiveQueueCapacity && + spi_.interruptAsserted(); ++reads) + { + Frame frame; + const ReadResult result = readReceived(frame); + if (result == ReadResult::kNone) { + return; + } + if (result == ReadResult::kFrame) { + rx_queue_[(rx_head_ + rx_count_) % kReceiveQueueCapacity] = frame; + ++rx_count_; + bus_load_.note(frame, spi_.millis()); + } + } +} + +void Mcp2515CanTransport::clearReceived() +{ + rx_head_ = 0; + rx_count_ = 0; + rxb1_older_ = false; +} + +bool Mcp2515CanTransport::receive(Frame & frame, const uint32_t timeout_ms) +{ + if (!open_) { + return false; + } + const uint32_t start = spi_.millis(); + for (;;) { + collectReceived(); + if (rx_count_ > 0) { + frame = rx_queue_[rx_head_]; + rx_head_ = static_cast((rx_head_ + 1) % kReceiveQueueCapacity); + --rx_count_; + return true; + } + if (spi_.millis() - start >= timeout_ms) { + return false; + } + } +} + +void Mcp2515CanTransport::sampleErrors() +{ + const uint8_t eflg = readRegister(kEflg); + const uint8_t tec = readRegister(kTec); + const uint8_t rec = readRegister(kRec); + // With rollover the chip flags RX0OVR, not RX1OVR, when a frame finds both buffers full + // (measured on the bench chip); either way a frame was lost. + if ((eflg & (kRx0Ovr | kRx1Ovr)) != 0) { + ++receive_overflows_; + bitModify(kEflg, kRx0Ovr | kRx1Ovr, 0x00); + } + const uint8_t entered = static_cast(eflg & kErrorStateMask & ~eflg_); + if (entered != 0 || tec > tec_ || rec > rec_) { + ++error_events_; + } + eflg_ = eflg; + tec_ = tec; + rec_ = rec; +} + +void Mcp2515CanTransport::checkLink() +{ + if (linkHealthy(kModeNormal)) { + link_suspect_ = false; + return; + } + ++link_faults_; + if (!link_suspect_) { + link_suspect_ = true; // confirm on the next check before restarting + return; + } + // Two failed checks in a row: the chip lost its configuration (a reset or brownout) or the + // link is broken. Start again; service() keeps retrying while that fails. + ++restarts_; + open_ = start(); +} + +void Mcp2515CanTransport::service() +{ + if (!running_) { + return; + } + const uint32_t now = spi_.millis(); + if (!open_) { + if (now - last_link_check_ms_ >= kLinkCheckPeriodMs) { + last_link_check_ms_ = now; + ++restarts_; + open_ = start(); + } + return; + } + if (tx_pending_) { + transmitIdle(now); + } + collectReceived(); + if (now - last_error_sample_ms_ >= kErrorSamplePeriodMs) { + last_error_sample_ms_ = now; + sampleErrors(); + } + if (now - last_link_check_ms_ >= kLinkCheckPeriodMs) { + last_link_check_ms_ = now; + checkLink(); + } +} + +Mcp2515CanTransport::SelfTest Mcp2515CanTransport::runSelfTest(const uint16_t frames) +{ + SelfTest result; + uint32_t random = 0x2545F491u; + for (uint16_t n = 0; n < frames; n += 2) { + // Two at a time, so the second rolls over into RXB1 and both buffers are read. + const uint8_t count = (frames - n >= 2) ? 2 : 1; + Frame sent[2]; + for (uint8_t k = 0; k < count; ++k) { + selfTestFrame(static_cast(n + k), random, sent[k]); + loadTransmit(sent[k]); + const uint32_t start = spi_.millis(); + while ((readRegister(kTxb0Ctrl) & kTxReq) != 0 && + spi_.millis() - start < kSelfTestWaitMs) + { + } + } + for (uint8_t k = 0; k < count; ++k) { + ++result.frames; + const uint32_t start = spi_.millis(); + while (!spi_.interruptAsserted() && spi_.millis() - start < kSelfTestWaitMs) { + } + Frame got; + if (!spi_.interruptAsserted() || readReceived(got) != ReadResult::kFrame) { + ++result.missing; + } else if (!sameFrame(got, sent[k])) { + ++result.bad; + } + } + } + return result; +} + +} // namespace waybionic diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.h b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.h new file mode 100644 index 00000000..5c90c85b --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/common/Mcp2515CanTransport.h @@ -0,0 +1,168 @@ +#pragma once + +#include + +#include "common/BusLoad.h" +#include "common/Frame.h" +#include "common/ICanTransport.h" + +namespace waybionic +{ + +// SPI access to one MCP2515: chip select, byte transfer, its INT pin and a clock. The Arduino +// implementation is mcp2515/ArduinoMcp2515Spi.h; the unit tests use a simulated chip. +class Mcp2515Spi +{ +public: + virtual ~Mcp2515Spi() = default; + virtual void select() = 0; + virtual uint8_t transfer(uint8_t out) = 0; + virtual void deselect() = 0; + // True while INT is low. Only the receive-buffer interrupts are enabled, so this means a + // received frame is waiting. + virtual bool interruptAsserted() = 0; + virtual uint32_t millis() = 0; + virtual void delayMs(uint32_t ms) = 0; +}; + +// CAN through an MCP2515 controller on SPI, the common "MCP2515 + TJA1050" module. +// +// Register reads use the one method measured clean on the WayBionic bench link. On that link +// the chip sometimes shifts a read out one bit early (its SO output is one clock ahead), which +// depends on the previous SPI transaction, and multi-byte "burst" reads slip inside the burst. +// Writes, bit-modify and instructions were not observed to be affected in those tests. +// Every read here is a single byte, preceded by a two-byte read of TXB2's data registers, +// which are kept at zero and never +// transmitted. With that, 8000 loopback frames had no bad byte and 800 drive replies out of 800 +// were valid; burst reads of the same frames were wrong 84 % of the time. +// +// Transmission uses TXB0 only, so frames leave in the order they are sent. A frame that has +// not left after kTransmitTimeoutMs (nobody ACKs it: drives unpowered, open bus) is aborted and +// counted rather than sent late. Reception uses both buffers with rollover; INT shows when a +// frame is waiting, so an idle poll costs no SPI traffic. The chip holds only two frames and a +// conditioned read of one takes about a quarter of a millisecond, so service() moves them into a +// queue here as they arrive and receive() hands them out in arrival order. +// RXM=00 with standard-frame filters and zero masks admits all standard IDs but rejects +// errored CAN messages, unlike debug RXM=11 which can expose partially assembled messages. +// RXnIF remains set until the full frame is copied, so new traffic cannot overwrite a +// buffer while it is being read. +// +// begin() resets the chip, checks that it answers and holds its configuration, then sends +// kSelfTestFrames through the chip's internal loopback (nothing reaches the bus) and only joins +// the bus if every frame read back exactly. A link too noisy for the read method is refused +// instead of handing out wrong data. +class Mcp2515CanTransport : public ICanTransport +{ +public: + static constexpr uint32_t kTransmitTimeoutMs = 20; + static constexpr uint32_t kErrorSamplePeriodMs = 10; + static constexpr uint32_t kLinkCheckPeriodMs = 100; + static constexpr uint16_t kSelfTestFrames = 96; + static constexpr uint8_t kReceiveQueueCapacity = 16; + // At most this many frames are read from the chip per call, which bounds a call's time. + static constexpr uint8_t kMaxReadsPerCall = 4; + + struct SelfTest + { + uint16_t frames = 0; + uint16_t bad = 0; // read back with a different ID, length or data byte + uint16_t missing = 0; // never arrived + bool passed() const {return frames > 0 && bad == 0 && missing == 0;} + }; + + // crystal_hz is the oscillator on the module, usually 8 or 16 MHz. + Mcp2515CanTransport(Mcp2515Spi & spi, uint32_t crystal_hz); + + // Reset, configure, self-test and join the bus. Calling it again at the running bitrate is a + // no-op; another bitrate reconfigures the chip. False leaves the chip off the bus. If the + // chip later loses its configuration, service() restarts it. + bool begin(uint32_t bitrate); + // Reset the chip into configuration mode: off the bus, nothing acknowledged. + void end(); + bool isOpen() const {return open_;} + uint32_t bitrate() const {return bitrate_;} + + bool send(const Frame & frame) override; + // Extended and remote frames that reach software are dropped and counted: every protocol + // here uses 11-bit data frames. + bool receive(Frame & frame, uint32_t timeout_ms) override; + + // Call every loop pass, and between slow jobs such as writing to a serial port: moves received + // frames off the chip, finishes or aborts the pending transmission, samples the controller's + // error state and checks the SPI link. Does SPI work only when something is due. + void service(); + + const SelfTest & lastSelfTest() const {return self_test_;} + // Controller error-state changes: error counters rising, warning/passive/bus-off entered. + uint32_t errorEvents() const {return error_events_;} + // Frames aborted because they did not leave in time. + uint32_t failedWrites() const {return failed_writes_;} + // Failed checks of the SPI link or the chip's configuration, and failed (re)starts. + uint32_t linkFaults() const {return link_faults_;} + // Times the chip lost a frame because both of its receive buffers were full. + uint32_t receiveOverflows() const {return receive_overflows_;} + uint32_t droppedFrames() const {return dropped_frames_;} + uint32_t restarts() const {return restarts_;} + uint8_t transmitErrorCount() const {return tec_;} + uint8_t receiveErrorCount() const {return rec_;} + uint8_t errorFlags() const {return eflg_;} + // Frames sent and received since begin(). + BusLoad & busLoad() {return bus_load_;} + + // CNF1..CNF3 for 8 time quanta per bit with the sample point at 75 %. False if the crystal + // cannot make the bitrate exactly with those quanta (8 MHz cannot make 1 Mbit/s). + static bool timing( + uint32_t crystal_hz, uint32_t bitrate, uint8_t & cnf1, uint8_t & cnf2, uint8_t & cnf3); + +private: + enum class ReadResult : uint8_t {kNone, kFrame, kDropped}; + + uint8_t readRegister(uint8_t address); + void writeRegisters(uint8_t address, const uint8_t * data, uint8_t length); + void writeRegister(uint8_t address, uint8_t value) {writeRegisters(address, &value, 1);} + void bitModify(uint8_t address, uint8_t mask, uint8_t value); + void instruction(uint8_t code); + bool setMode(uint8_t mode); + bool configure(uint8_t mode); + bool start(); + void loadTransmit(const Frame & frame); + ReadResult readReceived(Frame & frame); + void collectReceived(); + void clearReceived(); + bool transmitIdle(uint32_t now_ms); + void sampleErrors(); + bool linkHealthy(uint8_t mode); + void checkLink(); + SelfTest runSelfTest(uint16_t frames); + + Mcp2515Spi & spi_; + uint32_t crystal_hz_; + bool running_ = false; // opened by begin(); service() restarts it if the chip drops out + bool open_ = false; + uint32_t bitrate_ = 0; + uint8_t cnf_[3] = {}; + bool tx_pending_ = false; + bool tx_aborting_ = false; + uint32_t tx_started_ms_ = 0; + uint32_t last_error_sample_ms_ = 0; + uint32_t last_link_check_ms_ = 0; + bool link_suspect_ = false; + // Set when RXB1 holds a frame older than whatever RXB0 receives next. + bool rxb1_older_ = false; + Frame rx_queue_[kReceiveQueueCapacity]; + uint8_t rx_head_ = 0; + uint8_t rx_count_ = 0; + SelfTest self_test_; + uint32_t error_events_ = 0; + uint32_t failed_writes_ = 0; + uint32_t link_faults_ = 0; + uint32_t receive_overflows_ = 0; + uint32_t dropped_frames_ = 0; + uint32_t restarts_ = 0; + uint8_t tec_ = 0; + uint8_t rec_ = 0; + uint8_t eflg_ = 0; + BusLoad bus_load_; +}; + +} // namespace waybionic diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.cpp b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.cpp new file mode 100644 index 00000000..f13d1e1d --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.cpp @@ -0,0 +1,92 @@ +#include "mcp2515/ArduinoMcp2515Spi.h" + +#if defined(ARDUINO) + +#include +#include + +namespace waybionic +{ + +ArduinoMcp2515Spi::ArduinoMcp2515Spi( + const uint8_t cs_pin, const uint8_t int_pin, const uint32_t clock_hz) +: cs_pin_(cs_pin), int_pin_(int_pin), clock_hz_(clock_hz) +{ +} + +void ArduinoMcp2515Spi::begin() +{ + pinMode(cs_pin_, OUTPUT); + digitalWrite(cs_pin_, HIGH); + pinMode(int_pin_, INPUT); +#if defined(ARDUINO_ARCH_RENESAS) + // Every register read is two transactions, so chip select through the port's set/reset + // register instead of digitalWrite saves a tenth of each read. + const bsp_io_port_pin_t pin = g_pin_cfg[cs_pin_].pin; + const uintptr_t port_stride = + reinterpret_cast(R_PORT1) - reinterpret_cast(R_PORT0); + R_PORT0_Type * const port = reinterpret_cast( + reinterpret_cast(R_PORT0) + port_stride * (static_cast(pin) >> 8)); + cs_set_reset_ = &port->PCNTR3; + cs_mask_ = 1u << (static_cast(pin) & 0xFFu); +#endif + // Not SPI.end() first: on the UNO R4 core it faults if SPI has not been started. + SPI.begin(); +} + +void ArduinoMcp2515Spi::csLow() +{ + if (cs_set_reset_ != nullptr) { + *cs_set_reset_ = cs_mask_ << 16; // the upper half resets the pin + } else { + digitalWrite(cs_pin_, LOW); + } +} + +void ArduinoMcp2515Spi::csHigh() +{ + if (cs_set_reset_ != nullptr) { + *cs_set_reset_ = cs_mask_; + } else { + digitalWrite(cs_pin_, HIGH); + } +} + +void ArduinoMcp2515Spi::select() +{ + SPI.beginTransaction(SPISettings(clock_hz_, MSBFIRST, SPI_MODE0)); + csLow(); +} + +uint8_t ArduinoMcp2515Spi::transfer(const uint8_t out) +{ + return SPI.transfer(out); +} + +void ArduinoMcp2515Spi::deselect() +{ + csHigh(); + SPI.endTransaction(); + // The MCP2515 needs chip select high for 50 ns between transactions; the next select is + // further off than that, and these cover it even if it were not (21 ns each at 48 MHz). + __asm__ volatile("nop\n nop\n nop"); +} + +bool ArduinoMcp2515Spi::interruptAsserted() +{ + return digitalRead(int_pin_) == LOW; +} + +uint32_t ArduinoMcp2515Spi::millis() +{ + return ::millis(); +} + +void ArduinoMcp2515Spi::delayMs(const uint32_t ms) +{ + delay(ms); +} + +} // namespace waybionic + +#endif diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.h b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.h new file mode 100644 index 00000000..c85829cd --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/mcp2515/ArduinoMcp2515Spi.h @@ -0,0 +1,45 @@ +#pragma once + +// The MCP2515 module on the board's hardware SPI pins (UNO R4: D11 MOSI, D12 MISO, D13 SCK), +// with chip select and INT on any digital pins. Mcp2515CanTransport does the rest. + +#if defined(ARDUINO) + +#include + +#include "common/Mcp2515CanTransport.h" + +namespace waybionic +{ + +class ArduinoMcp2515Spi : public Mcp2515Spi +{ +public: + // 8 MHz is the clock the bench link was validated at; the MCP2515 allows up to 10 MHz. + ArduinoMcp2515Spi(uint8_t cs_pin, uint8_t int_pin, uint32_t clock_hz = 8000000); + + // Call once from setup(), before the transport's begin(). + void begin(); + + void select() override; + uint8_t transfer(uint8_t out) override; + void deselect() override; + bool interruptAsserted() override; + uint32_t millis() override; + void delayMs(uint32_t ms) override; + +private: + void csLow(); + void csHigh(); + + uint8_t cs_pin_; + uint8_t int_pin_; + uint32_t clock_hz_; + // The port's set/reset register for chip select, where the core has one (UNO R4). + volatile uint32_t * cs_set_reset_ = nullptr; + uint32_t cs_mask_ = 0; +}; + +} // namespace waybionic + +#endif diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.cpp b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.cpp new file mode 100644 index 00000000..56de9d89 --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.cpp @@ -0,0 +1,43 @@ +#include "r4/UsbHandBack.h" + +#if defined(ARDUINO_UNOWIFIR4) + +#include + +void goBootloader(); + +namespace waybionic +{ + +static const uint32_t kHandBackBaud = 1200; +static const uint32_t kDisconnectMs = 250; + +void handBackUsbWhenAsked() +{ + if (SerialUSB.baud() != kHandBackBaud) { + return; + } + // The host's DTR drop would otherwise run the core's immediate reset from the USB interrupt. + __disable_irq(); + R_USB_FS0->SYSCFG_b.DPRPU = 0; + R_BSP_SoftwareDelay(kDisconnectMs, BSP_DELAY_UNITS_MILLISECONDS); + // Already handed back: stop the bootloader pulsing P408 to do it again while the host is + // enumerating the bridge. + R_SYSTEM->PRCR = 0xA502; + R_SYSTEM->VBTBKR[1] = 0; + R_SYSTEM->PRCR = 0xA500; + goBootloader(); +} + +} // namespace waybionic + +#else + +namespace waybionic +{ + +void handBackUsbWhenAsked() {} + +} // namespace waybionic + +#endif diff --git a/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.h b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.h new file mode 100644 index 00000000..0ccf3cbc --- /dev/null +++ b/waybionic_can/arduino/libraries/WaybionicCan/src/r4/UsbHandBack.h @@ -0,0 +1,17 @@ +#pragma once + +namespace waybionic +{ + +// For sketches that take the UNO R4 WiFi's USB-C port off the ESP32-S3 bridge (see +// carrier_bridge.ino). Call at the top of loop(): when the host sets 1200 baud and keeps DTR +// high, it disconnects for long enough that the host notices, then restarts in the bootloader +// with the port back on the bridge, ready for an upload. Does nothing on other boards. +// +// The core's own 1200-baud reset (DTR low) also restarts in the bootloader, but it drops the +// connection and resets at once. The bridge, whose pull-up never went off, takes the line +// back too quickly for macOS to see a disconnect, so it keeps the dead device and never finds +// the bridge. +void handBackUsbWhenAsked(); + +} // namespace waybionic diff --git a/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md b/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md index 13332476..8db605fd 100644 --- a/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md +++ b/waybionic_can/docs/HARDWARE_BRINGUP_CHECKLIST.md @@ -28,13 +28,15 @@ With only the UNO R4 WiFi connected over USB: ```bash brew install arduino-cli -./scripts/macos.sh flash +./scripts/macos.sh flash carrier_bridge ``` -Expected: the helper finds one `/dev/cu.usbmodem*`, compiles `carrier_bridge`, uploads it, and -prints `Flashed carrier_bridge to ...`. If several ports exist, set -`WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. The firmware uses **1,000,000 baud on USB serial**. -That is independent of the selected **1,000,000 bit/s CAN bus** rate. +Expected: the helper compiles `carrier_bridge`, finds the upload port with +`scripts/carrier_usb.py upload-port` (which hands USB back to the WiFi bridge when the running +carrier firmware has it), uploads, and prints `Flashed carrier_bridge`. If several UNO R4 +boards are plugged in, set `WAYBIONIC_CARRIER=/dev/cu.usbmodem...`. The firmware uses the +RA4M1's native USB, so the serial baud rate has no effect (1200 baud only asks it to hand USB +back for an upload). That is independent of the selected **1,000,000 bit/s CAN bus** rate. Before changing drive settings, connect one factory drive at 500 kbit/s and run: @@ -165,7 +167,7 @@ carrier's status frame is host-only ID `0x7F0`; it is not transmitted on CAN. Date / repository commit: Operators / lead present: Carrier port / firmware result: -USB serial baud: 1000000 +USB serial: native USB (baud rate ignored) CAN bitrate: 1000000 bit/s Termination / powered-off resistance: Supply setting / current limit: diff --git a/waybionic_can/tests/unit/test_mcp2515_transport.cpp b/waybionic_can/tests/unit/test_mcp2515_transport.cpp new file mode 100644 index 00000000..816b1dff --- /dev/null +++ b/waybionic_can/tests/unit/test_mcp2515_transport.cpp @@ -0,0 +1,733 @@ +// Mcp2515CanTransport against a simulated MCP2515 whose SPI link has the bench fault: a read +// comes back shifted one bit (the next register's MSB shifted in) unless it is a single byte +// right after a two-byte read of zeros. The real link is kinder; this model is the strict form +// of the rule the transport must follow, so every test below fails if any read breaks it. + +#include + +#include +#include +#include +#include + +#include "common/Mcp2515CanTransport.h" +#include "common/MksFrame.h" + +namespace waybionic +{ +namespace +{ + +constexpr uint8_t kCanStat = 0x0E; +constexpr uint8_t kCanCtrl = 0x0F; +constexpr uint8_t kTec = 0x1C; +constexpr uint8_t kRec = 0x1D; +constexpr uint8_t kCnf1 = 0x2A; +constexpr uint8_t kCanIntE = 0x2B; +constexpr uint8_t kCanIntF = 0x2C; +constexpr uint8_t kEflg = 0x2D; +constexpr uint8_t kTxb0Ctrl = 0x30; +constexpr uint8_t kTxb2Data = 0x56; +constexpr uint8_t kRxb0Ctrl = 0x60; +constexpr uint8_t kRxb0Sidh = 0x61; +constexpr uint8_t kRxb1Ctrl = 0x70; +constexpr uint8_t kRxb1Sidh = 0x71; + +class FakeMcp2515 : public Mcp2515Spi +{ +public: + enum class Link {kClean, kSlipping, kBroken}; + + FakeMcp2515() + { + std::memset(regs, 0xA5, sizeof(regs)); + reset(); + } + + void select() override + { + index_ = 0; + instruction_ = 0; + read_count_ = 0; + read_all_zero_ = true; + } + + uint8_t transfer(const uint8_t out) override + { + ++transfers; + if (!present) { + return 0xFF; + } + const size_t index = index_++; + if (index == 0) { + instruction_ = out; + if (out == 0xC0) { + reset(); + } else if (out == 0x81) { + requestToSend(); + } + return 0x00; + } + switch (instruction_) { + case 0x03: // READ + if (index == 1) { + address_ = out; + return 0x00; + } + return readByte(); + case 0x02: // WRITE + if (index == 1) { + address_ = out; + } else { + writeRegister(address_++, out, 0xFF); + } + return 0x00; + case 0x05: // BIT MODIFY + if (index == 1) { + address_ = out; + } else if (index == 2) { + mask_ = out; + } else if (index == 3) { + writeRegister(address_, out, mask_); + } + return 0x00; + default: + return 0x00; + } + } + + void deselect() override + { + conditioned_ = instruction_ == 0x03 && read_count_ == 2 && read_all_zero_; + } + + bool interruptAsserted() override {return (regs[kCanIntF] & regs[kCanIntE]) != 0;} + uint32_t millis() override {return now_ms++;} + void delayMs(const uint32_t ms) override {now_ms += ms;} + + uint8_t mode() const {return regs[kCanStat] & 0xE0;} + + // A frame arriving from the bus, into RXB0 or (rollover) RXB1. + bool deliver( + const Frame & frame, const uint8_t sidl_flags = 0, const bool valid_can = true) + { + if (!valid_can) { + ++regs[kRec]; + regs[kCanIntF] |= 0x80; // MERRF + } + uint8_t base = 0; + uint8_t flag = 0; + if ((regs[kCanIntF] & 0x01) == 0) { + base = kRxb0Sidh; + flag = 0x01; + } else if ((regs[kRxb0Ctrl] & 0x04) != 0 && (regs[kCanIntF] & 0x02) == 0) { + base = kRxb1Sidh; + flag = 0x02; + } else { + // Measured on the bench chip: with rollover, a frame finding both buffers full sets + // RX0OVR (and ERRIF), not RX1OVR. + regs[kEflg] |= 0x40; + regs[kCanIntF] |= 0x20; + return false; + } + // DS20001801J section 4.2.2: debug RXM=11 also accepts partial, errored messages. + if (!valid_can && (regs[base - 1] & 0x60) != 0x60) { + return false; + } + regs[base] = static_cast(frame.id >> 3); + regs[base + 1] = static_cast(((frame.id & 0x07) << 5) | sidl_flags); + regs[base + 2] = 0; + regs[base + 3] = 0; + regs[base + 4] = frame.dlc; + for (uint8_t i = 0; i < kMaxCanDataBytes; ++i) { + regs[base + 5 + i] = frame.data[i]; + } + regs[kCanIntF] |= flag; + return true; + } + + // The pending TXB0 frame got its ACK. + void acknowledge() + { + if (regs[kTxb0Ctrl] & 0x08) { + transmitted.push_back(pending_); + regs[kTxb0Ctrl] &= static_cast(~0x08); + } + } + + uint8_t regs[128]; + // Frames on the wire: each lands the moment a receive buffer is freed. + std::vector arriving; + Link link = Link::kSlipping; + bool present = true; + bool auto_ack = true; + uint32_t now_ms = 1000; + uint32_t transfers = 0; + uint32_t aborted = 0; + std::vector transmitted; + std::function on_read; + +private: + void reset() + { + // Data registers keep what they held; only the control registers have reset values. + regs[kCanStat] = 0x80; + regs[kCanCtrl] = 0x87; + for (uint8_t a = 0x28; a <= 0x2D; ++a) { + regs[a] = 0; + } + regs[kTec] = 0; + regs[kTec + 1] = 0; + regs[kTxb0Ctrl] = 0; + regs[kRxb0Ctrl] = 0; + regs[0x70] = 0; + } + + uint8_t readByte() + { + if (on_read) { + on_read(address_ & 0x7F); + } + const uint8_t value = regs[address_ & 0x7F]; + const uint8_t next = regs[(address_ + 1) & 0x7F]; + ++address_; + ++read_count_; + read_all_zero_ = read_all_zero_ && value == 0; + const bool clean = link == Link::kClean || + (link == Link::kSlipping && read_count_ == 1 && conditioned_); + return clean ? value : static_cast((value << 1) | (next >> 7)); + } + + void writeRegister(const uint8_t address, const uint8_t value, const uint8_t mask) + { + const uint8_t a = address & 0x7F; + const uint8_t merged = static_cast((regs[a] & ~mask) | (value & mask)); + if (a == kCanStat) { + return; // read-only + } + if (a == kCanCtrl) { + regs[a] = merged; + regs[kCanStat] = static_cast((regs[kCanStat] & 0x1F) | (merged & 0xE0)); + return; + } + if (a == kCanIntF) { + const bool freed = (regs[a] & 0x03 & ~merged) != 0; + regs[a] = merged; + if (freed && !arriving.empty()) { + deliver(arriving.front()); + arriving.erase(arriving.begin()); + } + return; + } + if (a == kTxb0Ctrl) { + if ((regs[a] & 0x08) && !(merged & 0x08)) { + ++aborted; + regs[a] = static_cast((merged & ~0x08) | 0x40); // ABTF + return; + } + regs[a] = merged; + return; + } + regs[a] = merged; + } + + void requestToSend() + { + Frame frame; + frame.id = static_cast((regs[0x31] << 3) | (regs[0x32] >> 5)); + frame.dlc = regs[0x35] & 0x0F; + for (uint8_t i = 0; i < kMaxCanDataBytes; ++i) { + frame.data[i] = i < frame.dlc ? regs[0x36 + i] : 0; + } + regs[kTxb0Ctrl] = 0x08; + if (mode() == 0x40) { + regs[kTxb0Ctrl] = 0; + deliver(frame); + return; + } + pending_ = frame; + if (auto_ack) { + acknowledge(); + } + } + + size_t index_ = 0; + uint8_t instruction_ = 0; + uint8_t address_ = 0; + uint8_t mask_ = 0; + uint8_t read_count_ = 0; + bool read_all_zero_ = true; + bool conditioned_ = false; + Frame pending_; +}; + +Frame makeFrame(const uint16_t id, std::initializer_list bytes) +{ + Frame frame; + frame.id = id; + for (const uint8_t b : bytes) { + frame.data[frame.dlc++] = b; + } + return frame; +} + +void expectSame(const Frame & expected, const Frame & got) +{ + EXPECT_EQ(expected.id, got.id); + ASSERT_EQ(expected.dlc, got.dlc); + for (uint8_t i = 0; i < expected.dlc; ++i) { + EXPECT_EQ(expected.data[i], got.data[i]) << "byte " << int(i); + } +} + +TEST(Mcp2515Timing, EightQuantaPerBit) +{ + uint8_t c1 = 0; + uint8_t c2 = 0; + uint8_t c3 = 0; + ASSERT_TRUE(Mcp2515CanTransport::timing(8000000, 500000, c1, c2, c3)); + EXPECT_EQ(0x00, c1); // the register set the bench drives answered at, AA_MCP2515's 8 MHz/500k + EXPECT_EQ(0x91, c2); + EXPECT_EQ(0x01, c3); + ASSERT_TRUE(Mcp2515CanTransport::timing(8000000, 250000, c1, c2, c3)); + EXPECT_EQ(0x01, c1); + ASSERT_TRUE(Mcp2515CanTransport::timing(8000000, 125000, c1, c2, c3)); + EXPECT_EQ(0x03, c1); + ASSERT_TRUE(Mcp2515CanTransport::timing(16000000, 1000000, c1, c2, c3)); + EXPECT_EQ(0x00, c1); + ASSERT_TRUE(Mcp2515CanTransport::timing(16000000, 500000, c1, c2, c3)); + EXPECT_EQ(0x01, c1); + EXPECT_FALSE(Mcp2515CanTransport::timing(8000000, 1000000, c1, c2, c3)); + EXPECT_FALSE(Mcp2515CanTransport::timing(8000000, 0, c1, c2, c3)); +} + +TEST(Mcp2515Fake, BurstAndUnconditionedReadsSlip) +{ + // Guards the model itself: without the method, the transport tests would prove nothing. + FakeMcp2515 chip; + chip.regs[0x40] = 0x31; + chip.regs[0x41] = 0xFF; + chip.regs[0x42] = 0x00; + chip.select(); + chip.transfer(0x03); + chip.transfer(0x40); + const uint8_t first = chip.transfer(0); + const uint8_t second = chip.transfer(0); + chip.deselect(); + EXPECT_NE(0x31, first); + EXPECT_NE(0xFF, second); +} + +TEST(Mcp2515Transport, BeginConfiguresSelfTestsAndJoinsTheBus) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + EXPECT_TRUE(can.isOpen()); + EXPECT_EQ(500000u, can.bitrate()); + EXPECT_EQ(0x00, chip.mode()); + EXPECT_EQ(0x00, chip.regs[kCnf1]); + EXPECT_EQ(0x91, chip.regs[kCnf1 - 1]); + EXPECT_EQ(0x01, chip.regs[kCnf1 - 2]); + EXPECT_EQ(0x03, chip.regs[kCanIntE]); + EXPECT_EQ(0x04, chip.regs[kRxb0Ctrl]); + EXPECT_EQ(0x00, chip.regs[kRxb1Ctrl]); + // Reset does not initialize these in the fake; configuration must set every filter and + // both complete masks, including the standard-frame data-byte mask bits. + for (const uint8_t base : {0x00, 0x04, 0x08, 0x10, 0x14, 0x18, 0x20, 0x24}) { + for (uint8_t i = 0; i < 4; ++i) { + EXPECT_EQ(0, chip.regs[base + i]) << "register " << int(base + i); + } + } + for (uint8_t i = 0; i < 8; ++i) { + EXPECT_EQ(0x00, chip.regs[kTxb2Data + i]); + } + EXPECT_TRUE(can.lastSelfTest().passed()); + EXPECT_EQ(Mcp2515CanTransport::kSelfTestFrames, can.lastSelfTest().frames); + EXPECT_TRUE(chip.transmitted.empty()); // the self-test never reaches the bus + EXPECT_EQ(0u, can.linkFaults()); +} + +TEST(Mcp2515Transport, BeginAgainAtTheSameBitrateIsANoOp) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const uint32_t transfers = chip.transfers; + EXPECT_TRUE(can.begin(500000)); + EXPECT_EQ(transfers, chip.transfers); +} + +TEST(Mcp2515Transport, RefusesAMissingChipAnUnreachableBitrateAndABrokenLink) +{ + FakeMcp2515 absent; + absent.present = false; + Mcp2515CanTransport no_chip(absent, 8000000); + EXPECT_FALSE(no_chip.begin(500000)); + EXPECT_FALSE(no_chip.isOpen()); + EXPECT_EQ(1u, no_chip.linkFaults()); + + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + EXPECT_FALSE(can.begin(1000000)); + EXPECT_FALSE(can.isOpen()); + + FakeMcp2515 broken; + broken.link = FakeMcp2515::Link::kBroken; + Mcp2515CanTransport noisy(broken, 8000000); + EXPECT_FALSE(noisy.begin(500000)); + EXPECT_FALSE(noisy.isOpen()); + EXPECT_EQ(0x80, broken.mode()); // left off the bus +} + +TEST(Mcp2515Transport, ReceivesExactFramesFromBothBuffersInOrder) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + + const Frame reply = makeFrame(3, {0x31, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x38}); + const Frame ones = makeFrame(0x7FF, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}); + ASSERT_TRUE(chip.deliver(reply)); + ASSERT_TRUE(chip.deliver(ones)); // RXB0 full: rolls over into RXB1 + ASSERT_TRUE(can.receive(got, 0)); + expectSame(reply, got); + ASSERT_TRUE(can.receive(got, 0)); + expectSame(ones, got); + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_FALSE(chip.interruptAsserted()); + + const Frame short_frame = makeFrame(0x123, {0x80}); + const Frame empty = makeFrame(0x001, {}); + ASSERT_TRUE(chip.deliver(short_frame)); + ASSERT_TRUE(can.receive(got, 0)); + expectSame(short_frame, got); + ASSERT_TRUE(chip.deliver(empty)); + ASSERT_TRUE(can.receive(got, 0)); + expectSame(empty, got); + EXPECT_EQ(4u, can.busLoad().totalFrames()); +} + +TEST(Mcp2515Transport, KeepsArrivalOrderWhenAFrameLandsAfterFlagClear) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame a = makeFrame(1, {0x31, 0x01}); + const Frame b = makeFrame(3, {0x31, 0x03}); + const Frame c = makeFrame(4, {0x31, 0x04}); + const Frame d = makeFrame(5, {0x31, 0x05}); + ASSERT_TRUE(chip.deliver(a)); + ASSERT_TRUE(chip.deliver(b)); // RXB1 + // C lands in RXB0 as soon as A is read out of it, while B still waits in RXB1; D then rolls + // over into RXB1 once B is read. + chip.arriving = {c, d}; + for (const Frame & expected : {a, b, c, d}) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_TRUE(chip.arriving.empty()); +} + +TEST(Mcp2515Transport, KeepsArrivalOrderWhenAFrameRollsOverWhileTheOtherBufferIsRead) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame a = makeFrame(1, {0x31, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}); + const Frame b = makeFrame(3, {0x31, 0x03}); + const Frame c = makeFrame(4, {0x31, 0x04}); + ASSERT_TRUE(chip.deliver(a)); + bool injected = false; + chip.on_read = [&](const uint8_t address) { + if (!injected && address == kRxb0Sidh + 5) { + injected = true; + // RXB1 was empty when the read of A began; A still locks RXB0, so B rolls into RXB1 + // and C takes RXB0 the moment A is released. + EXPECT_TRUE(chip.deliver(b)); + chip.arriving = {c}; + } + }; + for (const Frame & expected : {a, b, c}) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + EXPECT_TRUE(injected); + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_TRUE(chip.arriving.empty()); +} + +TEST(Mcp2515Transport, PendingBuffersStayLockedDuringRegisterReads) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame a = makeFrame(1, {0x31, 1, 2, 3, 4, 5, 6, 7}); + const Frame b = makeFrame(3, {0xF5, 0x02, 0xFA}); + ASSERT_TRUE(chip.deliver(a)); + ASSERT_TRUE(chip.deliver(b)); + bool injected = false; + chip.on_read = [&](const uint8_t address) { + if (!injected && address == kRxb0Sidh + 5) { + injected = true; + EXPECT_EQ(0x03, chip.regs[kCanIntF] & 0x03); + EXPECT_FALSE(chip.deliver(makeFrame(5, {0xF5, 0x02, 0xFC}))); + } + }; + for (const Frame & expected : {a, b}) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + EXPECT_TRUE(injected); + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_GT(can.receiveOverflows(), 0u); +} + +TEST(Mcp2515Fake, DebugReceiveModeExposesErroredCanMessages) +{ + FakeMcp2515 chip; + chip.regs[kRxb0Ctrl] = 0x64; + chip.regs[kRxb1Ctrl] = 0x60; + // Recorded at 1793447327.347629 in the bench host log. Its MKS checksum passes; + // the log does not establish whether the original CAN message had a protocol error. + const Frame partial = makeFrame(5, {0x31, 0x02, 0xFC, 0xFF, 0xFF, 0xE9, 0x16, 0x31}); + mks::Message message; + ASSERT_EQ(mks::ParseResult::kOk, mks::parseFrame(partial, message)); + ASSERT_TRUE(chip.deliver(partial, 0, false)); + ASSERT_TRUE(chip.deliver(partial, 0, false)); + EXPECT_EQ(0x03, chip.regs[kCanIntF] & 0x03); +} + +TEST(Mcp2515Transport, RejectsErroredCanMessagesEvenWithValidMksChecksums) +{ + for (const bool rollover : {false, true}) { + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame good = makeFrame(5, {0x31, 0xFF, 0xFF, 0xFF, 0xFF, 0xE9, 0x16, 0x31}); + const Frame partial = makeFrame(5, {0x31, 0x02, 0xFC, 0xFF, 0xFF, 0xE9, 0x16, 0x31}); + if (rollover) { + ASSERT_TRUE(chip.deliver(good)); + } + ASSERT_FALSE(chip.deliver(partial, 0, false)); + ASSERT_TRUE(chip.deliver(good)); + for (int i = 0; i < (rollover ? 2 : 1); ++i) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(good, got); + } + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_GT(can.errorEvents(), 0u); + EXPECT_EQ(1, can.receiveErrorCount()); + } +} + +TEST(Mcp2515Transport, DetectsAndRepairsUnexpectedDebugReceiveMode) +{ + for (const uint8_t ctrl : {kRxb0Ctrl, kRxb1Ctrl}) { + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + chip.regs[ctrl] |= 0x60; + const uint32_t until = chip.now_ms + 3 * Mcp2515CanTransport::kLinkCheckPeriodMs; + while (chip.now_ms < until) { + can.service(); + } + EXPECT_GE(can.linkFaults(), 2u); + EXPECT_EQ(1u, can.restarts()); + EXPECT_EQ(0, chip.regs[kRxb0Ctrl] & 0x60); + EXPECT_EQ(0, chip.regs[kRxb1Ctrl] & 0x60); + } +} + +TEST(Mcp2515Transport, ReceiveStatusBitsDoNotTriggerLinkFaults) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + chip.regs[kRxb0Ctrl] |= 0x0B; // RXRTR, BUKT1, FILHIT0 + chip.regs[kRxb1Ctrl] |= 0x0F; // RXRTR, FILHIT + const uint32_t until = chip.now_ms + 3 * Mcp2515CanTransport::kLinkCheckPeriodMs; + while (chip.now_ms < until) { + can.service(); + } + EXPECT_EQ(0u, can.linkFaults()); + EXPECT_EQ(0u, can.restarts()); +} + +TEST(Mcp2515Transport, VerifiesEveryFilterAndMaskByteBeforeJoiningTheBus) +{ + for (const uint8_t base : {0x00, 0x04, 0x08, 0x10, 0x14, 0x18, 0x20, 0x24}) { + for (uint8_t i = 0; i < 4; ++i) { + FakeMcp2515 chip; + chip.on_read = [&](const uint8_t address) { + if (address == base + i) { + chip.regs[address] |= 0x01; + } + }; + Mcp2515CanTransport can(chip, 8000000); + EXPECT_FALSE(can.begin(500000)) << "register " << int(base + i); + EXPECT_EQ(0x80, chip.mode()); + EXPECT_TRUE(chip.transmitted.empty()); + EXPECT_GT(can.linkFaults(), 0u); + } + } +} + +TEST(Mcp2515Transport, ServiceQueuesFramesBeyondTheChipsTwoBuffers) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + std::vector sent; + for (uint8_t n = 0; n < Mcp2515CanTransport::kReceiveQueueCapacity + 2; n += 2) { + for (uint8_t k = 0; k < 2; ++k) { + sent.push_back(makeFrame(static_cast(0x100 + n + k), {n, k})); + ASSERT_TRUE(chip.deliver(sent.back())); + } + can.service(); + } + // The queue is full and the chip holds the last two; one more frame is lost and counted. + EXPECT_TRUE(chip.interruptAsserted()); + EXPECT_FALSE(chip.deliver(makeFrame(0x7FF, {}))); + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_EQ(1u, can.receiveOverflows()); + for (const Frame & expected : sent) { + Frame got; + ASSERT_TRUE(can.receive(got, 0)); + expectSame(expected, got); + } + Frame got; + EXPECT_FALSE(can.receive(got, 0)); +} + +TEST(Mcp2515Transport, DropsExtendedAndRemoteFrames) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + ASSERT_TRUE(chip.deliver(makeFrame(5, {1, 2}), 0x08)); // IDE + ASSERT_TRUE(chip.deliver(makeFrame(6, {}), 0x10)); // SRR: standard remote frame + Frame got; + EXPECT_FALSE(can.receive(got, 0)); + EXPECT_EQ(2u, can.droppedFrames()); + EXPECT_FALSE(chip.interruptAsserted()); +} + +TEST(Mcp2515Transport, SendsInOrderThroughOneBuffer) +{ + FakeMcp2515 chip; + chip.auto_ack = false; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + const Frame first = makeFrame(1, {0x31, 0x32}); + const Frame second = makeFrame(4, {0xF5, 0x01, 0x2C, 0x02, 0x00, 0x40, 0x00, 0x60}); + ASSERT_TRUE(can.send(first)); + EXPECT_FALSE(can.send(second)); // TXB0 still busy + chip.acknowledge(); + ASSERT_TRUE(can.send(second)); + chip.acknowledge(); + ASSERT_EQ(2u, chip.transmitted.size()); + expectSame(first, chip.transmitted[0]); + expectSame(second, chip.transmitted[1]); + EXPECT_EQ(0u, can.failedWrites()); + + Frame invalid; + invalid.id = 0x800; + EXPECT_FALSE(can.send(invalid)); +} + +TEST(Mcp2515Transport, AbortsAFrameNobodyAcknowledges) +{ + FakeMcp2515 chip; + chip.auto_ack = false; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + ASSERT_TRUE(can.send(makeFrame(1, {0xF5, 0x00}))); + const uint32_t sent_at = chip.now_ms; + while (chip.now_ms - sent_at < Mcp2515CanTransport::kTransmitTimeoutMs + 5) { + can.service(); + } + EXPECT_EQ(1u, chip.aborted); + EXPECT_EQ(1u, can.failedWrites()); + chip.acknowledge(); // the drive powers up: the stale frame must not go out now + EXPECT_TRUE(chip.transmitted.empty()); + chip.auto_ack = true; + ASSERT_TRUE(can.send(makeFrame(1, {0x31, 0x32}))); + ASSERT_EQ(1u, chip.transmitted.size()); +} + +TEST(Mcp2515Transport, CountsErrorStatesAndReceiveOverflows) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + chip.regs[kTec] = 128; + chip.regs[kEflg] = 0x15 | 0x40; // error passive and warning, RXB0 overflowed + for (int i = 0; i < 30; ++i) { + can.service(); + } + EXPECT_EQ(1u, can.errorEvents()); + EXPECT_EQ(1u, can.receiveOverflows()); + EXPECT_EQ(128, can.transmitErrorCount()); + EXPECT_EQ(0x15, can.errorFlags()); + EXPECT_EQ(0x15, chip.regs[kEflg]); // overflow flag cleared, state flags are the chip's +} + +TEST(Mcp2515Transport, RestartsAChipThatLostItsConfiguration) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + // A brownout resets the chip: configuration mode, timing registers cleared. + chip.select(); + chip.transfer(0xC0); + chip.deselect(); + ASSERT_EQ(0x80, chip.mode()); + const uint32_t until = chip.now_ms + 3 * Mcp2515CanTransport::kLinkCheckPeriodMs; + while (chip.now_ms < until) { + can.service(); + } + EXPECT_GE(can.linkFaults(), 2u); + EXPECT_EQ(1u, can.restarts()); + EXPECT_TRUE(can.isOpen()); + EXPECT_EQ(0x00, chip.mode()); + EXPECT_EQ(0x00, chip.regs[0x2A]); + EXPECT_EQ(0x91, chip.regs[0x29]); +} + +TEST(Mcp2515Transport, EndLeavesTheBus) +{ + FakeMcp2515 chip; + Mcp2515CanTransport can(chip, 8000000); + ASSERT_TRUE(can.begin(500000)); + can.end(); + EXPECT_FALSE(can.isOpen()); + EXPECT_EQ(0x80, chip.mode()); + EXPECT_FALSE(can.send(makeFrame(1, {0x31, 0x32}))); + for (int i = 0; i < 300; ++i) { + can.service(); + } + EXPECT_EQ(0x80, chip.mode()); +} + +} // namespace +} // namespace waybionic diff --git a/waybionic_rviz_plugins/CMakeLists.txt b/waybionic_rviz_plugins/CMakeLists.txt index 9e133adf..50a6f8f1 100644 --- a/waybionic_rviz_plugins/CMakeLists.txt +++ b/waybionic_rviz_plugins/CMakeLists.txt @@ -43,10 +43,16 @@ target_include_directories(${PROJECT_NAME} PUBLIC target_link_libraries(${PROJECT_NAME} Qt5::Widgets) ament_target_dependencies(${PROJECT_NAME} ${THIS_PACKAGE_INCLUDE_DEPENDS}) +add_executable(ground_station_rviz src/ground_station_rviz.cpp) +target_compile_features(ground_station_rviz PRIVATE cxx_std_17) +target_link_libraries(ground_station_rviz Qt5::Widgets) +ament_target_dependencies(ground_station_rviz rclcpp rviz_common) + if(APPLE) # RoboStack exports optional Python type-support dylibs through RViz targets. # Do not retain those unused dylibs in this C++-only plugin. target_link_options(${PROJECT_NAME} PRIVATE "LINKER:-dead_strip_dylibs") + target_link_options(ground_station_rviz PRIVATE "LINKER:-dead_strip_dylibs") endif() pluginlib_export_plugin_description_file(rviz_common plugin_description.xml) @@ -59,6 +65,10 @@ install( RUNTIME DESTINATION bin ) +install(TARGETS ground_station_rviz + DESTINATION lib/${PROJECT_NAME} +) + install( DIRECTORY include/ DESTINATION include/${PROJECT_NAME} diff --git a/waybionic_rviz_plugins/README.md b/waybionic_rviz_plugins/README.md index 3044505e..ba759dab 100644 --- a/waybionic_rviz_plugins/README.md +++ b/waybionic_rviz_plugins/README.md @@ -2,6 +2,11 @@ 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. +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: - No motor commands from this package. diff --git a/waybionic_rviz_plugins/src/ground_station_rviz.cpp b/waybionic_rviz_plugins/src/ground_station_rviz.cpp new file mode 100644 index 00000000..1d90eebf --- /dev/null +++ b/waybionic_rviz_plugins/src/ground_station_rviz.cpp @@ -0,0 +1,61 @@ +#include +#include +#include +#include +#include + +#include +#include + +#include "rclcpp/rclcpp.hpp" +#include "rviz_common/logging.hpp" +#include "rviz_common/ros_integration/ros_client_abstraction.hpp" +#include "rviz_common/visualization_frame.hpp" +#include "rviz_common/visualizer_app.hpp" + +int main(int argc, char ** argv) +{ + auto arguments = rclcpp::remove_ros_arguments(argc, argv); + // RViz's Ogre renderer needs X11 on Wayland unless the operator overrides Qt. + if (qEnvironmentVariable("XDG_SESSION_TYPE") == "wayland" && + !qEnvironmentVariableIsSet("QT_QPA_PLATFORM") && + std::find(arguments.begin(), arguments.end(), "-platform") == arguments.end()) + { + qputenv("QT_QPA_PLATFORM", "xcb"); + } + std::vector qt_arguments; + for (auto & argument : arguments) { + qt_arguments.push_back(argument.data()); + } + int qt_argc = static_cast(qt_arguments.size()); + qt_arguments.push_back(nullptr); + QApplication application(qt_argc, qt_arguments.data()); + const auto logger = rclcpp::get_logger("rviz2"); + rviz_common::set_logging_handlers( + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_DEBUG(logger, "%s", message.c_str()); + }, + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_INFO(logger, "%s", message.c_str()); + }, + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_WARN(logger, "%s", message.c_str()); + }, + [logger](const std::string & message, const std::string &, size_t) { + RCLCPP_ERROR(logger, "%s", message.c_str()); + }); + rviz_common::VisualizerApp visualizer( + std::make_unique()); + visualizer.setApp(&application); + if (!visualizer.init(argc, argv)) { + return EXIT_FAILURE; + } + for (auto * widget : QApplication::topLevelWidgets()) { + if (auto * frame = qobject_cast(widget)) { + frame->showMaximized(); + return application.exec(); + } + } + qCritical("RViz initialized without a visualization window"); + return EXIT_FAILURE; +} diff --git a/waybionic_teleop/config/arm_drives.yaml b/waybionic_teleop/config/arm_drives.yaml index 9a4a448e..4ac48950 100644 --- a/waybionic_teleop/config/arm_drives.yaml +++ b/waybionic_teleop/config/arm_drives.yaml @@ -8,10 +8,12 @@ sim_arm_drives: ros__parameters: rate_hz: 120.0 - # Set every drive to 1 Mbit/s first (mks_setup, or CanRate on its screen; MKS ships 500k): - # six drives at 120 Hz load the bus about 30% at 1 Mbit/s and 60% at 500 kbit/s. - bitrate: 1000000 - # The carrier's USB serial speed (carrier_bridge.ino); only used with interface slcan. + # Every drive and the carrier must run CAN at this rate. MKS drives ship at 500k (mks_setup or + # CanRate on a drive's screen changes it), and the carrier's MCP2515 module, with its 8 MHz + # crystal, runs 500 kbit/s at most. Six drives at 120 Hz load the bus about 60% at 500 kbit/s. + bitrate: 500000 + # The carrier's link is native USB, which ignores the baud rate, except that 1200 hands the + # port back for an upload (UsbHandBack.h). Only used with interface slcan. tty_baudrate: 1000000 # Teleop ramps the speed. A steep drive ramp keeps the drives in step with each other: a # gentle one gives every drive the same rpm/s, so the one that must change most falls behind. @@ -54,24 +56,25 @@ sim_arm_drives: gear_ratio: 26.0 joints: [joint_2] factors: [1.0] - # SERVO42D + # SERVO42D. Its motor counts down as the elbow turns the URDF's positive way (bench arm). elbow: can_id: 3 gear_ratio: 26.0 joints: [joint_3] - factors: [1.0] + factors: [-1.0] # SERVO42D, left side gear: pitch minus roll wrist_left: can_id: 4 gear_ratio: 3.0 joints: [joint_4, joint_5] factors: [1.0, -1.0] - # SERVO42D, right side gear: pitch plus roll + # SERVO42D, right side gear: pitch plus roll. Its motor counts the opposite way to the left + # one (bench arm), so pitch turns the two encoders opposite ways and roll the same way. wrist_right: can_id: 5 gear_ratio: 3.0 joints: [joint_4, joint_5] - factors: [1.0, 1.0] + factors: [-1.0, -1.0] tool: can_id: 6 gear_ratio: 1.0 diff --git a/waybionic_teleop/config/xbox_teleop.yaml b/waybionic_teleop/config/xbox_teleop.yaml index 8af6fd18..10c18b31 100644 --- a/waybionic_teleop/config/xbox_teleop.yaml +++ b/waybionic_teleop/config/xbox_teleop.yaml @@ -22,14 +22,19 @@ xbox_teleop: tilt_up_button: dpad_right tilt_down_button: dpad_left groups: [base, upper, cartesian, incision] + # Left stick right turns joint_1 positive (counter-clockwise seen from above), which is to + # the right of an operator facing the arm. Right stick up lifts the elbow (joint_3 negative). base: joints: [joint_1, joint_2, joint_3] axes: [left_x, left_y, right_y] - scales: [1.0, 1.0, 1.0] + scales: [-1.0, 1.0, -1.0] + # Left stick up lifts the elbow (joint_3 negative), as in the base group. Right stick up tips + # the wrist up (joint_4 negative), and right turns the wrist roll positive (counter-clockwise + # from above at the zero pose), as the operator preferred on the bench arm. upper: joints: [joint_2, joint_3, joint_4, joint_5] axes: [left_x, left_y, right_y, right_x] - scales: [1.0, 1.0, 1.0, 1.0] + scales: [1.0, -1.0, -1.0, -1.0] # Straight tool-tip moves in base_link: forward (x), left (y), up (z), then tool roll. The # lock button keeps only the strongest of x, y and z; the tilt buttons pivot the tool about # its tip. diff --git a/waybionic_teleop/package.xml b/waybionic_teleop/package.xml index fb6395f0..1bc5c0bc 100644 --- a/waybionic_teleop/package.xml +++ b/waybionic_teleop/package.xml @@ -20,6 +20,8 @@ python3-can python3-serial + + python3-yaml ament_flake8 ament_pep257 diff --git a/waybionic_teleop/test/conftest.py b/waybionic_teleop/test/conftest.py index 2885590f..01c0267b 100644 --- a/waybionic_teleop/test/conftest.py +++ b/waybionic_teleop/test/conftest.py @@ -29,7 +29,9 @@ def write(self, data): raise OSError(6, 'Device not configured') self.writes.append(bytes(data)) for line in bytes(data).split(b'\r')[:-1] if self.answering else (): - if line[:1] != b't': + if line == b'V': + self.inbox += b'V0100\r' + elif line[:1] != b't': # A command, or the empty line after a frame. self.inbox += b'\r' elif line in self.refuse: @@ -47,6 +49,20 @@ def usb_carrier(): return CarrierPort +# The bench arm: the shoulder motor is not wired and the shoulder is fixed upright; no tool. +BENCH_PROFILE = """\ +fitted_drives: [base_yaw, elbow, wrist_left, wrist_right] +locked_joints: {joint_2: 0.0, tool_grip: 0.0} +""" + + +@pytest.fixture +def bench_profile(tmp_path): + path = tmp_path / 'arm_profile.yaml' + path.write_text(BENCH_PROFILE, encoding='utf-8') + return str(path) + + def flatten(values, prefix=''): flat = {} for key, value in values.items(): diff --git a/waybionic_teleop/test/test_arm_profile.py b/waybionic_teleop/test/test_arm_profile.py new file mode 100644 index 00000000..1d8c39a1 --- /dev/null +++ b/waybionic_teleop/test/test_arm_profile.py @@ -0,0 +1,73 @@ +"""An arm profile says which drives one arm has and holds still the joints it lacks.""" + +import pytest + +from waybionic_teleop.arm_profile import ( + ArmProfile, + fit_drive_parameters, + load_profile, + profile_from_dict, +) + + +def test_no_profile_fits_every_drive(parameters): + params = parameters('arm_drives.yaml', 'sim_arm_drives') + assert load_profile('') == ArmProfile() + assert fit_drive_parameters(params, ArmProfile()) == params + + +def test_the_bench_profile_runs_four_drives_and_holds_the_shoulder(parameters, bench_profile): + params = parameters('arm_drives.yaml', 'sim_arm_drives') + profile = load_profile(bench_profile) + assert profile.locked_joints == {'joint_2': 0.0, 'tool_grip': 0.0} + fitted = fit_drive_parameters(params, profile) + assert fitted['drives'] == ['base_yaw', 'elbow', 'wrist_left', 'wrist_right'] + assert params['drives'][1] == 'shoulder' + + +@pytest.mark.parametrize('data, message', [ + ([], 'must be a mapping'), + ({'fitted': ['base_yaw']}, 'unknown keys'), + ({'fitted_drives': []}, 'distinct drive names'), + ({'fitted_drives': ['elbow', 'elbow']}, 'distinct drive names'), + ({'fitted_drives': 'elbow'}, 'distinct drive names'), + ({'locked_joints': ['joint_2']}, 'map joint names'), + ({'locked_joints': {'joint_2': float('nan')}}, 'finite angle'), + ({'locked_joints': {'joint_2': True}}, 'finite angle'), + ({'locked_joints': {'joint_2': 'up'}}, 'finite angle'), +]) +def test_a_malformed_profile_is_refused(data, message): + with pytest.raises(ValueError, match=message): + profile_from_dict(data) + + +def test_an_unreadable_profile_is_refused(tmp_path): + with pytest.raises(ValueError, match='cannot read'): + load_profile(str(tmp_path / 'missing.yaml')) + broken = tmp_path / 'broken.yaml' + broken.write_text('fitted_drives: [base_yaw\n', encoding='utf-8') + with pytest.raises(ValueError, match='cannot read'): + load_profile(str(broken)) + + +def test_an_empty_profile_file_fits_every_drive(tmp_path): + empty = tmp_path / 'empty.yaml' + empty.write_text('', encoding='utf-8') + assert load_profile(str(empty)) == ArmProfile() + + +@pytest.mark.parametrize('profile, message', [ + # Nothing would report where the shoulder is. + (ArmProfile(('base_yaw', 'elbow', 'wrist_left', 'wrist_right', 'tool')), r"\['joint_2'\]"), + (ArmProfile(('base_yaw', 'elbow', 'gripper')), 'lacks'), + # A mistyped joint would only show later, as every teleop command being refused. + (ArmProfile(None, {'joint_9': 0.0}), r"locks joints \['joint_9'\] that the arm map lacks"), + # A fitted drive would move a joint the model holds still. + (ArmProfile(None, {'joint_1': 0.0}), 'moved by fitted drives'), + # One wrist motor moves both wrist joints, so neither can be locked while it is fitted. + (ArmProfile(('base_yaw', 'shoulder', 'elbow', 'wrist_left', 'tool'), {'joint_4': 0.0}), + 'moved by fitted drives'), +]) +def test_a_profile_that_does_not_match_the_map_is_refused(parameters, profile, message): + with pytest.raises(ValueError, match=message): + fit_drive_parameters(parameters('arm_drives.yaml', 'sim_arm_drives'), profile) diff --git a/waybionic_teleop/test/test_can_drives.py b/waybionic_teleop/test/test_can_drives.py index ebec04bf..e126d818 100644 --- a/waybionic_teleop/test/test_can_drives.py +++ b/waybionic_teleop/test/test_can_drives.py @@ -26,7 +26,7 @@ from waybionic_teleop import carrier, mks_can, slcan_bus from waybionic_teleop.can_bus import CanBus from waybionic_teleop.mks_drive_sim import serve -from waybionic_teleop.sim_arm_drives_node import QUIET_BEFORE_ZERO_S, SimArmDrives +from waybionic_teleop.sim_arm_drives_node import HOLD_RPM, QUIET_BEFORE_ZERO_S, SimArmDrives from waybionic_teleop.sim_drives import SimulatedServo BITRATE = 1000000 @@ -101,6 +101,19 @@ def positions(node): return node.map.to_positions(node.counts) +def assert_holding(node): + """Each drive on the bus is stopped, or runs on only to its hold near where it stopped.""" + # Two ticks at full speed past the count, and a count of rounding. + reach = 2 * node.period * node.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + 31 + for index, drive in enumerate(node.map.drives): + servo = node.bus.drives.get(drive.can_id) + if servo is None: + continue + assert servo.target in (None, node.held[index]) + assert (servo.rpm == 0.0 if servo.target is None + else abs(servo.target - servo.axis) <= reach and servo.speed <= HOLD_RPM) + + def press_start(node): """Load the URDF limits, then release and press Start the way teleop reports it.""" node.on_description(String(data=URDF)) @@ -111,7 +124,7 @@ def press_start(node): def command(node, speed=1.0, **targets): """Refresh the enable and send one complete command toward the named joint targets.""" current = positions(node) - goal = {**(node.commanded or current), **targets} + goal = {**(node.commanded or current), **node.locked, **targets} velocities = [math.copysign(speed, goal[joint] - current[joint]) if joint in targets else 0.0 for joint in goal] node.on_enabled(Bool(data=True)) @@ -264,8 +277,9 @@ def test_the_host_drives_mks_servos_over_can(make_node): assert node.authorized, node.stop_reason assert set(node.limits) == set(node.map.joints) assert move(node, executor, joint_1=0.3, joint_4=0.2) - # Wrist pitch turns both differential motors the same way, through 3:1 belts. - assert servos[4].axis == pytest.approx(servos[5].axis) + # Wrist pitch turns the two differential motors through 3:1 belts, the right one + # mounted to count the opposite way. + assert servos[4].axis == pytest.approx(-servos[5].axis) assert servos[4].axis == pytest.approx( 0.2 * node.map.drives[3].gear_ratio / (2 * math.pi) * mks_can.COUNTS_PER_REV, abs=1.0) @@ -312,6 +326,9 @@ def write(self, data): for reply in servo.step(now - self.last)] self.last = now for line in bytes(data).split(b'\r')[:-1]: + if line == b'V': + self.output += b'V0100\r' + continue if line[:1] != b't': # C, Sn, O and an empty line get \r; a frame the carrier puts on the bus, nothing. self.open = {b'O': True, b'C': False}.get(line, self.open) @@ -357,7 +374,7 @@ def test_the_host_drives_the_arm_through_the_carrier(make_node, carrier_port, mo node, executor = make_node(interface='slcan', channel='/dev/cu.usbmodem1101', drives=ARM_DRIVES) # The carrier opens at the drives' bit rate, and the monitor waits for its first report. - assert port.writes[0] == b'C\rS8\rO\r' + assert port.writes[0] == b'V\rC\rS6\rO\r' assert carrier_row(node, monkeypatch).level == DiagnosticStatus.WARN port.flags = carrier.ESTOP_WIRED assert spin_until(executor, lambda: all(state == 'ready' for state in node.state)) @@ -395,7 +412,7 @@ def pressed_mid_move(): assert 'USB link lost' in carrier_row(node, monkeypatch).message port.unplugged = False assert spin_until(executor, lambda: not any(node.lost)) - assert node.bus.reopens == 1 and port.writes.count(b'C\rS8\rO\r') == 2 + assert node.bus.reopens == 1 and port.writes.count(b'V\rC\rS6\rO\r') == 2 assert node.bus.refused == 0 @@ -431,6 +448,35 @@ def busy(can_id, data): assert node.bus.refused > 0 and node.bus.errors == 0 and node.bus_errors == 0 +def test_an_arm_without_its_shoulder_drive_zeroes_and_moves_through_the_carrier( + make_node, carrier_port, monkeypatch, bench_profile): + port = carrier_port + # Only the drives the bench arm has wired answer; a frame for any other fails the test. + del port.servos[2] + port.flags = carrier.ESTOP_WIRED + node, executor = make_node(interface='slcan', channel='/dev/cu.usbmodem1101', + arm_profile=bench_profile) + states = [] + monkeypatch.setattr(node.state_publisher, 'publish', states.append) + assert spin_until(executor, lambda: all(state == 'ready' for state in node.state)) + assert zero(node).success + assert spin_until(executor, lambda: node.commanded is not None) + press_start(node) + assert node.authorized, node.stop_reason + assert move(node, executor, joint_1=0.3, joint_4=0.2) + assert dict(zip(states[-1].name, states[-1].position))['joint_2'] == 0.0 + reports = [] + monkeypatch.setattr(node.diagnostics_publisher, 'publish', reports.append) + node.report() + assert all(row.level == DiagnosticStatus.OK for row in reports[-1].status), [ + (row.name, row.message) for row in reports[-1].status + if row.level != DiagnosticStatus.OK] + sent = {int(line[1:4], 16) for data in port.writes for line in data.split(b'\r') + if line[:1] == b't'} + assert sent == {1, 3, 4, 5} + assert node.bus.errors == 0 and node.bus.refused == 0 + + def test_a_real_bus_needs_a_urdf_limit_for_every_drive_joint(make_node, mock_drives): channel, servos = mock_drives sim, _ = make_node() @@ -482,7 +528,7 @@ def commanding_until_lost(): assert spin_until(executor, commanding_until_lost) assert node.commanded is None and not node.zeroed[2] and not node.authorized # Every other drive was told to stop where it is. - assert all(servo.target is None for servo in node.bus.drives.values()) + assert_holding(node) node.bus.drives[3] = elbow assert spin_until(executor, lambda: not node.lost[2] and not node.unconfirmed[2]) @@ -498,6 +544,29 @@ def commanding_until_lost(): assert node.authorized +def test_a_relaunch_keeps_the_zero_while_the_drives_stay_powered( + make_node, mock_drives, tmp_path): + channel, servos = mock_drives + saved = tmp_path / 'drive_zero.yaml' + servos[1].axis = mks_can.COUNTS_PER_REV / 2 + node, executor = make_node(interface='virtual', channel=channel, drives=ARM_DRIVES, + zero_state=str(saved)) + assert spin_until(executor, lambda: all(state == 'ready' for state in node.state)) + assert zero(node).success + assert spin_until(executor, saved.exists) + # Pushed by hand while the station is down; raw and zeroed counts move alike. + servos[1].axis = 1234.0 + relaunched, executor = make_node(interface='virtual', channel=channel, drives=ARM_DRIVES, + zero_state=str(saved)) + assert not any(relaunched.zeroed) + assert spin_until(executor, lambda: all(relaunched.zeroed)) + assert spin_until(executor, lambda: relaunched.commanded is not None) + assert relaunched.counts[0] == 1234 + press_start(relaunched) + assert relaunched.authorized, relaunched.stop_reason + assert relaunched.bus.errors == 0 and relaunched.bus_errors == 0 + + def test_commands_that_stop_mid_move_stop_the_drives(make_node): node, executor = make_node(max_rpm=6) assert spin_until(executor, lambda: node.commanded is not None) @@ -567,7 +636,7 @@ def test_a_command_without_speeds_stops_the_drives(make_node): targets = dict(node.commanded) node.on_command(JointState(name=list(targets), position=list(targets.values()))) assert not node.authorized and node.rejected == 1 - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + assert_holding(node) stopped = positions(node)['joint_1'] spin_for(executor, 0.5) assert positions(node)['joint_1'] == pytest.approx(stopped, abs=1e-3) @@ -625,7 +694,7 @@ def test_an_empty_command_stops_the_drives_until_a_fresh_start(make_node): assert node.bus.drives[1].target is not None node.on_command(JointState()) assert not node.authorized and node.rejected == 1 - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + assert_holding(node) response = zero(node) assert not response.success and 'still arriving' in response.message # Neither an invalid nor a valid command moves the arm again without a fresh Start. @@ -633,7 +702,7 @@ def test_an_empty_command_stops_the_drives_until_a_fresh_start(make_node): command(node, joint_1=0.3) spin_for(executor, 0.1) assert not node.authorized - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + assert_holding(node) press_start(node) # 6 rpm turns the base 0.024 rad/s through its reducer. assert move(node, executor, joint_1=0.01) diff --git a/waybionic_teleop/test/test_carrier_usb.py b/waybionic_teleop/test/test_carrier_usb.py new file mode 100644 index 00000000..e58cc267 --- /dev/null +++ b/waybionic_teleop/test/test_carrier_usb.py @@ -0,0 +1,95 @@ +"""Handing the carrier's USB port back for an upload must pick the selected board's bridge.""" + +import importlib.util +from pathlib import Path +from types import SimpleNamespace + +import pytest + +SCRIPT = Path(__file__).resolve().parents[2] / 'scripts' / 'carrier_usb.py' + + +@pytest.fixture +def usb(): + spec = importlib.util.spec_from_file_location('carrier_usb', SCRIPT) + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class Port: + def __init__(self, device, pid, location): + self.device, self.vid, self.pid, self.location = device, 0x2341, pid, location + + +class Machine: + """USB ports that change when the carrier gives its port back after a few polls.""" + + def __init__(self, usb, ports, reenumerated, polls_until_bridge=3): + self.usb, self.ports, self.reenumerated = usb, list(ports), reenumerated + self.polls_until_bridge = polls_until_bridge + self.opened = [] + + def comports(self): + if self.opened: + self.polls_until_bridge -= 1 + if self.polls_until_bridge <= 0: + return self.reenumerated + return self.ports + + def serial(self): + link = SimpleNamespace(port=None, baudrate=None, dtr=None, close=lambda: None) + link.open = lambda: self.opened.append((link.port, link.baudrate, link.dtr)) + return link + + +@pytest.fixture +def machine(usb, monkeypatch): + def make(ports, reenumerated, **kwargs): + fake = Machine(usb, ports, reenumerated, **kwargs) + monkeypatch.setattr(usb.list_ports, 'comports', fake.comports) + monkeypatch.setattr(usb, 'Serial', fake.serial) + monkeypatch.setattr(usb.time, 'sleep', lambda seconds: None) + return fake + return make + + +def test_the_selected_carriers_own_bridge_is_returned_not_another_boards(usb, machine): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, '20-1') + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, '20-2') + own_bridge = Port('/dev/cu.usbmodem3301', usb.WIFI_BRIDGE_PID, '20-1') + fake = machine([carrier, other_bridge], [other_bridge, own_bridge]) + assert usb.upload_port('/dev/cu.usbmodem1101') == '/dev/cu.usbmodem3301' + assert fake.opened == [('/dev/cu.usbmodem1101', usb.HAND_BACK_BAUD, True)] + + +def test_the_bridge_may_keep_the_carriers_device_name(usb, machine): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, '20-1') + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, '20-2') + own_bridge = Port('/dev/cu.usbmodem1101', usb.WIFI_BRIDGE_PID, '20-1') + machine([carrier, other_bridge], [other_bridge, own_bridge]) + assert usb.upload_port('/dev/cu.usbmodem1101') == '/dev/cu.usbmodem1101' + + +def test_without_a_usb_location_only_a_new_bridge_counts(usb, machine): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, None) + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, None) + new_bridge = Port('/dev/cu.usbmodem3301', usb.WIFI_BRIDGE_PID, None) + machine([carrier, other_bridge], [other_bridge, new_bridge]) + assert usb.upload_port('/dev/cu.usbmodem1101') == '/dev/cu.usbmodem3301' + + +def test_a_bridge_already_there_is_never_taken_for_the_handed_back_one(usb, machine, monkeypatch): + carrier = Port('/dev/cu.usbmodem1101', usb.WIFI_NATIVE_PID, None) + other_bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, None) + machine([carrier, other_bridge], [other_bridge], polls_until_bridge=1) + monkeypatch.setattr(usb, 'HAND_BACK_TIMEOUT_S', 0.05) + with pytest.raises(SystemExit, match='did not hand USB back'): + usb.upload_port('/dev/cu.usbmodem1101') + + +def test_a_board_already_in_bridge_mode_is_used_as_it_is(usb, machine): + bridge = Port('/dev/cu.usbmodem2201', usb.WIFI_BRIDGE_PID, '20-2') + fake = machine([bridge], [bridge]) + assert usb.upload_port('/dev/cu.usbmodem2201') == '/dev/cu.usbmodem2201' + assert fake.opened == [] diff --git a/waybionic_teleop/test/test_collision.py b/waybionic_teleop/test/test_collision.py index b083c26b..4fafc204 100644 --- a/waybionic_teleop/test/test_collision.py +++ b/waybionic_teleop/test/test_collision.py @@ -88,11 +88,11 @@ def test_teleop_backs_out_of_a_collision_but_never_goes_deeper(parameters, check teleop.update(*sample(button), start, DT) teleop.update(*sample(), start, DT) for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] == pytest.approx(start['joint_3']) assert 'forearm_link: table' in teleop.blocked for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] < start['joint_3'] - 0.1 @@ -106,8 +106,8 @@ def test_teleop_stops_before_the_forearm_reaches_the_table(parameters, check): assert teleop.active_group.name == 'upper' stopped = False for _ in range(round(4.0 / DT)): - # Left stick up bends the elbow down towards the table. - teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) + # Left stick down bends the elbow down towards the table. + teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) if any(hit.endswith(': table') for hit in teleop.blocked): stopped = True # The published one-period lookahead stops with the refused step. @@ -117,7 +117,7 @@ def test_teleop_stops_before_the_forearm_reaches_the_table(parameters, check): assert stopped and teleop.targets['joint_3'] < LIMITS['joint_3'][1] - 0.05 elbow = teleop.targets['joint_3'] for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] < elbow - 0.05 @@ -157,7 +157,7 @@ def test_teleop_refuses_a_step_that_presses_one_contact_deeper(parameters, check teleop.update(*sample(button), start, DT) teleop.update(*sample(), start, DT) for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_y=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_y=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_3'] == start['joint_3'] assert teleop.blocked == ['forearm_link: table'] @@ -189,7 +189,7 @@ def test_teleop_refuses_to_slide_the_forearm_further_into_the_side_of_the_base( teleop.update(*sample('start'), start, DT) teleop.update(*sample(), start, DT) for _ in range(round(0.5 / DT)): - teleop.update(*sample(left_x=-1.0), dict(teleop.targets), DT) + teleop.update(*sample(left_x=1.0), dict(teleop.targets), DT) assert teleop.targets['joint_1'] == start['joint_1'] assert teleop.blocked == ['forearm_link: base_link'] # Raising the shoulder backs it out. diff --git a/waybionic_teleop/test/test_drive_map.py b/waybionic_teleop/test/test_drive_map.py index ff46283c..200df09f 100644 --- a/waybionic_teleop/test/test_drive_map.py +++ b/waybionic_teleop/test/test_drive_map.py @@ -32,9 +32,10 @@ def test_positions_round_trip_through_counts(arm_map): def test_wrist_differential_mixes_pitch_and_roll(arm_map): zero = dict.fromkeys(arm_map.joints, 0.0) # A quarter turn of the wrist is three quarters of a turn of each motor through the belts. + # The right motor counts the opposite way to the left one (bench arm). turn = 3 * COUNTS // 4 - assert arm_map.to_counts({**zero, 'joint_4': math.pi / 2})[3:5] == [turn, turn] - assert arm_map.to_counts({**zero, 'joint_5': math.pi / 2})[3:5] == [-turn, turn] + assert arm_map.to_counts({**zero, 'joint_4': math.pi / 2})[3:5] == [turn, -turn] + assert arm_map.to_counts({**zero, 'joint_5': math.pi / 2})[3:5] == [-turn, -turn] def test_gear_ratio_scales_counts_and_speed(): diff --git a/waybionic_teleop/test/test_frame_log.py b/waybionic_teleop/test/test_frame_log.py new file mode 100644 index 00000000..f2c2d9d6 --- /dev/null +++ b/waybionic_teleop/test/test_frame_log.py @@ -0,0 +1,83 @@ +import errno + +from waybionic_teleop import mks_can +from waybionic_teleop.frame_log import parse_line, RecordingBus +from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo + + +def test_every_frame_sent_received_or_refused_is_written_in_order(tmp_path): + path = tmp_path / 'frames.log' + sim = SimulatedBus([SimulatedServo(1)], 500000) + bus = RecordingBus(sim, str(path)) + assert bus.send(1, mks_can.read_encoder(1)) + reply = bus.receive() + assert reply is not None and bus.receive() is None + # Everything else, such as the simulated drives, still comes from the wrapped bus. + assert bus.drives is sim.drives and bus.frames == sim.frames + sim.take_refused = lambda: [(1, mks_can.stop(1, 0))] + assert bus.take_refused() == [(1, mks_can.stop(1, 0))] + bus.shutdown() + lines = [parse_line(line) for line in path.read_text().splitlines()] + assert [line[1:] for line in lines] == [ + ('tx', 1, mks_can.read_encoder(1)), + ('rx', *reply), + ('refused', 1, mks_can.stop(1, 0)), + ] + assert lines[0][0] <= lines[1][0] <= lines[2][0] + + +class FullDisk: + """A log file whose writes (and, with fail_close, final flush) fail like a full disk.""" + + def __init__(self, fail_write=True, fail_close=True): + self.fail_write, self.fail_close = fail_write, fail_close + self.writes = self.closes = 0 + + def write(self, text): + self.writes += 1 + if self.fail_write: + raise OSError(errno.ENOSPC, 'No space left on device') + + def close(self): + self.closes += 1 + if self.fail_close: + raise OSError(errno.ENOSPC, 'No space left on device') + + +def recording_bus_on(file, tmp_path, messages): + sim = SimulatedBus([SimulatedServo(1)], 500000) + bus = RecordingBus(sim, str(tmp_path / 'frames.log'), report=messages.append) + bus.file.close() + bus.file = file + sim.stopped = False + sim.shutdown = lambda: setattr(sim, 'stopped', True) + return bus, sim + + +def test_a_failing_log_never_interrupts_the_bus(tmp_path): + messages = [] + disk = FullDisk() + bus, sim = recording_bus_on(disk, tmp_path, messages) + for _ in range(3): + # The stops at shutdown go through send(), so a log error must not reach the caller. + assert bus.send(1, mks_can.read_encoder(1)) + assert bus.receive() is not None + assert disk.writes == 1 + assert len(messages) == 1 + assert 'No space left on device' in messages[0] and 'frames.log' in messages[0] + bus.shutdown() + assert sim.stopped and disk.closes == 1 + assert len(messages) == 1 + + +def test_a_log_that_cannot_be_closed_is_reported_without_blocking_shutdown(tmp_path): + messages = [] + disk = FullDisk(fail_write=False) + bus, sim = recording_bus_on(disk, tmp_path, messages) + assert bus.send(1, mks_can.read_encoder(1)) + assert messages == [] + bus.shutdown() + assert sim.stopped and disk.closes == 1 + assert len(messages) == 1 and 'No space left on device' in messages[0] + bus.shutdown() + assert disk.closes == 1 diff --git a/waybionic_teleop/test/test_mks_can.py b/waybionic_teleop/test/test_mks_can.py index 14f1b8dc..1cbb8b06 100644 --- a/waybionic_teleop/test/test_mks_can.py +++ b/waybionic_teleop/test/test_mks_can.py @@ -13,6 +13,7 @@ (mks_can.absolute_axis(1, 0, 0, 4), 'F5000004000000FA'), (mks_can.absolute_axis(1, 0, 0, 0), 'F5000000000000F6'), (mks_can.read_encoder(1), '3132'), + (mks_can.read_position_error(3), '393C'), (mks_can.set_mode(1), '820588'), (mks_can.enable(1), 'F301F5'), (mks_can.emergency_stop(1), 'F7F8'), @@ -52,6 +53,28 @@ def test_encoder_reply_preserves_the_signed_int48_limits(raw, expected): assert mks_can.encoder_value(bytes.fromhex(raw)) == expected +@pytest.mark.parametrize('raw, expected', [ + ('00000000', 0), + ('0000C800', 51200), + ('FFFF3800', -51200), + ('80000000', -(1 << 31)), + ('7FFFFFFF', (1 << 31) - 1), +]) +def test_position_error_preserves_the_signed_int32_value(raw, expected): + code, arguments = mks_can.parse( + 3, mks_can.frame(3, mks_can.READ_POSITION_ERROR, bytes.fromhex(raw))) + assert code == mks_can.READ_POSITION_ERROR + assert mks_can.position_error_value(arguments) == expected + if abs(expected) == 51200: + assert expected * 360 / mks_can.ERROR_COUNTS_PER_REV == (360 if expected > 0 else -360) + + +@pytest.mark.parametrize('length', [0, 1, 2, 3, 5, 6]) +def test_position_error_rejects_a_truncated_or_wrong_length_reply(length): + with pytest.raises(ValueError, match='four bytes'): + mks_can.position_error_value(bytes(length)) + + @pytest.mark.parametrize('can_id, data', [ (1, bytes.fromhex('3133')), (1, b'\x31'), diff --git a/waybionic_teleop/test/test_mks_setup.py b/waybionic_teleop/test/test_mks_setup.py index 39fe4562..a8b86858 100644 --- a/waybionic_teleop/test/test_mks_setup.py +++ b/waybionic_teleop/test/test_mks_setup.py @@ -1,8 +1,10 @@ """Bench set-up of the MKS drives: finding them, new CAN IDs and bit rates.""" +from collections import deque + import pytest -from waybionic_teleop import mks_can, mks_setup +from waybionic_teleop import carrier, mks_can, mks_setup from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo from waybionic_teleop.slcan_bus import SlcanBus @@ -103,3 +105,92 @@ def take_refused(): bus.send, bus.take_refused = busy_once, take_refused bus.drives[3].axis = 0x4000 assert mks_setup.scan(bus, [3]) == {3: 0x4000} + + +class ErrorReadBus: + """Supply recorded error replies without a simulation of motor torque.""" + + def __init__(self, replies): + self.replies = deque(replies) + self.sent = [] + self.closed = False + + def send(self, can_id, data): + self.sent.append((can_id, data)) + return True + + def step(self, dt): + pass + + def receive(self): + return self.replies.popleft() if self.replies else None + + def shutdown(self): + self.closed = True + + +def test_read_error_is_signed_and_sends_only_a_read(monkeypatch, capsys): + # CAN ID 3 + 39h + FFFF3800 has checksum 72h; -51200 is -360 motor degrees. + bus = ErrorReadBus([ + (0x7F0, bytes(8)), + (3, bytes.fromhex('39FFFF380072')), + ]) + monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) + mks_setup.main(['--interface', 'virtual', '--channel', 'fake', 'read-error', '3']) + assert bus.sent == [(3, bytes.fromhex('393C'))] + assert bus.closed + assert '-360.000000 motor deg (-51200 error counts)' in capsys.readouterr().out + + +@pytest.mark.parametrize('reply, reason', [ + (bytes.fromhex('39003C'), 'four bytes'), + (bytes.fromhex('39000000003D'), 'bad frame'), +]) +def test_read_error_reports_bad_replies_and_releases_the_bus(monkeypatch, reply, reason): + bus = ErrorReadBus([(3, reply)]) + monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) + with pytest.raises(SystemExit, match=reason): + mks_setup.main(['--interface', 'virtual', '--channel', 'fake', 'read-error', '3']) + assert bus.closed + assert bus.sent == [(3, bytes.fromhex('393C'))] + + +def test_read_error_reports_an_unanswered_request(): + bus = ErrorReadBus([]) + with pytest.raises(SystemExit, match='did not report its position error'): + mks_setup.read_error(bus, 3) + assert bus.sent == [(3, bytes.fromhex('393C'))] + + +@pytest.mark.parametrize('can_id', ['0', '-1', '2032', '2048']) +def test_read_error_rejects_invalid_or_reserved_ids_before_opening_usb(monkeypatch, can_id): + def unexpected_open(*args): + pytest.fail('invalid input opened USB') + monkeypatch.setattr(mks_setup, 'open_bus', unexpected_open) + with pytest.raises(SystemExit): + mks_setup.main(['--channel', 'fake', 'read-error', can_id]) + + +def test_a_drive_may_use_the_carriers_status_id_off_the_carrier(): + # Only the carrier's own link reserves that ID; on SocketCAN it is an ordinary CAN ID. + bus = SimulatedBus([SimulatedServo(1)], 500000) + assert 'now answers on 2032' in mks_setup.set_id(bus, 1, carrier.STATUS_ID) + assert mks_setup.scan(bus, [carrier.STATUS_ID]) == {carrier.STATUS_ID: 0} + + +@pytest.mark.parametrize('old, new', [(1, carrier.STATUS_ID), (carrier.STATUS_ID, 1)]) +def test_the_carriers_status_id_is_refused_before_a_drive_is_changed(usb_carrier, old, new): + port = usb_carrier() + bus = SlcanBus('/dev/fake', 500000, open_port=lambda: port) + with pytest.raises(SystemExit, match='reserved for the carrier'): + mks_setup.set_id(bus, old, new) + assert not any(line.startswith(b't') for line in b''.join(port.writes).split(b'\r')) + + +def test_read_error_accepts_the_carriers_status_id_off_the_carrier(monkeypatch, capsys): + reply = mks_can.frame(carrier.STATUS_ID, mks_can.READ_POSITION_ERROR, bytes([0, 0, 0, 100])) + bus = ErrorReadBus([(carrier.STATUS_ID, reply)]) + monkeypatch.setattr(mks_setup, 'open_bus', lambda *args: bus) + mks_setup.main(['--interface', 'socketcan', '--channel', 'can0', 'read-error', + str(carrier.STATUS_ID)]) + assert 'position error +0.703125 motor deg (+100 error counts)' in capsys.readouterr().out diff --git a/waybionic_teleop/test/test_sim_arm_drives_node.py b/waybionic_teleop/test/test_sim_arm_drives_node.py index b1139bfb..607480a7 100644 --- a/waybionic_teleop/test/test_sim_arm_drives_node.py +++ b/waybionic_teleop/test/test_sim_arm_drives_node.py @@ -21,18 +21,30 @@ DriveHealthState, DriveHealthThresholds, ) -from waybionic_teleop import joy_udp_receiver, mks_can, sim_arm_drives_node, xbox_teleop_node +from waybionic_teleop import ( + autoplay_node, + carrier, + joy_udp_receiver, + mks_can, + ros_shutdown, + sim_arm_drives_node, + xbox_teleop_node, +) from waybionic_teleop.gamepad import AXES, BUTTONS from waybionic_teleop.kinematics import ArmKinematics, joint_limits from waybionic_teleop.sim_arm_drives_node import ( + HOLD_RPM, + HOLD_S, QUIET_BEFORE_ZERO_S, REPLY_TIMEOUT_S, REPORT_PERIOD_S, SimArmDrives, + START_DEADBAND_COUNTS, ) from waybionic_teleop.sim_drives import SimulatedServo from waybionic_teleop.slcan_bus import SlcanBus from waybionic_teleop.teleop import ArmTeleop, config_from_parameters +import yaml URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' / 'waybionic_arm.urdf').read_text(encoding='utf-8') @@ -60,6 +72,7 @@ (joy_udp_receiver, 'JoyUdpReceiver'), (camera_module, 'CameraFollower'), (joint_demo_module, 'JointDemo'), + (autoplay_node, 'Autoplay'), ] @@ -109,8 +122,15 @@ def sent_frame(node, index): def assert_stopped(node): assert not node.authorized - assert all(servo.enabled and servo.target is None and servo.rpm == 0.0 - for servo in node.bus.drives.values()) + # Two ticks at full speed past the count, and a count of rounding. + reach = (2 * node.period * node.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + + START_DEADBAND_COUNTS + 1) + for index, drive in enumerate(node.map.drives): + servo = node.bus.drives[drive.can_id] + # A drive stopped mid-move runs on only to its hold, its last move's nearby end. + assert servo.enabled and servo.target in (None, node.held[index]) + assert (servo.rpm == 0.0 if servo.target is None + else abs(servo.target - servo.axis) <= reach and servo.speed <= HOLD_RPM) assert all(sent_frame(node, index) == (mks_can.ABSOLUTE_AXIS, bytes(6)) for index in range(len(node.map.drives))) @@ -371,6 +391,8 @@ def test_stale_encoder_feedback_stops_before_sending_another_position(node): assert not node.authorized node.on_enabled(Bool(data=False)) node.on_enabled(Bool(data=True)) + # The base was stopped mid-move, so it moves again once a reading shows it has settled. + advance(node) node.on_command(command(node, joint_1=1.0)) advance(node) assert node.authorized and node.bus.drives[1].target is not None @@ -419,7 +441,11 @@ def failing(data): node.on_command(command(node, joint_1=0.31, joint_2=0.31)) advance(node) assert not node.authorized and not node.zeroed[1] and 'shoulder' in node.stop_reason - assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) + # The others hold where their moves end; the shoulder, no longer trusted, gets no hold. + assert_stopped(node) + advance(node) + assert shoulder.target is None and node.hold_tick[1] == -1 + assert node.hold_tick[0] == node.ticks published = [] monkeypatch.setattr(node.diagnostics_publisher, 'publish', published.append) node.report() @@ -455,6 +481,265 @@ def test_a_drive_that_stops_following_its_targets_stops_every_drive(node, monkey assert all(servo.target is None and servo.rpm == 0.0 for servo in node.bus.drives.values()) +def test_a_reversing_drive_stops_before_it_gets_a_target_behind_it(node, monkeypatch): + ready(node) + clock = [time.monotonic()] + monkeypatch.setattr(sim_arm_drives_node.time, 'monotonic', lambda: clock[0]) + # A gentler ramp keeps the base turning when the stick reverses, and a slow stroke back + # lets the fast stroke forward put the next target behind the still-turning base. + node.acc = 240 + base = node.bus.drives[1] + stops, angle, turns, latched = capture_sends(node, monkeypatch), 0.0, [0.0], [] + rates = [0.5] * 30 + [-0.3] * 40 + [0.5] * 20 + [0.0] * 30 + for previous, rate in zip([0.5] + rates, rates): + if rate != previous: + turns.append(base.axis) + angle += rate * node.period + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={'joint_1': rate}, joint_1=angle)) + clock[0] += node.period + advance(node) + # Firmware V1.0.9 would run back to this target after the next stop. + latched.append(base.latched) + assert node.authorized and latched == [None] * len(rates) + # Each reversal and the final hold stopped the base, which followed the stick both ways. + assert stops.count(mks_can.stop(1, 0)) >= 3 + assert turns[0] < turns[1] > turns[2] < turns[3] + held = base.axis + for _ in range(60): + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={}, joint_1=angle)) + clock[0] += node.period + advance(node) + assert base.axis == held and node.authorized + + +def test_a_drive_that_turns_after_its_stop_stops_every_drive_but_keeps_its_zero(node): + ready(node) + node.following_error, node.following_ticks = 400, 5 + hold = command(node, velocities={}) + node.on_command(hold) + advance(node) + assert node.sent[0] == (None, 0) and node.held[0] == 0 + # The base runs on to a target its firmware kept from before the stop. + base = node.bus.drives[1] + base.target, base.speed, base.acc = 20000, 60, 0 + for _ in range(100): + node.on_enabled(Bool(data=True)) + node.on_command(hold) + advance(node) + if not node.authorized: + break + assert node.stop_reason.startswith('base_yaw turned +') and all(node.zeroed) + assert 400 < base.axis < 2000 and base.target is None and base.rpm == 0.0 + + +def stroke(node, clock, ticks, rate=0.5): + """Turn the base with the stick for some ticks of a mocked clock; return its angle.""" + angle = 0.0 + for _ in range(ticks): + angle += rate * node.period + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={'joint_1': rate}, joint_1=angle)) + clock[0] += node.period + advance(node) + return angle + + +@pytest.fixture +def clock(monkeypatch): + clock = [time.monotonic()] + monkeypatch.setattr(sim_arm_drives_node.time, 'monotonic', lambda: clock[0]) + return clock + + +def test_a_target_kept_by_the_firmware_never_runs_past_the_hold_behind_the_stop(node, clock): + ready(node) + base = node.bus.drives[1] + angle = stroke(node, clock, 20) + up = node.direction[0] + assert up + # Firmware V1.0.9 kept a target from earlier in the stroke, and runs back to it at once + # when the stick's release stops the base. + base.latched = (round(base.axis) - 3000 * up, 300, 0) + stopped = base.axis + node.on_command(command(node, velocities={}, joint_1=angle)) + assert base.latched is None and base.target == node.held[0] + assert 0 <= (node.held[0] - stopped) * up <= ( + 2 * node.period * node.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + START_DEADBAND_COUNTS) + lowest = stopped * up + for _ in range(60): + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={}, joint_1=angle)) + clock[0] += node.period + advance(node) + lowest = min(lowest, base.axis * up) + # The hold right behind the stop took over before the base turned back at all. + assert node.authorized and lowest == stopped * up and base.axis == node.held[0] + + +def test_a_target_kept_by_the_firmware_is_taken_over_within_a_tick_of_the_hold( + node, clock, monkeypatch): + ready(node) + base = node.bus.drives[1] + angle = stroke(node, clock, 20) + up = node.direction[0] + assert up + node.on_command(command(node, velocities={}, joint_1=angle)) + stopped_at, held = clock[0], node.held[0] + + def hold_tick(): + node.on_enabled(Bool(data=True)) + node.on_command(command(node, velocities={}, joint_1=angle)) + clock[0] += node.period + advance(node) + for _ in range(5): + hold_tick() + # The base reaches its hold, then runs back to a target its firmware kept. The hold goes + # out again on the next tick, before the following error could stop the arm. + base.target, base.speed, base.acc = held - 20000 * up, 300, 0 + farthest = 0 + for _ in range(20): + hold_tick() + farthest = max(farthest, (held - base.axis) * up) + assert node.authorized and 0 < farthest < 1500 and base.axis == held + # Once HOLD_S has passed, nothing but stops goes out to a drive at rest. + while clock[0] - stopped_at < HOLD_S: + hold_tick() + sent = capture_sends(node, monkeypatch) + for _ in range(10): + hold_tick() + assert all(frame[0] != mks_can.ABSOLUTE_AXIS for frame in sent) + + +def test_a_drive_disabled_mid_stroke_is_held_every_tick_for_the_hold_time( + node, clock, monkeypatch): + ready(node) + base = node.bus.drives[1] + stroke(node, clock, 20) + up = node.direction[0] + assert up + sent = capture_sends(node, monkeypatch) + node.on_enabled(Bool(data=False)) + stopped_at, held = clock[0], node.held[0] + hold = mks_can.absolute_axis(1, held, min(HOLD_RPM, node.max_rpm), node.acc) + # The hold goes out right behind the stop, a little ahead of the base, never behind it. + assert sent == [mks_can.stop(1, 0), hold] and (held - base.axis) * up >= 0 + ticks = [] + for _ in range(40): + sent.clear() + clock[0] += node.period + advance(node) + ticks.append((clock[0] - stopped_at, sent.count(hold))) + assert all(holds == 1 for elapsed, holds in ticks if elapsed < HOLD_S - 1e-6) + assert all(holds == 0 for elapsed, holds in ticks if elapsed > HOLD_S + 1e-6) + assert not node.authorized and base.axis == held and base.target is None + + +@pytest.mark.parametrize('state', ['moving', 'disabled', 'holding']) +def test_zeroing_sends_no_hold_in_the_old_coordinates(node, clock, monkeypatch, state): + ready(node) + base = node.bus.drives[1] + angle = stroke(node, clock, 10) + if state == 'disabled': + node.on_enabled(Bool(data=False)) + elif state == 'holding': + node.on_command(command(node, velocities={}, joint_1=angle)) + assert node.authorized + if state != 'moving': + # Its hold, a few thousand counts out, would be within reach of the new zero. + assert node.hold_until[0] > clock[0] and 0 < abs(node.held[0]) < node.following_error + sent = capture_sends(node, monkeypatch) + node.zero() + for _ in range(10): + clock[0] += node.period + advance(node) + assert all(node.zeroed) and node.counts[0] == 0 + assert not [frame for frame in sent + if frame[0] == mks_can.ABSOLUTE_AXIS and frame[1:3] != b'\x00\x00'] + assert base.axis == 0 and base.target is None + + +def test_a_drive_that_turns_after_a_disable_stops_every_drive_again(node, clock): + ready(node) + node.following_error, node.following_ticks = 400, 5 + base = node.bus.drives[1] + stroke(node, clock, 20) + up = node.direction[0] + node.on_enabled(Bool(data=False)) + held = node.held[0] + for _ in range(40): + clock[0] += node.period + advance(node) + assert not node.authorized and base.axis == held and node.stop_reason == 'Teleop disabled' + # Its hold over, the base runs on to a target its firmware kept, though disarmed. + base.target, base.speed, base.acc = held + 20000 * up, 60, 0 + for _ in range(100): + clock[0] += node.period + advance(node) + if node.stop_reason != 'Teleop disabled': + break + assert node.stop_reason.startswith('base_yaw turned ') and all(node.zeroed) + assert 400 < (base.axis - held) * up < 2000 and base.target is None and base.rpm == 0.0 + + +def test_a_hold_from_an_old_count_never_pulls_the_drive_back(node, clock): + ready(node) + base = node.bus.drives[1] + stroke(node, clock, 20) + up, speed = node.direction[0], node.sent[0][1] + # The base's last few counts were lost, so the node's count is four ticks behind it. + lag = 4 * node.period + node.counts[0] -= round(up * lag * speed / 60.0 * mks_can.COUNTS_PER_REV) + node.since_count[0] += lag + node.on_enabled(Bool(data=False)) + assert (node.held[0] - base.axis) * up >= -1 + + +def test_no_hold_goes_out_once_an_estop_press_is_released(node, clock, monkeypatch): + ready(node) + stroke(node, clock, 20) + node.interface = 'slcan' + monkeypatch.setattr(node.bus, 'take_refused', lambda: [], raising=False) + sent = capture_sends(node, monkeypatch) + flags = carrier.ESTOP_WIRED + node.on_reply(carrier.STATUS_ID, bytes([1, flags | carrier.ESTOP_PRESSED, 0, 0, 0, 0, 0, 0]), + clock[0]) + assert node.stop_reason == 'E-stop pressed' and mks_can.stop(1, 0) in sent + clock[0] += node.period + advance(node) + node.on_reply(carrier.STATUS_ID, bytes([2, flags, 0, 0, 0, 0, 0, 0]), clock[0]) + assert not node.estop_pressed + for _ in range(10): + clock[0] += node.period + advance(node) + # The drives may have restarted with new counts, so nothing but stops went out. + assert not [frame for frame in sent + if frame[0] == mks_can.ABSOLUTE_AXIS and frame[1:3] != b'\x00\x00'] + + +def test_closing_mid_move_holds_the_drive_until_the_hold_time_is_over(node, usb_carrier): + ready(node) + node.on_command(command(node, velocities={'joint_1': 0.5}, joint_1=0.5)) + for _ in range(3): + advance(node) + assert node.sent[0][0] is not None + port = usb_carrier() + node.interface = 'slcan' + node.bus = SlcanBus('/dev/fake', 1000000, open_port=lambda: port) + started = time.monotonic() + node.close() + written = b''.join(port.writes) + frames = [line for line in written.split(b'\r') if line.startswith(b't')] + hold = mks_can.absolute_axis(1, node.held[0], min(HOLD_RPM, node.max_rpm), node.acc) + hold_line = b't001%d%s' % (len(hold), hold.hex().upper().encode()) + # The hold goes out right behind the base's stop, then about once a tick for HOLD_S. + assert frames[frames.index(stop_line(1)) + 1] == hold_line + assert 0.6 * HOLD_S / node.period <= frames.count(hold_line) <= HOLD_S / node.period + 2 + assert written.endswith(b'C\r') and port.closed + assert HOLD_S <= time.monotonic() - started < sim_arm_drives_node.CLOSE_TIMEOUT_S + 0.1 + + def test_a_drive_that_restarts_between_polls_is_set_up_and_zeroed_again(node): start = dict.fromkeys(node.map.joints, 0.0) start['joint_2'] = 1.2 @@ -477,6 +762,143 @@ def test_a_drive_that_restarts_between_polls_is_set_up_and_zeroed_again(node): assert not node.authorized +@pytest.fixture +def drives_with(monkeypatch, parameters): + """Make drive nodes with changed parameters, all destroyed after the test.""" + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + made = [] + + def make(**changes): + configured = parameters('arm_drives.yaml', 'sim_arm_drives') + configured.update(changes) + made.append(SimArmDrives(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in configured.items()])) + return made[-1] + yield make + for made_node in made: + made_node.destroy_node() + rclpy.try_shutdown(context=context) + + +def zeroed_with_state(drives_with, path): + """Zero drives powered on away from the zero pose, saving the zero to path.""" + node = drives_with(zero_state=str(path), zero_on_start=False) + for index, servo in enumerate(node.bus.drives.values()): + # Power-on starts the raw encoder at the shaft's magnetic angle. + servo.raw_shift, servo.axis = 1000 * index + 7, 5000.0 + advance(node) + assert not path.exists() + assert node.on_zero(Trigger.Request(), Trigger.Response()).success + for _ in range(3): + advance(node) + return node + + +def restart(drives_with, old, path): + """Start the node again on the same simulated drives, as a relaunch does.""" + node = drives_with(zero_state=str(path), zero_on_start=False) + node.bus = old.bus + for index in range(len(node.map.drives)): + node.set_up(index) + return node + + +def test_a_zero_is_saved_once_every_drive_reports_its_fingerprint(drives_with, tmp_path): + path = tmp_path / 'state' / 'drive_zero.yaml' + node = zeroed_with_state(drives_with, path) + saved = yaml.safe_load(path.read_text(encoding='utf-8'))['drives'] + assert saved == {drive.name: {'can_id': drive.can_id, 'offset': 1000 * index + 5007} + for index, drive in enumerate(node.map.drives)} + assert not node.checks and not list(tmp_path.glob('state/*.partial')) + + +def test_a_restart_keeps_the_zero_of_drives_that_stayed_powered(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + old = zeroed_with_state(drives_with, path) + # The arm is driven or pushed elsewhere before the station restarts. + for servo in old.bus.drives.values(): + servo.axis = 2000.0 + node = restart(drives_with, old, path) + assert not any(node.zeroed) and node.checks + published = [] + node.state_publisher.publish = published.append + for _ in range(3): + advance(node) + assert all(node.zeroed) and not node.checks + assert node.counts == [2000] * len(node.map.drives) + assert published[-1].position[:len(node.map.joints)] == pytest.approx( + list(node.map.to_positions(node.counts).values())) + ready(node) + + +def test_a_restart_after_a_power_cycle_does_not_keep_the_zero(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + old = zeroed_with_state(drives_with, path) + saved = yaml.safe_load(path.read_text(encoding='utf-8'))['drives'] + for drive in old.map.drives: + # Powered on again where its raw encoder reads its saved offset, so only the zero + # status shows it lost its zero. + old.bus.drives[drive.can_id].power_cycle(saved[drive.name]['offset']) + node = restart(drives_with, old, path) + for _ in range(3): + advance(node) + assert not any(node.zeroed) and not node.checks + node.on_description(String(data=URDF)) + node.on_enabled(Bool(data=False)) + node.on_enabled(Bool(data=True)) + assert not node.authorized + + +def test_a_restart_does_not_keep_a_zero_made_elsewhere(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + old = zeroed_with_state(drives_with, path) + base = old.bus.drives[old.map.drives[0].can_id] + base.axis = 3000.0 + base.receive(mks_can.set_zero(base.can_id)) + node = restart(drives_with, old, path) + for _ in range(3): + advance(node) + assert node.zeroed == [False] + [True] * (len(node.map.drives) - 1) + + +def test_a_fault_or_a_new_zero_forgets_the_saved_zero(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + node = zeroed_with_state(drives_with, path) + node.zero() + assert not path.exists() and not node.saved_zero + for _ in range(3): + advance(node) + assert path.exists() + node.fault(0, 'is 5000 counts from its target') + assert not path.exists() and not node.saved_zero + for _ in range(3): + advance(node) + assert not path.exists() + restarted = restart(drives_with, node, path) + assert not restarted.checks and not any(restarted.zeroed) + + +def test_a_drive_that_answers_again_keeps_its_zero_unless_it_lost_power(drives_with, tmp_path): + path = tmp_path / 'drive_zero.yaml' + node = zeroed_with_state(drives_with, path) + ready(node) + can_id = node.map.drives[0].can_id + for power_cycled in (False, True): + unplugged = node.bus.drives.pop(can_id) + for _ in range(node.max_unanswered + 3): + advance(node) + assert node.lost[0] and not node.zeroed[0] and not node.authorized + if power_cycled: + unplugged.power_cycle(5007) + node.bus.drives[can_id] = unplugged + for _ in range(3): + advance(node) + assert not node.lost[0] and node.zeroed[0] is not power_cycled + assert node.held[0] is None and not node.checks + + def test_zeroing_waits_until_teleop_stops_streaming_to_an_arm_that_lost_its_zero(node): ready(node) held = command(node, joint_1=0.3, joint_2=0.3) @@ -522,6 +944,8 @@ def test_a_stop_the_interface_refuses_is_sent_again_until_it_goes_out(node, monk advance(node) base = node.bus.drives[1] assert base.target is not None + up = node.direction[0] + assert up send, refusing = node.bus.send, [True] def full(can_id, data): @@ -540,7 +964,9 @@ def full(can_id, data): assert not node.authorized refusing[0] = False advance(node) - assert not node.stopping and base.target is None and base.rpm == 0.0 + # The hold is taken where the drive was once its stop went out, so it never pulls back. + assert not node.stopping and base.target == node.held[0] and base.rpm == 0.0 + assert (node.held[0] - base.axis) * up >= 0 node.on_enabled(Bool(data=True)) assert node.authorized @@ -797,7 +1223,7 @@ def test_following_error_is_reported_and_clears_on_a_current_pose_command(node, node.on_command(command( node, - velocities={joint: 0.0 for joint in node.map.joints}, + velocities=dict.fromkeys(node.map.joints, 0.0), joint_1=math.radians(6.0))) clock[0] += 0.1 node.report() @@ -859,7 +1285,7 @@ def test_stalled_simulated_drive_is_reported_within_detection_window_and_recover clock[0], servo.enabled, servo.target, servo.rpm) assert stalled, states assert stalled[0][1] == DiagnosticStatus.ERROR - assert stalled[0][0] - fault_started <= 2.0 + REPORT_PERIOD_S + assert stalled[0][0] - fault_started <= 2.0 + REPORT_PERIOD_S + 1e-6 assert float(stalled[0][3]['target_encoder_error_deg']) == pytest.approx(3.0, abs=0.01) assert float(stalled[0][3]['reply_age_sec']) <= REPORT_PERIOD_S assert servo.axis == pytest.approx(0.0) @@ -906,7 +1332,8 @@ def test_not_responding_simulated_drive_is_stale_within_one_report_period_and_re node.report() row = next(item for item in published[-1].status if item.name == 'drive.base_yaw') values = {value.key: value.value for value in row.values} - assert clock[0] - fault_started <= REPORT_PERIOD_S + # The clock is a float sum of tick periods, which can overshoot by a rounding error. + assert clock[0] - fault_started <= REPORT_PERIOD_S + 1e-6 assert row.level == DiagnosticStatus.STALE assert values['state'] == DriveHealthState.NOT_RESPONDING.value assert 'target_encoder_error_deg' in values and 'reply_age_sec' in values @@ -1045,17 +1472,20 @@ def test_zero_speed_f5_stops_six_drives_and_negative_targets_rearm(node): node.on_command(command(node, velocities=dict.fromkeys(POSE, 0.0), **measured)) advance(node) assert node.authorized - assert all(drive.enabled and drive.target is None and drive.rpm == 0.0 - for drive in node.bus.drives.values()) + servos = [node.bus.drives[drive.can_id] for drive in node.map.drives] + # Each drive stops, then runs on only to its hold, the nearby end of its move. + assert all(servo.enabled and servo.target == held and abs(held - servo.axis) <= 60 + for servo, held in zip(servos, node.held)) assert all(sent_frame(node, index) == (mks_can.ABSOLUTE_AXIS, bytes(6)) for index in range(len(node.map.drives))) - held = [drive.axis for drive in node.bus.drives.values()] advance(node, 0.6) - assert [drive.axis for drive in node.bus.drives.values()] == held + assert [servo.axis for servo in servos] == node.held assert_stopped(node) node.on_enabled(Bool(data=False)) node.on_enabled(Bool(data=True)) + # Its hold reached, the next quiet encoder step lets each drive move again. + advance(node) reverse = dict.fromkeys(POSE, -0.4) reverse.update(joint_5=0.1, tool_grip=0.2) rates = dict.fromkeys(POSE, -0.2) @@ -1123,8 +1553,109 @@ def test_a_cartesian_tilt_into_a_joint_limit_keeps_the_drives_enabled(node, para assert node.commanded['joint_3'] == pytest.approx(node.limits['joint_3'][1], abs=1e-9) +@pytest.fixture +def bench(monkeypatch, parameters, bench_profile): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + configured = {**parameters('arm_drives.yaml', 'sim_arm_drives'), + 'arm_profile': bench_profile} + node = SimArmDrives(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in configured.items()]) + yield node + node.destroy_node() + rclpy.try_shutdown(context=context) + + +def test_an_arm_without_a_shoulder_drive_publishes_the_shoulder_where_it_is_fixed( + bench, monkeypatch): + states = [] + monkeypatch.setattr(bench.state_publisher, 'publish', states.append) + assert [drive.can_id for drive in bench.map.drives] == [1, 3, 4, 5] + assert sorted(bench.bus.drives) == [1, 3, 4, 5] + ready(bench) + published = dict(zip(states[-1].name, states[-1].position)) + assert set(published) == {'joint_1', 'joint_2', 'joint_3', 'joint_4', 'joint_5', + 'tool_grip'} + assert published['joint_2'] == 0.0 and published['tool_grip'] == 0.0 + + +def test_a_command_must_hold_a_locked_joint_where_it_is(bench): + ready(bench) + bench.on_command(command(bench, joint_1=0.5, joint_2=0.0, tool_grip=0.0)) + advance(bench) + assert bench.authorized and bench.rejected == 0 + assert set(bench.commanded) == set(bench.map.joints) + assert bench.bus.drives[1].target is not None + bench.on_command(command(bench, joint_1=0.5, joint_2=0.1, tool_grip=0.0)) + assert not bench.authorized and bench.stop_reason == 'joint_2 is locked at 0 rad' + ready(bench) + # Leaving a locked joint out is as incomplete as leaving out a driven one. + bench.on_command(command(bench, joint_1=0.5, tool_grip=0.0)) + assert not bench.authorized and bench.stop_reason.startswith('incomplete') + + +def test_a_profile_that_leaves_a_joint_unaccounted_for_stops_the_node( + monkeypatch, parameters, tmp_path): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + profile = tmp_path / 'arm_profile.yaml' + profile.write_text('fitted_drives: [base_yaw, elbow, wrist_left, wrist_right]\n', + encoding='utf-8') + configured = {**parameters('arm_drives.yaml', 'sim_arm_drives'), + 'arm_profile': str(profile)} + context = rclpy.Context() + rclpy.init(context=context) + try: + with pytest.raises(ValueError, match='joint_2'): + SimArmDrives(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in configured.items()]) + finally: + rclpy.try_shutdown(context=context) + + +def test_teleop_drives_an_arm_with_a_locked_shoulder_without_a_stop( + bench, parameters, monkeypatch): + states = [] + monkeypatch.setattr(bench.state_publisher, 'publish', states.append) + ready(bench) + arm = ArmKinematics.from_urdf(URDF) + teleop = ArmTeleop(config_from_parameters(parameters('xbox_teleop.yaml', 'xbox_teleop')), + joint_limits(URDF, arm.joints), arm, locked=bench.locked) + + 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)] + 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 + assert bench.rejected == 0 + assert abs(measured()['joint_1']) > 0.1 and measured()['joint_2'] == 0.0 + + +@pytest.fixture +def short_shutdown_grace(monkeypatch): + monkeypatch.setattr(ros_shutdown, 'SHUTDOWN_GRACE_S', 0.05) + + @pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES) -def test_shutdown_only_ignores_an_invalid_shutdown_context(module, class_name, monkeypatch): +def test_shutdown_only_ignores_an_invalid_shutdown_context( + module, class_name, monkeypatch, short_shutdown_grace): factory = MagicMock() spin = MagicMock(side_effect=RCLError('the given context is not valid')) monkeypatch.setattr(module, class_name, factory) @@ -1146,7 +1677,8 @@ def test_shutdown_only_ignores_an_invalid_shutdown_context(module, class_name, m @pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES) -def test_binding_error_only_ignored_after_context_shutdown(module, class_name, monkeypatch): +def test_binding_error_only_ignored_after_context_shutdown( + module, class_name, monkeypatch, short_shutdown_grace): factory = MagicMock() error = RuntimeError("Unable to convert call argument '0' to Python object") spin = MagicMock(side_effect=error) @@ -1170,7 +1702,8 @@ def test_binding_error_only_ignored_after_context_shutdown(module, class_name, m @pytest.mark.parametrize('module, class_name', [ (camera_module, 'CameraFollower'), (joint_demo_module, 'JointDemo')]) -def test_tf_time_error_only_ignored_after_context_shutdown(module, class_name, monkeypatch): +def test_tf_time_error_only_ignored_after_context_shutdown( + module, class_name, monkeypatch, short_shutdown_grace): factory = MagicMock() error = TypeError('time must have sec and nanosec, or nanoseconds.') spin = MagicMock(side_effect=error) @@ -1190,3 +1723,22 @@ def test_tf_time_error_only_ignored_after_context_shutdown(module, class_name, m module.main() assert spin.call_count == 3 assert factory.return_value.destroy_node.call_count == 3 + + +@pytest.mark.parametrize('error', [ + RCLError('the given context is not valid'), + RuntimeError("Unable to convert call argument '0' to Python object")]) +@pytest.mark.parametrize('module, class_name', SHUTDOWN_NODES) +def test_shutdown_error_waits_for_the_signal_thread_to_shut_rclpy_down( + module, class_name, error, monkeypatch): + # rclpy's SIGINT thread wakes spin before it shuts the context down. + factory = MagicMock() + running = iter([True, True, True]) + monkeypatch.setattr(module, class_name, factory) + monkeypatch.setattr(module.rclpy, 'init', MagicMock()) + monkeypatch.setattr(module.rclpy, 'try_shutdown', MagicMock()) + monkeypatch.setattr(module.rclpy, 'spin', MagicMock(side_effect=error)) + monkeypatch.setattr(module.rclpy, 'ok', lambda: next(running, False)) + module.main() + assert next(running, None) is None + assert factory.return_value.destroy_node.call_count == 1 diff --git a/waybionic_teleop/test/test_sim_drives.py b/waybionic_teleop/test/test_sim_drives.py index 2318bb4c..0dc682c8 100644 --- a/waybionic_teleop/test/test_sim_drives.py +++ b/waybionic_teleop/test/test_sim_drives.py @@ -95,6 +95,38 @@ def test_f5_stop_is_immediate_and_a_new_negative_target_rearms_the_drive(): assert servo.target == -0x4000 and servo.rpm < 0.0 and servo.axis < held +@pytest.mark.parametrize('end', [mks_can.stop(1, 0), mks_can.emergency_stop(1), None]) +def test_a_target_that_reverses_a_running_move_is_run_to_once_the_moves_stop(end): + # Firmware V1.0.9 on the bench: the reversing target is kept while later targets steer the + # move, and the drive runs back to it on its own after a stop or its last target. + servo = ready_servo() + servo.receive(mks_can.absolute_axis(1, 0x8000, 300, 0)) + run(servo, 0.05) + assert servo.rpm > 0.0 + servo.receive(mks_can.absolute_axis(1, -0x1000, 300, 0)) + run(servo, 0.02) + servo.receive(mks_can.absolute_axis(1, round(servo.axis) + 2000, 300, 0)) + if end is None: + run(servo, 0.05) + else: + servo.receive(end) + run(servo, 1.0) + assert servo.axis == -0x1000 and servo.latched is None + + +def test_a_drive_that_stops_before_it_reverses_runs_only_to_its_last_target(): + servo = ready_servo() + servo.receive(mks_can.absolute_axis(1, 0x8000, 300, 0)) + run(servo, 0.05) + servo.receive(mks_can.stop(1, 0)) + servo.receive(mks_can.absolute_axis(1, -0x1000, 300, 0)) + run(servo, 1.0) + held = servo.axis + assert servo.receive(mks_can.stop(1, 0)) == [COMPLETE] + run(servo, 1.0) + assert servo.axis == held == -0x1000 + + def test_stalled_test_fault_keeps_replying_without_advancing_and_recovers(): servo = ready_servo() initial_axis = servo.axis diff --git a/waybionic_teleop/test/test_slcan_bus.py b/waybionic_teleop/test/test_slcan_bus.py index d9023baa..92a68121 100644 --- a/waybionic_teleop/test/test_slcan_bus.py +++ b/waybionic_teleop/test/test_slcan_bus.py @@ -10,6 +10,9 @@ from waybionic_teleop import carrier, 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. +VERSION = b'V0100\r' + class FakeSerial: """A USB serial port that can be unplugged.""" @@ -45,6 +48,11 @@ def close(self): def clock(monkeypatch): now = [1000.0] monkeypatch.setattr(slcan_bus.time, 'monotonic', lambda: now[0]) + + def sleep(seconds): + now[0] += seconds + + monkeypatch.setattr(slcan_bus.time, 'sleep', sleep) return now @@ -62,7 +70,7 @@ def open_port(): def test_it_opens_the_bridge_at_the_bit_rate_then_writes_a_tick_in_one_go(bus, ports): - assert ports[0].writes == [b'C\rS8\rO\r'] + assert ports[0].writes == [b'V\rC\rS8\rO\r'] assert bus.send(1, mks_can.read_encoder(1)) and bus.send(2, mks_can.read_encoder(2)) assert len(ports[0].writes) == 1 assert bus.receive() is None @@ -71,7 +79,7 @@ def test_it_opens_the_bridge_at_the_bit_rate_then_writes_a_tick_in_one_go(bus, p def test_replies_are_parsed_across_reads(bus, ports): - ports[0].inbox += b'\r\r\rt0013F5' + ports[0].inbox += VERSION + b'\r\r\rt0013F5' assert bus.receive() is None ports[0].inbox += b'01F7\rt7F080005000000000000\r' assert bus.receive() == (1, bytes.fromhex('F501F7')) @@ -85,15 +93,29 @@ def test_a_refusal_is_matched_to_the_frame_it_answers(bus, ports): for frame in frames: bus.send(*frame) assert bus.receive() is None - # C, S8, O; frame 1 taken; frame 2 refused, a drive's reply in between; frame 3 taken. - ports[0].inbox += b'\r\r\r\r\at00183100000000000032\r\r\r' + # V, C, S8, O; frame 1 taken; frame 2 refused, a drive's reply in between; frame 3 taken. + ports[0].inbox += VERSION + b'\r\r\r\r\at00183100000000000032\r\r\r' assert bus.receive() == (1, bytes.fromhex('3100000000000032')) assert bus.take_refused() == [frames[1]] and bus.take_refused() == [] assert bus.refused == 1 and bus.errors == 0 +def test_answers_left_from_the_last_session_are_not_pinned_on_new_lines(bus, ports): + # The last program closed the port as the carrier answered its last lines: their ends, a + # BELL for a frame cut off by its C, a drive's reply and a status frame come out first. + ports[0].inbox += b'00000032\r\a\r\rt00183100000000000032\rt7F080F00000000010011\r' + bus.send(1, mks_can.read_encoder(1)) + assert bus.receive() is None + ports[0].inbox += VERSION + b'\r\r\r\r' + assert bus.receive() is None + assert bus.errors == 0 and bus.problem == '' and bus.unanswered == 0 + assert bus.take_refused() == [] and bus.refused == 0 + ports[0].inbox += b't00183100000000000033\r' + assert bus.receive() == (1, bytes.fromhex('3100000000000033')) + + def test_a_refused_open_is_an_error_that_says_why(bus, ports): - ports[0].inbox += b'\r\r\a' + ports[0].inbox += VERSION + b'\r\r\a' bus.send(1, mks_can.read_encoder(1)) assert bus.receive() is None assert bus.errors == 1 and '1000000 bit/s' in bus.problem @@ -104,7 +126,7 @@ def test_a_refused_open_is_an_error_that_says_why(bus, ports): def test_a_closed_carrier_that_still_answers_is_opened_again(bus, ports, clock): - ports[0].inbox += b'\r\r\r' + ports[0].inbox += VERSION + b'\r\r\r' for _ in range(3): clock[0] += slcan_bus.SILENCE_S / 2 bus.send(1, mks_can.read_encoder(1)) @@ -112,7 +134,7 @@ def test_a_closed_carrier_that_still_answers_is_opened_again(bus, ports, clock): # A carrier that reset answers every line, but passes on no frames until it is opened. ports[0].inbox += b'\a\r' bus.step(0.0) - assert ports[0].writes[-1] == b'C\rS8\rO\r' + assert ports[0].writes[-1] == b'V\rC\rS8\rO\r' def test_an_unplugged_carrier_is_reopened_and_set_up_again(bus, ports, clock): @@ -125,7 +147,7 @@ def test_an_unplugged_carrier_is_reopened_and_set_up_again(bus, ports, clock): assert len(ports) == 1 clock[0] += slcan_bus.REOPEN_EVERY_S bus.step(0.0) - assert bus.connected and bus.reopens == 1 and ports[1].writes == [b'C\rS8\rO\r'] + assert bus.connected and bus.reopens == 1 and ports[1].writes == [b'V\rC\rS8\rO\r'] def test_a_carrier_that_went_quiet_is_opened_again(bus, ports, clock): @@ -136,11 +158,11 @@ def test_a_carrier_that_went_quiet_is_opened_again(bus, ports, clock): assert len(ports[0].writes) == 1 clock[0] += slcan_bus.SILENCE_S bus.step(0.0) - assert ports[0].writes[-1] == b'C\rS8\rO\r' + assert ports[0].writes[-1] == b'V\rC\rS8\rO\r' def test_no_more_frames_are_unanswered_than_the_carrier_can_queue(bus, ports): - ports[0].inbox += b'\r\r\r' + ports[0].inbox += VERSION + b'\r\r\r' bus.receive() frames = [(can_id, mks_can.read_encoder(can_id)) for can_id in range(1, slcan_bus.CARRIER_QUEUE + 3)] @@ -170,7 +192,7 @@ def test_a_carrier_that_stops_answering_lines_is_opened_again(bus, ports, clock) assert bus.unanswered == 0 and bus.take_refused() == [(1, mks_can.read_encoder(1))] * 3 clock[0] += slcan_bus.REOPEN_EVERY_S bus.step(0.0) - assert bus.connected and ports[1].writes == [b'C\rS8\rO\r'] + assert bus.connected and ports[1].writes == [b'V\rC\rS8\rO\r'] def test_the_carrier_status_frame_decodes(): @@ -183,6 +205,57 @@ def test_the_carrier_status_frame_decodes(): carrier.parse_status(bytes(7)) +def test_shutdown_waits_for_the_close_acknowledgement_before_releasing_usb(bus, ports): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + ports[0].inbox += b't7F080100000000000000\r\r' + bus.shutdown() + assert ports[0].writes[-1] == b'C\r' + assert ports[0].closed and not bus.connected + assert not ports[0].inbox and bus.unanswered == 0 + assert bus.errors == 0 and bus.problem == '' + writes = list(ports[0].writes) + bus.shutdown() + assert ports[0].writes == writes + + +def test_shutdown_times_out_and_reports_an_unacknowledged_close(bus, ports, clock, capfd): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + start = clock[0] + bus.shutdown() + assert ports[0].closed and not bus.connected + assert slcan_bus.CLOSE_TIMEOUT_S <= clock[0] - start <= slcan_bus.CLOSE_TIMEOUT_S + 0.002 + assert bus.errors == 1 and 'acknowledge close' in bus.problem + assert 'acknowledge close' in capfd.readouterr().err + + +@pytest.mark.parametrize('unplugged', [False, True]) +def test_shutdown_reports_a_refusal_or_disconnect_and_still_releases_usb( + bus, ports, unplugged, capfd): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + ports[0].unplugged = unplugged + ports[0].inbox += b'\a' + bus.shutdown() + assert ports[0].closed and not bus.connected + assert bus.errors == 1 + assert 'close' in capfd.readouterr().err.lower() + + +def test_an_interrupted_close_still_releases_usb(bus, ports, monkeypatch): + ports[0].inbox += VERSION + b'\r\r\r' + bus.receive() + + def interrupted_read(): + raise KeyboardInterrupt + + monkeypatch.setattr(bus, '_read', interrupted_read) + with pytest.raises(KeyboardInterrupt): + bus.shutdown() + assert ports[0].closed and not bus.connected + + def slcan_sim(): try: from ament_index_python.packages import get_package_prefix @@ -199,7 +272,8 @@ def test_the_simulated_carrier_answers_through_the_real_bridge_code(): stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True) try: port = sim.stdout.readline().strip() - bus = SlcanBus(port, 500000) + # A pty ignores the baud rate, and macOS refuses a custom rate such as 1000000 on one. + bus = SlcanBus(port, 500000, baudrate=115200) frames = [] def wait_for(done, seconds=2.0): diff --git a/waybionic_teleop/test/test_teleop.py b/waybionic_teleop/test/test_teleop.py index 9c3dc252..3ec923e1 100644 --- a/waybionic_teleop/test/test_teleop.py +++ b/waybionic_teleop/test/test_teleop.py @@ -71,6 +71,23 @@ def test_enable_waits_for_joint_states(teleop): assert not teleop.enabled and teleop.warning and 'joint_2' in teleop.note +def test_a_locked_joint_stays_exactly_at_its_angle(params, arm): + teleop = ArmTeleop(config_from_parameters(params), LIMITS, arm, + locked={'joint_2': 0.25, 'tool_grip': 0.0, 'not_a_joint': 1.0}) + assert teleop.limits['joint_2'] == (0.25, 0.25) and 'not_a_joint' not in teleop.limits + # 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')): + teleop.update(*sample(**axes), HOME, DT) + assert joint in 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 + + @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) @@ -88,9 +105,10 @@ def test_enable_refuses_held_tilt_and_home_buttons(params, arm, button): def test_base_group_moves_yaw_shoulder_and_elbow(teleop): press(teleop, 'start') - run(teleop, 1.0, left_x=1.0, left_y=-1.0, right_y=0.5) + run(teleop, 1.0, left_x=-1.0, left_y=-1.0, right_y=0.5) targets = teleop.targets - assert targets['joint_1'] > 0.3 and targets['joint_2'] < -0.3 and targets['joint_3'] > 0.1 + # Stick right turns the base the positive way; right stick up lifts the elbow (negative). + assert targets['joint_1'] > 0.3 and targets['joint_2'] < -0.3 and targets['joint_3'] < -0.1 assert targets['joint_4'] == targets['joint_5'] == 0.0 @@ -101,7 +119,9 @@ def test_y_switches_to_the_upper_joints_and_leaves_the_base_alone(teleop): targets = teleop.targets assert teleop.active_group.name == 'upper' assert targets['joint_1'] == 0.0 and targets['joint_2'] > 0.3 - assert targets['joint_3'] > 0.3 and targets['joint_4'] > 0.3 and targets['joint_5'] < -0.3 + # Left stick up lifts the elbow (negative), as in the base group. Right stick up tips the + # wrist up, and right turns the roll positive (counter-clockwise). + assert targets['joint_3'] < -0.3 and targets['joint_4'] < -0.3 and targets['joint_5'] > 0.3 def test_small_stick_drift_is_ignored(teleop): @@ -132,7 +152,7 @@ def test_b_stop_needs_a_fresh_start_with_centered_sticks_to_rearm(teleop): teleop.update(*sample(), pose, DT) press(teleop, 'start', pose) assert teleop.enabled and teleop.targets == pose - run(teleop, 0.4, left_x=-1.0) + run(teleop, 0.4, left_x=1.0) assert teleop.targets['joint_1'] < pose['joint_1'] diff --git a/waybionic_teleop/test/test_teleop_node.py b/waybionic_teleop/test/test_teleop_node.py index 87e85f69..8cd86e17 100644 --- a/waybionic_teleop/test/test_teleop_node.py +++ b/waybionic_teleop/test/test_teleop_node.py @@ -9,7 +9,8 @@ from std_msgs.msg import String from std_srvs.srv import Trigger -from waybionic_teleop.sim_arm_drives_node import SimArmDrives +from waybionic_teleop import mks_can +from waybionic_teleop.sim_arm_drives_node import SimArmDrives, START_DEADBAND_COUNTS from waybionic_teleop.xbox_teleop_node import XboxTeleop URDF = (Path(__file__).resolve().parents[2] / 'waybionic_description' / 'urdf' @@ -122,11 +123,21 @@ def enable(): drives.last_tick -= 0.05 drives.tick() stopped_at = motor.axis - assert motor.rpm == 0.0 and motor.target is None + # The stop is followed by a hold at the moving drive's last target, no farther than + # two ticks of full-speed travel plus the start deadband, and never behind the stop. + held = drives.held[0] + reach = (2 * drives.period * drives.max_rpm / 60.0 * mks_can.COUNTS_PER_REV + + START_DEADBAND_COUNTS + 1) + assert motor.target == held and stopped_at - 1 <= held <= stopped_at + reach for _ in range(10): drives.last_tick -= 0.05 drives.tick() - assert motor.axis == stopped_at and not drives.authorized + assert motor.target in (None, held) and motor.axis == pytest.approx(held, abs=1) + rested = motor.axis + for _ in range(10): + drives.last_tick -= 0.05 + drives.tick() + assert motor.axis == rested and not drives.authorized if valid_replacement: enable() heard = drives.command_time diff --git a/waybionic_teleop/test/test_xbox_teleop_node.py b/waybionic_teleop/test/test_xbox_teleop_node.py index 36f1b384..61eb8e13 100644 --- a/waybionic_teleop/test/test_xbox_teleop_node.py +++ b/waybionic_teleop/test/test_xbox_teleop_node.py @@ -96,11 +96,11 @@ def test_a_host_pause_disables_even_if_controller_packets_look_fresh(node, monke def test_a_late_tick_moves_the_targets_at_most_two_periods(node): ready(node) for _ in range(20): - tick(node, left_x=1.0) + tick(node, left_x=-1.0) speed = node.teleop.velocities['joint_1'] assert speed == pytest.approx(node.teleop.speed) before = node.teleop.targets['joint_1'] - tick(node, left_x=1.0, elapsed=0.1) + tick(node, left_x=-1.0, elapsed=0.1) assert node.teleop.targets['joint_1'] - before == pytest.approx( 2 * node.config.period * speed) @@ -125,7 +125,7 @@ def step(message=None): step(joy()) step(joy('start')) for _ in range(10): - step(joy(left_x=1.0)) + step(joy(left_x=-1.0)) assert node.teleop.enabled and node.teleop.velocities['joint_1'] > 0 last_input = clock.now # The drives trail the moving target. @@ -192,6 +192,23 @@ def test_the_rate_and_input_timeout_must_be_positive(monkeypatch, parameters, ch rclpy.try_shutdown(context=context) +def test_the_arm_profile_pins_its_locked_joints(monkeypatch, parameters, bench_profile): + monkeypatch.setenv('ROS_AUTOMATIC_DISCOVERY_RANGE', 'OFF') + context = rclpy.Context() + rclpy.init(context=context) + params = {**parameters('xbox_teleop.yaml', 'xbox_teleop'), 'arm_profile': bench_profile} + node = XboxTeleop(context=context, parameter_overrides=[ + Parameter(name, value=value) for name, value in params.items()]) + try: + node.load(String(data=URDF)) + assert node.teleop.limits['joint_2'] == (0.0, 0.0) + assert node.teleop.limits['tool_grip'] == (0.0, 0.0) + assert node.teleop.limits['joint_1'][0] < node.teleop.limits['joint_1'][1] + finally: + node.destroy_node() + rclpy.try_shutdown(context=context) + + def test_a_stick_wavering_at_a_limit_rumbles_at_most_once_a_second(node, monkeypatch): clock = Clock() monkeypatch.setattr(xbox_teleop_node, 'time', clock) @@ -216,7 +233,7 @@ def step(*pressed, **axes): # The base group's right stick pushes the elbow into its limit, past the deadzone every # other tick, so the arm is blocked and released 60 times a second. for index in range(round(2.5 / period)): - step(right_y=0.2 if index % 2 == 0 else 0.0) + step(right_y=-0.2 if index % 2 == 0 else 0.0) starts = [at for at, intensity in rumbles if intensity > 0] assert starts[0] == first assert len(starts) == 3 diff --git a/waybionic_teleop/waybionic_teleop/arm_profile.py b/waybionic_teleop/waybionic_teleop/arm_profile.py new file mode 100644 index 00000000..7f5a9059 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/arm_profile.py @@ -0,0 +1,100 @@ +""" +How one physical arm differs from the arm map in config/arm_drives.yaml. + +The map describes every drive the arm is designed with. A profile is a small YAML file that +says which of them this arm actually has on its bus, and holds still each joint that no +fitted drive moves, at the angle it is fixed at, so the model in RViz matches the arm: + + # The shoulder motor is not wired yet; the shoulder is fixed upright. + fitted_drives: [base_yaw, elbow, wrist_left, wrist_right] + locked_joints: {joint_2: 0.0, tool_grip: 0.0} + +Angles are in radians, in the joint's URDF frame. The drive node publishes a locked joint at +its angle and refuses commands that would move it; teleop treats it as a joint whose limits +are that angle. +""" + +from dataclasses import dataclass, field +import math + +import yaml + +KEYS = {'fitted_drives', 'locked_joints'} + + +@dataclass(frozen=True) +class ArmProfile: + # None means every drive in the map is fitted. + fitted_drives: tuple = None + locked_joints: dict = field(default_factory=dict) + + +def load_profile(path): + """Return the ArmProfile in the YAML file at path, or the default one for no path.""" + if not path: + return ArmProfile() + try: + with open(path, encoding='utf-8') as stream: + data = yaml.safe_load(stream) + except (OSError, yaml.YAMLError) as error: + raise ValueError(f'cannot read the arm profile {path}: {error}') from None + return profile_from_dict(data if data is not None else {}, path) + + +def profile_from_dict(data, source='the arm profile'): + if not isinstance(data, dict): + raise ValueError(f'{source} must be a mapping') + unknown = sorted(set(data) - KEYS) + if unknown: + raise ValueError(f'{source} has unknown keys {unknown}; expected {sorted(KEYS)}') + fitted = data.get('fitted_drives') + if fitted is not None: + if (not isinstance(fitted, list) or not fitted + or any(not isinstance(name, str) for name in fitted) + or len(set(fitted)) != len(fitted)): + raise ValueError(f'{source}: fitted_drives must list distinct drive names') + fitted = tuple(fitted) + locked = data.get('locked_joints') or {} + if not isinstance(locked, dict) or any(not isinstance(joint, str) for joint in locked): + raise ValueError(f'{source}: locked_joints must map joint names to angles') + angles = {} + for joint, angle in locked.items(): + if isinstance(angle, bool) or not isinstance(angle, (int, float)) or not math.isfinite( + angle): + raise ValueError(f'{source}: locked joint {joint} needs a finite angle in radians') + angles[joint] = float(angle) + return ArmProfile(fitted, angles) + + +def fit_drive_parameters(params, profile): + """ + Return the drive node's parameters with only the profile's fitted drives. + + Every joint that only an unfitted drive moves must be locked, or nothing would report + where it is. + """ + drives = list(params['drives']) + if profile.fitted_drives is None: + fitted = drives + else: + unknown = sorted(set(profile.fitted_drives) - set(drives)) + if unknown: + raise ValueError(f'the arm profile fits drives {unknown} that the arm map lacks') + fitted = [name for name in drives if name in profile.fitted_drives] + + def joints(names): + try: + return {joint for name in names for joint in params[f'{name}.joints']} + except KeyError as missing: + raise ValueError(f'missing drive parameter {missing}') from None + driven = joints(fitted) + unknown_locked = sorted(set(profile.locked_joints) - joints(drives)) + if unknown_locked: + raise ValueError(f'the arm profile locks joints {unknown_locked} that the arm map lacks') + moved = sorted(driven & set(profile.locked_joints)) + if moved: + raise ValueError(f'locked joints {moved} are moved by fitted drives') + loose = sorted(joints(drives) - driven - set(profile.locked_joints)) + if loose: + raise ValueError(f'no fitted drive moves {loose}; lock them in the arm profile') + return {**params, 'drives': fitted} diff --git a/waybionic_teleop/waybionic_teleop/autoplay_node.py b/waybionic_teleop/waybionic_teleop/autoplay_node.py index 752818fe..9a7ac2b6 100644 --- a/waybionic_teleop/waybionic_teleop/autoplay_node.py +++ b/waybionic_teleop/waybionic_teleop/autoplay_node.py @@ -27,6 +27,7 @@ from waybionic_teleop.demo_script import ( DemoPlayer, operator_active, PIVOT, STALE_S, TeleopState) from waybionic_teleop.kinematics import ArmKinematics +from waybionic_teleop.ros_shutdown import is_shutdown_error HOME_TOLERANCE_RAD = 0.01 @@ -207,6 +208,9 @@ def main(): 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() diff --git a/waybionic_teleop/waybionic_teleop/drive_map.py b/waybionic_teleop/waybionic_teleop/drive_map.py index a0913d2d..3c0bca73 100644 --- a/waybionic_teleop/waybionic_teleop/drive_map.py +++ b/waybionic_teleop/waybionic_teleop/drive_map.py @@ -69,10 +69,14 @@ def to_counts(self, positions): return [round(angle / (2 * math.pi) * self.counts_per_rev) for angle in self._shaft(positions)] + def shaft_rpm(self, velocities): + """Return each drive's signed shaft speed in rpm (positive counts up) for rad/s.""" + rates = self._shaft({joint: velocities.get(joint, 0.0) for joint in self.joints}) + return [rate * 60.0 / (2 * math.pi) for rate in rates] + def to_rpm(self, velocities): """Return each drive's shaft speed in rpm for joint velocities in rad/s.""" - rates = self._shaft({joint: velocities.get(joint, 0.0) for joint in self.joints}) - return [abs(rate) * 60.0 / (2 * math.pi) for rate in rates] + return [abs(rate) for rate in self.shaft_rpm(velocities)] def to_positions(self, counts): """Return joint positions in radians from one encoder reading per drive.""" diff --git a/waybionic_teleop/waybionic_teleop/frame_log.py b/waybionic_teleop/waybionic_teleop/frame_log.py new file mode 100644 index 00000000..d29a1c3b --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/frame_log.py @@ -0,0 +1,76 @@ +"""Record every frame the drive node sends, receives or gets refused, for bench analysis.""" + +import time + + +def parse_line(line): + """Return (host time, kind, can_id, data) for a line that RecordingBus wrote.""" + stamp, kind, frame = line.split() + can_id, data = frame.split('#') + return float(stamp), kind, int(can_id, 16), bytes.fromhex(data) + + +class RecordingBus: + """ + Pass frames through to a bus, writing one line per frame to a file. + + Each line is the host's wall-clock time, the kind and the frame, such as + ``1793438841.369542 tx 001#F5008200FFE3A09A``. Kinds: tx (queued to the bus), unsent (the + bus was unplugged), rx (a frame the bus received) and refused (a frame the carrier or the + bus refused after send() returned True). + + The recording never gets in the way of the drives: if the file cannot be written or closed, + such as on a full disk, report() is called once with the reason and recording stops. + """ + + def __init__(self, bus, path, report=None): + self.bus = bus + self.path = path + self.report = report or (lambda message: None) + self.file = open(path, 'a', encoding='ascii', buffering=1 << 16) + + def __getattr__(self, name): + return getattr(self.bus, name) + + def send(self, can_id, data): + sent = self.bus.send(can_id, data) + self._write('tx' if sent else 'unsent', can_id, data) + return sent + + def receive(self, *args, **kwargs): + frame = self.bus.receive(*args, **kwargs) + if frame is not None: + self._write('rx', *frame) + return frame + + def take_refused(self): + refused = self.bus.take_refused() + for can_id, data in refused: + self._write('refused', can_id, data) + return refused + + def shutdown(self): + try: + self.bus.shutdown() + finally: + self._stop_recording() + + def _write(self, kind, can_id, data): + if self.file is None: + return + try: + self.file.write( + f'{time.time():.6f} {kind} {can_id:03X}#{bytes(data).hex().upper()}\n') + except OSError as error: + self._stop_recording(error) + + def _stop_recording(self, error=None): + file, self.file = self.file, None + if file is None: + return + try: + file.close() + except OSError as close_error: + error = error or close_error + if error is not None: + self.report(f'Stopped recording drive frames to {self.path}: {error}') diff --git a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py index 2f49e9fe..f5f2559b 100644 --- a/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py +++ b/waybionic_teleop/waybionic_teleop/joy_udp_receiver.py @@ -10,13 +10,13 @@ from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from sensor_msgs.msg import Joy, JoyFeedback from waybionic_teleop.gamepad import (AXES, BUTTONS, pack_ping, pack_rumble, PACKET_SIZE, PONG_MAGIC, unpack, unpack_pong) +from waybionic_teleop.ros_shutdown import is_shutdown_error # What a connected packet with centred sticks, released triggers and no buttons unpacks to. NEUTRAL = ([0.0] * len(AXES), [0] * len(BUTTONS)) @@ -240,14 +240,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise except RuntimeError as error: - # Jazzy may surface this binding error when SIGINT invalidates a subscription. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): + if not is_shutdown_error(error): raise finally: node.socket.close() diff --git a/waybionic_teleop/waybionic_teleop/mks_can.py b/waybionic_teleop/waybionic_teleop/mks_can.py index f28e3c43..1004827e 100644 --- a/waybionic_teleop/waybionic_teleop/mks_can.py +++ b/waybionic_teleop/waybionic_teleop/mks_can.py @@ -7,12 +7,16 @@ """ COUNTS_PER_REV = 0x4000 +ERROR_COUNTS_PER_REV = 51200 MAX_SPEED_RPM = 3000 MIN_AXIS, MAX_AXIS = -0x800000, 0x7FFFFF # Every drive acts on a frame to this ID, and none replies (manual part 5, note 1). BROADCAST_ID = 0 READ_ENCODER = 0x31 +READ_RAW_ENCODER = 0x35 +READ_POSITION_ERROR = 0x39 +READ_ZERO_STATUS = 0x3B SET_MODE = 0x82 SET_BITRATE = 0x8A SET_CAN_ID = 0x8B @@ -80,12 +84,51 @@ def read_encoder(can_id): def encoder_value(arguments): - """Decode the signed 48-bit value of a 31h reply.""" + """Decode the signed 48-bit value of a 31h or 35h reply.""" if len(arguments) != 6: raise ValueError('an encoder reply carries 6 bytes') return int.from_bytes(arguments, 'big', signed=True) +def read_raw_encoder(can_id): + """ + Request the raw cumulative encoder value (35h), which a zero (92h) leaves alone. + + It counts from the shaft's magnetic angle at power-on, so it minus the 31h value stays the + same from one zero until the drive loses power (bench, firmware V1.0.9). + """ + return frame(can_id, READ_RAW_ENCODER) + + +def read_position_error(can_id): + """Request motor-shaft position error (39h), not a fault code or force measurement.""" + return frame(can_id, READ_POSITION_ERROR) + + +def position_error_value(arguments): + """Decode signed int32 position error; 51200 units represent one motor turn.""" + if len(arguments) != 4: + raise ValueError('a position error reply carries four bytes') + return int.from_bytes(arguments, 'big', signed=True) + + +def read_zero_status(can_id): + """Request the zero status (3Bh); zero_is_set reads its reply.""" + return frame(can_id, READ_ZERO_STATUS) + + +def zero_is_set(arguments): + """ + Return whether a 3Bh reply says the axis was zeroed since power-on. + + The drives answer two bytes, the second 1 after a zero (92h) and 2 from power-on until one + (bench, firmware V1.0.9). + """ + if len(arguments) != 2: + raise ValueError('a zero status reply carries 2 bytes') + return arguments[1] == 1 + + def set_mode(can_id, mode=MODE_SR_VFOC): """Select the work mode (82h); SR_vFOC is bus control with FOC.""" return frame(can_id, SET_MODE, [mode]) diff --git a/waybionic_teleop/waybionic_teleop/mks_setup.py b/waybionic_teleop/waybionic_teleop/mks_setup.py index 3fdb429f..233b345e 100644 --- a/waybionic_teleop/waybionic_teleop/mks_setup.py +++ b/waybionic_teleop/waybionic_teleop/mks_setup.py @@ -5,6 +5,7 @@ in arm_drives.yaml, then move every drive to the bus bit rate and check they all answer: ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 scan + ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 read-error 3 ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 set-id 1 3 ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 set-bitrate 3 1000000 ros2 run waybionic_teleop mks_setup --channel /dev/cu.usbmodem1101 --bitrate 1000000 scan @@ -28,6 +29,11 @@ def open_bus(interface, channel, bitrate, tty_baudrate): return CanBus(interface, channel, bitrate) +def reserved_ids(bus): + """Return the CAN IDs the interface itself uses, which no drive can answer from.""" + return getattr(bus, 'reserved_ids', frozenset()) + + def request(bus, can_id, data, code, answer_ids=None, timeout=0.2): """Send a frame; return the arguments of the reply with this code, or None.""" answer_ids = answer_ids or {can_id} @@ -46,9 +52,13 @@ def request(bus, can_id, data, code, answer_ids=None, timeout=0.2): time.sleep(0.002) continue reply_id, reply = frame + if reply_id in reserved_ids(bus): + continue try: reply_code, arguments = mks_can.parse(reply_id, reply) - except ValueError: + except ValueError as error: + if reply_id in answer_ids: + raise SystemExit(str(error)) from error continue if reply_id in answer_ids and reply_code == code: return arguments @@ -65,10 +75,26 @@ def scan(bus, ids): return found +def read_error(bus, can_id): + """Read signed position error without changing the drive's configuration or motion.""" + arguments = request( + bus, can_id, mks_can.read_position_error(can_id), mks_can.READ_POSITION_ERROR) + if arguments is None: + raise SystemExit(f'CAN ID {can_id} did not report its position error (39h)') + try: + return mks_can.position_error_value(arguments) + except ValueError as error: + raise SystemExit(f'CAN ID {can_id}: {error}') from error + + def set_id(bus, old, new): """Give the drive at old the CAN ID new; return a message, or raise SystemExit.""" if old == new: raise SystemExit(f'the drive already has CAN ID {new}') + reserved = sorted({old, new} & reserved_ids(bus)) + if reserved: + raise SystemExit(f"CAN ID {reserved[0]} is reserved for the carrier's status; " + 'no drive can answer from it through the carrier') if scan(bus, [new]): raise SystemExit(f'CAN ID {new} is taken; connect only the drive to change') if not scan(bus, [old]): @@ -140,6 +166,9 @@ def main(argv=None): commands = parser.add_subparsers(dest='command', required=True) scan_command = commands.add_parser('scan', help='list the drives that answer') scan_command.add_argument('--ids', type=int, nargs='+', default=list(range(1, 17))) + error_command = commands.add_parser( + 'read-error', help='read signed motor position error (39h); does not move the motor') + error_command.add_argument('can_id', type=int) id_command = commands.add_parser('set-id', help='give one drive a new CAN ID') id_command.add_argument('old', type=int) id_command.add_argument('new', type=int) @@ -149,6 +178,11 @@ def main(argv=None): commands.add_parser('stop', help='stop every drive at once (F7h to broadcast ID 0); give ' "the drives' --bitrate") args = parser.parse_args(argv) + if args.command == 'read-error' and ( + not 1 <= args.can_id <= 0x7FF + or args.interface == 'slcan' and args.can_id == carrier.STATUS_ID): + parser.error('read-error needs a drive CAN ID from 1 to 2047, excluding carrier ID 2032 ' + 'on the carrier') bus = open_bus(args.interface, args.channel, args.bitrate, args.tty_baudrate) try: @@ -164,6 +198,11 @@ def main(argv=None): print(set_id(bus, args.old, args.new)) elif args.command == 'set-bitrate': print(set_bitrate(bus, args.can_id, args.rate)) + elif args.command == 'read-error': + error = read_error(bus, args.can_id) + degrees = error * 360.0 / mks_can.ERROR_COUNTS_PER_REV + print(f'CAN ID {args.can_id}: position error {degrees:+.6f} motor deg ' + f'({error:+d} error counts)') else: stop = mks_can.emergency_stop(mks_can.BROADCAST_ID) if not send_confirmed(bus, mks_can.BROADCAST_ID, stop): diff --git a/waybionic_teleop/waybionic_teleop/ros_shutdown.py b/waybionic_teleop/waybionic_teleop/ros_shutdown.py new file mode 100644 index 00000000..32a72da6 --- /dev/null +++ b/waybionic_teleop/waybionic_teleop/ros_shutdown.py @@ -0,0 +1,36 @@ +"""Tell an error from a node shutting down on SIGINT apart from a real failure.""" + +import time + +import rclpy + +# How long to wait for rclpy to finish shutting the context down. +SHUTDOWN_GRACE_S = 1.0 + +# Errors spin can raise once SIGINT has started invalidating the ROS context. +SHUTDOWN_ERRORS = ( + # SIGINT can shut down the context before spin recreates its wait set. + 'the given context is not valid', + # Jazzy's binding error when a subscription's context is invalidated. + "Unable to convert call argument '0' to Python object", + # tf2 can no longer read a lookup time once the context is invalid. + 'time must have sec and nanosec', +) + + +def is_shutdown_error(error): + """ + Return whether spin raised this error only because ROS is shutting down. + + On SIGINT, rclpy's signal thread wakes every executor before it shuts the contexts + down, so spin can fail while rclpy.ok() is still true. Wait briefly for the shutdown + to land: the same error while ROS keeps running is a real failure. + """ + if not any(text in str(error) for text in SHUTDOWN_ERRORS): + return False + deadline = time.monotonic() + SHUTDOWN_GRACE_S + while rclpy.ok(): + if time.monotonic() >= deadline: + return False + time.sleep(0.01) + return True diff --git a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py index f2f4a6cb..0efe5d71 100644 --- a/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py +++ b/waybionic_teleop/waybionic_teleop/sim_arm_drives_node.py @@ -9,7 +9,13 @@ The encoders count from where the drives were powered on, so nothing moves until every drive has been zeroed with the arm in the zero pose: at start-up in simulation, and through the ``~/zero`` service on real drives. A drive that stops answering is treated as power-cycled: -every drive stops and the arm must be zeroed again. +every drive stops and the arm must be zeroed again. With ``zero_state`` naming a file, each +zero is saved there, and a drive keeps it, at start-up or once it answers again, if it shows +it has not lost power since: see ``check_zero``. + +``arm_profile`` names a file (waybionic_teleop/arm_profile.py) that lists the drives this arm +has fitted; each joint no fitted drive moves is published at its locked angle, and a command +must leave it there. 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 @@ -17,15 +23,25 @@ drive stops where it is, whatever speed it was last given, so a publisher that dies cannot leave the arm running on to its last target. After any stop, teleop must be disabled and enabled again before the arm moves. + +A drive never gets a target behind a move it is running. MKS firmware V1.0.9 can keep such a +target and run to it on its own once the moves stop, even after a stop frame, so a drive is +stopped first, and after any stop of a running move it starts a new one only once its encoder +has stopped advancing. The firmware also keeps an occasional target sent mid-move, and runs +back to it once the move stops, however it stops. So every stop of a running move is followed +at once by a target where the drive is to stay, sent again every tick for ``HOLD_S``, which +takes such a run over within a tick. A drive that turns more than ``following_error_counts`` +after its stop while the arm is enabled stops every drive. """ +import datetime import math +import os import time from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue from rcl_interfaces.msg import SetParametersResult import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.qos import DurabilityPolicy, QoSProfile @@ -39,9 +55,13 @@ DriveHealthThresholds, ) from waybionic_teleop import carrier, 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 from waybionic_teleop.kinematics import joint_limits +from waybionic_teleop.ros_shutdown import is_shutdown_error from waybionic_teleop.sim_drives import SimulatedBus, SimulatedServo +import yaml REPLY_TIMEOUT_S = 0.5 REPORT_PERIOD_S = 0.5 @@ -56,6 +76,28 @@ # F5 replies of a drive that no longer follows its targets: run failed, as when stall # protection releases the motor, and stopped at an end limit. 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 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. +SETTLE_S = 0.012 +SETTLED_STEP_COUNTS = 5 +# A drive at rest starts a move only toward a target this far ahead in the commanded +# direction, so a target that its stop overshot never starts a move the wrong way. +START_DEADBAND_COUNTS = 30 +# After the stop of a running move, a drive gets its hold target right behind the stop and +# again every tick for HOLD_S, at HOLD_RPM at most. On the bench (firmware V1.0.9, base, 80 +# stops each), no run back to a kept target started with the hold right behind the stop, and +# none went past 107 counts; with the hold 1 ms later, 5 started and ended within 437 counts, +# and with only a re-target once a run showed, 7 ran up to 2515 counts. +HOLD_RPM = 60 +HOLD_S = 0.25 +# A drive keeps its zero across a restart of this node only while its zero status says it was +# zeroed since power-on and its raw-minus-zeroed encoder offset is the one saved at the zero, +# give or take the counts it turns between two replies at rest (bench: 2 at most). +ZERO_MATCH_COUNTS = 16 +ZERO_CHECK_TIMEOUT_S = 2.0 def status(name, level, value, unit, message, **extra): @@ -72,6 +114,10 @@ def __init__(self, **kwargs): **kwargs) params = {name: self.get_parameter(name).value for name in self.list_parameters([], 0).names} + # Joints whose drive this arm lacks hold still at the profile's angles. + profile = load_profile(params.get('arm_profile', '')) + params = fit_drive_parameters(params, profile) + self.locked = dict(profile.locked_joints) self.map = drive_map_from_parameters(params, mks_can.COUNTS_PER_REV) self.acc = int(params['acc']) self.max_rpm = int(params['max_rpm']) @@ -104,8 +150,9 @@ def __init__(self, **kwargs): if self.interface != 'sim': # Real drives move only joints whose URDF limits are known. unmodeled = set() - elif not unmodeled <= set(self.map.joints): + elif not unmodeled <= set(self.map.joints) | set(self.locked): raise ValueError('unmodeled_joints must name drives in the simulated map') + unmodeled -= set(self.locked) self.modeled_joints = [joint for joint in self.map.joints if joint not in unmodeled] if not self.modeled_joints: raise ValueError('at least one drive joint needs a URDF limit') @@ -128,6 +175,10 @@ def __init__(self, **kwargs): from waybionic_teleop.can_bus import CanBus self.bus = CanBus(self.interface, channel, self.bitrate) self.bus_label = f'{self.interface} {channel}' + if frame_log := params.get('frame_log', ''): + self.bus = RecordingBus(self.bus, os.path.expanduser(frame_log), + self.get_logger().error) + self.get_logger().info(f'Recording every drive frame to {frame_log}') self.test_fault = None if self.interface == 'sim': self.declare_parameter('test_fault', 'none') @@ -145,6 +196,17 @@ def __init__(self, **kwargs): self.setup_time = [None] * len(drives) self.state = ['starting'] * len(drives) self.sent = [None] * len(drives) + # Each drive's running move: +1 or -1 counts up or down, 0 at rest. After the stop of + # a running move, (time of the stop, its direction) until the drive has settled. + self.direction = [0] * len(drives) + self.settling = [None] * len(drives) + # Where each drive was told to stay at its last stop, which it must keep, and until + # when that target goes out again every tick, with the tick it last went out. + self.held = [None] * len(drives) + self.hold_until = [-math.inf] * len(drives) + self.hold_tick = [-1] * len(drives) + self.ticks = 0 + self.completed = [-math.inf] * len(drives) self.drive_health_monitors = [ DriveHealthMonitor(health_thresholds) for _ in drives] self.drive_health_states = [None] * len(drives) @@ -167,6 +229,10 @@ def __init__(self, **kwargs): self.awaiting_release = True self.rejected = 0 self.bus_errors = 0 + # The file the zero is saved in, each drive's saved offset (see check_zero), the + # offsets read since the last zero, and the drives whose zero is being checked. + self.zero_state = os.path.expanduser(params.get('zero_state', '') or '') + self.saved_zero, self.zero_offsets, self.checks = {}, {}, {} if self.interface == 'sim': self.add_on_set_parameters_callback(self.on_test_fault_parameter) for index in range(len(drives)): @@ -174,6 +240,10 @@ def __init__(self, **kwargs): zero_on_start = params.get('zero_on_start', self.interface == 'sim') if zero_on_start: self.zero() + else: + self.saved_zero = self.load_zero() + for index in self.saved_zero: + self.check_zero(index, 'restore') self.stop_reason = 'Waiting for robot_description and a released Start button' topic = params.get('diagnostics_topic', '/diagnostics') latched = QoSProfile(depth=1, durability=DurabilityPolicy.TRANSIENT_LOCAL) @@ -193,7 +263,10 @@ def __init__(self, **kwargs): self.get_logger().info(f'Simulated drives: {drive_list} (no hardware)') else: self.get_logger().info(f'MKS drives on {self.bus_label}: {drive_list}') - if not zero_on_start: + if self.checks: + self.get_logger().info( + f'Checking whether the drives kept the zero saved in {self.zero_state}') + elif not zero_on_start: self.get_logger().warning(f'Not zeroed. {self.zero_hint()}') def zero_hint(self): @@ -220,10 +293,14 @@ def stop_all(self, reason): def zero(self): """Make the current pose every drive's zero.""" + # A hold in the old coordinates would move the arm after the zero, so none goes out. + self.zeroed = [False] * len(self.map.drives) + self.forget_zero() self.stop_all('Zeroing the drives') + self.held = [None] * len(self.map.drives) + self.hold_until = [-math.inf] * len(self.map.drives) for drive in self.map.drives: self.bus.send(drive.can_id, mks_can.set_zero(drive.can_id)) - self.zeroed = [False] * len(self.map.drives) def on_zero(self, request, response): if time.monotonic() - self.command_time < QUIET_BEFORE_ZERO_S: @@ -241,6 +318,115 @@ def on_zero(self, request, response): self.get_logger().info(response.message) return response + def check_zero(self, index, purpose): + """ + Read a drive's zero fingerprint, to save it after a zero or restore it with ``restore``. + + The raw encoder (35h) counts from power-on and a zero leaves it alone, so it minus the + zeroed count stays the same from one zero until the drive loses power, and the zero + status (3Bh) says whether the drive was zeroed since power-on. A drive keeps its saved + zero only if its status shows a zero, which a power cycle clears, and its offset is the + saved one, which a zero made elsewhere would change. + """ + self.checks[index] = {'purpose': purpose, 'raw': None, 'count': None, 'set': None, + 'deadline': time.monotonic() + ZERO_CHECK_TIMEOUT_S} + + def send_checks(self, now): + for index, check in list(self.checks.items()): + drive = self.map.drives[index] + if self.heard[index] is None or now - self.heard[index] > REPLY_TIMEOUT_S: + # The check times out only while the drive answers, as the carrier may still + # be starting. + check['deadline'] = now + ZERO_CHECK_TIMEOUT_S + continue + if now > check['deadline']: + del self.checks[index] + self.get_logger().warning( + f'{drive.name} did not report its zero status, so its zero is ' + + ('not saved' if check['purpose'] == 'save' + else f'not restored. {self.zero_hint()}')) + continue + if check['raw'] is None: + self.bus.send(drive.can_id, mks_can.read_raw_encoder(drive.can_id)) + if check['set'] is None: + self.bus.send(drive.can_id, mks_can.read_zero_status(drive.can_id)) + + def finish_check(self, index): + check = self.checks[index] + if None in (check['raw'], check['count'], check['set']): + return + del self.checks[index] + name = self.map.drives[index].name + offset = check['raw'] - check['count'] + if check['purpose'] == 'save': + if not check['set']: + 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): + self.save_zero() + return + saved = self.saved_zero[index] + if not check['set']: + reason = 'lost power since its last zero' + elif abs(offset - saved) > ZERO_MATCH_COUNTS: + reason = f'was zeroed elsewhere since (offset {offset}, saved {saved})' + else: + self.zeroed[index] = True + # Its last hold is from before it went quiet, so it gets a new one at its next stop. + self.held[index], self.hold_until[index] = None, -math.inf + self.get_logger().info(f'{name} kept its zero') + if all(self.zeroed): + self.get_logger().info('Every drive kept its zero; teleop can be enabled') + return + self.get_logger().warning(f'{name} {reason}, so it is not zeroed. {self.zero_hint()}') + + def load_zero(self): + """Return each drive's saved offset by index, for the drives the zero file names.""" + if not self.zero_state: + return {} + try: + with open(self.zero_state, encoding='utf-8') as file: + saved = yaml.safe_load(file)['drives'] + return {index: int(saved[drive.name]['offset']) + for index, drive in enumerate(self.map.drives) + if drive.name in saved and int(saved[drive.name]['can_id']) == drive.can_id} + except FileNotFoundError: + return {} + except (OSError, yaml.YAMLError, AttributeError, KeyError, TypeError, + ValueError) as error: + self.get_logger().warning(f'Ignoring the zero saved in {self.zero_state}: {error}') + return {} + + 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)} + saved = {'saved': datetime.datetime.now().isoformat(timespec='seconds'), + 'drives': drives} + partial = self.zero_state + '.partial' + try: + os.makedirs(os.path.dirname(self.zero_state) or '.', exist_ok=True) + with open(partial, 'w', encoding='utf-8') as file: + yaml.safe_dump(saved, file, sort_keys=False) + os.replace(partial, self.zero_state) + except OSError as error: + self.get_logger().warning(f'Could not save the zero to {self.zero_state}: {error}') + return + self.saved_zero = dict(self.zero_offsets) + self.get_logger().info(f'Saved the zero to {self.zero_state}') + + def forget_zero(self): + """Drop the saved zero, so no later start or reconnect restores it.""" + self.saved_zero, self.zero_offsets, self.checks = {}, {}, {} + if not self.zero_state: + return + try: + os.remove(self.zero_state) + except FileNotFoundError: + pass + except OSError as error: + self.get_logger().warning(f'Could not remove {self.zero_state}: {error}') + def on_description(self, message): self.disarm('Robot description changed', require_release=True) try: @@ -277,7 +463,14 @@ def disarm(self, reason, require_release=False): self.awaiting_release = self.awaiting_release or require_release self.commanded = None self.velocities.clear() - self.sent = [None] * len(self.map.drives) + # A drive whose stop has not gone out yet still runs its last move. + self.sent = [sent if index in self.stopping else None + for index, sent in enumerate(self.sent)] + # The stops just sent must settle before a fresh Start moves those drives again. + now = time.monotonic() + self.settling = [(now, direction) if direction else settling + for direction, settling in zip(self.direction, self.settling)] + self.direction = [0] * len(self.map.drives) self.stop_reason = reason def on_command(self, message): @@ -285,13 +478,20 @@ def on_command(self, message): if not self.authorized or self.commanded is None: return names = message.name - if (len(names) != len(self.map.joints) or set(names) != set(self.map.joints) + expected = set(self.map.joints) | set(self.locked) + if (len(names) != len(expected) or set(names) != expected or len(message.position) != len(names) or len(message.velocity) != len(names) or any(not math.isfinite(value) for value in message.position) or any(not math.isfinite(value) for value in message.velocity)): self.reject_command('incomplete, duplicate or nonfinite joint command') return positions = dict(zip(names, message.position)) + velocities = dict(zip(names, message.velocity)) + for joint, angle in self.locked.items(): + if abs(positions.pop(joint) - angle) > LOCKED_TOLERANCE_RAD: + self.reject_command(f'{joint} is locked at {angle:g} rad') + return + del velocities[joint] measured = self.map.to_positions(self.counts) for joint, (lower, upper) in self.limits.items(): position, actual = positions[joint], measured[joint] @@ -301,7 +501,7 @@ def on_command(self, message): self.reject_command(f'{joint} target outside its URDF range') return self.commanded = positions - self.velocities = dict(zip(names, message.velocity)) + self.velocities = velocities # Send now rather than at the next tick, unless that tick will stop the drives. now = time.monotonic() if (now - self.last_tick < self.heartbeat_s and self.feedback_fresh(now) @@ -323,6 +523,7 @@ def reject_command(self, reason): def tick(self): now = time.monotonic() dt, self.last_tick = now - self.last_tick, now + self.ticks += 1 # The old motion must consume the entire elapsed host time before any new frame # can reset its heartbeat. A pause requires a released and newly pressed Start. self.bus.step(dt) @@ -354,6 +555,8 @@ def tick(self): self.disarm('Teleop enable timed out', require_release=True) if self.authorized and self.commanded is not None: self.send_targets() + self.send_holds(now) + self.send_checks(now) for index, drive in enumerate(self.map.drives): self.bus.send(drive.can_id, mks_can.read_encoder(drive.can_id)) self.unanswered[index] += 1 @@ -365,6 +568,7 @@ def tick(self): if self.commanded is None: # Hold the actual encoder pose while disarmed, including after a host pause. self.commanded = dict(positions) + positions.update(self.locked) message = JointState(name=list(positions), position=list(positions.values())) message.header.stamp = self.get_clock().now().to_msg() self.state_publisher.publish(message) @@ -384,23 +588,43 @@ def lose(self, index, reason): """Treat a drive as power-cycled: every drive stops until the arm is zeroed again.""" name = self.map.drives[index].name self.lost[index], self.zeroed[index] = True, False + self.checks.pop(index, None) self.stop_all(f'{name} {reason}') self.get_logger().error(f'{name} {reason}; every drive is stopped') def check_following(self): for index, (sent, count) in enumerate(zip(self.sent, self.counts)): - axis = sent[0] if self.authorized and sent else None - if axis is None or count is None or abs(axis - count) <= self.following_error: + # 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 + if self.authorized and sent: + target = self.held[index] if sent[0] is None else sent[0] + elif not self.authorized and index not in self.stopping and self.zeroed[index]: + target = self.held[index] + if target is None or count is None or abs(target - count) <= self.following_error: self.behind[index] = 0 continue self.behind[index] += 1 - if self.behind[index] >= self.following_ticks: - self.fault(index, f'is {abs(axis - count)} counts from its target') + if self.behind[index] < self.following_ticks: + continue + if self.authorized and sent[0] is not None: + self.fault(index, f'is {abs(target - count)} counts from its target') + continue + # Its encoder still counts true, so the arm keeps its zero. Its last stop did not + # hold it, so it gets another, and no hold drives it back that far. + name = self.map.drives[index].name + reason = f'{name} turned {count - target:+d} counts after its stop' + self.held[index], self.hold_until[index] = None, -math.inf + self.stopping.add(index) + self.stop_all(reason) + self.get_logger().error(f'{reason}; every drive is stopped') def fault(self, index, reason): """Stop every drive after one stops following; the arm must be zeroed again.""" name = self.map.drives[index].name self.zeroed[index] = False + # A restart must not bring back a zero the arm no longer follows. + self.forget_zero() self.stop_all(f'{name} {reason}') self.get_logger().error(f'{name} {reason}; every drive is stopped. {self.zero_hint()}') @@ -413,41 +637,111 @@ def stop_drives(self): def send_stops(self): # A refused stop goes out again on every tick, as the encoder polls keep the drive's # heartbeat from stopping it. + now = time.monotonic() for index in sorted(self.stopping): drive = self.map.drives[index] data = mks_can.stop(drive.can_id, 0) + # The hold is where the drive is once the stop goes out, not when it was asked for. + target, running = self.hold_target(index, now) if self.bus.send(drive.can_id, data): self.stopping.discard(index) - self.sent[index] = (None, 0) + self.sent[index], self.held[index] = (None, 0), target self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + self.hold_until[index] = -math.inf + if running: + self.start_hold(index, now) def send_targets(self): try: moves = self.map.synchronized(self.commanded, self.counts, self.period, self.max_rpm, self.velocities) - motor_rates = self.map.to_rpm(self.velocities) + motor_rates = self.map.shaft_rpm(self.velocities) commands = [] # Preflight every int24 axis and frame before sending any coupled motor an update. - for drive, (axis, speed), rpm in zip(self.map.drives, moves, motor_rates): + for drive, (axis, speed) in zip(self.map.drives, moves): if not mks_can.MIN_AXIS <= axis <= mks_can.MAX_AXIS: raise ValueError(f'{drive.name}: axis {axis} is outside int24') - if rpm == 0.0: - key = (None, 0) - data = mks_can.absolute_axis(drive.can_id, 0, 0, 0) - else: - key = (axis, speed) - data = mks_can.absolute_axis(drive.can_id, axis, speed, self.acc) - commands.append((key, data)) + commands.append(mks_can.absolute_axis(drive.can_id, axis, speed, self.acc)) except (ValueError, OverflowError) as error: self.reject_command(f'Cannot synchronize drives: {error}') return - for index, (drive, (key, data)) in enumerate(zip(self.map.drives, commands)): - if self.sent[index] == key: - continue - # A frame the interface refused is sent again on the next tick. - if self.bus.send(drive.can_id, data): - self.sent[index] = key - self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + for index, (drive, (axis, speed), rpm, data) in enumerate( + zip(self.map.drives, moves, motor_rates, commands)): + 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)): + # A refused stop goes out again on the next tick, like a refused target. + self.hold(index) + elif direction or (abs(ahead) > START_DEADBAND_COUNTS and ahead * rpm > 0): + if self.sent[index] != (axis, speed) and self.bus.send(drive.can_id, data): + self.sent[index], self.held[index] = (axis, speed), None + self.hold_until[index] = -math.inf + self.direction[index] = direction or (1 if ahead > 0 else -1) + self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + + def hold(self, index): + """Stop one armed drive where it is; a running move must then settle.""" + if self.sent[index] != (None, 0): + drive = self.map.drives[index] + data = mks_can.stop(drive.can_id, 0) + now = time.monotonic() + target, running = self.hold_target(index, now) + if not self.bus.send(drive.can_id, data): + return + self.sent[index], self.held[index] = (None, 0), target + self.last_command[index] = mks_can.hex_frame(drive.can_id, data) + if running: + self.start_hold(index, now) + else: + self.hold_until[index] = -math.inf + if self.direction[index]: + self.settling[index] = (time.monotonic(), self.direction[index]) + self.direction[index] = 0 + + def hold_target(self, index, now): + """Return where a drive about to be stopped is to stay, and if it must be held there.""" + sent, count = self.sent[index], self.counts[index] + if self.held[index] is not None and now < self.hold_until[index]: + # A stop ends the drive's run to its hold, after which it must keep holding. + return self.held[index], True + if not sent or sent[0] is None or count is None: + return count, False + # The running move's end, though never more than a lagging drive covers in two ticks, + # or since its last count if that is older. + axis, speed = sent + reach = round(max(2 * self.period, self.since_count[index] + self.period) * speed + / 60.0 * mks_can.COUNTS_PER_REV) + START_DEADBAND_COUNTS + target = min(max(axis, count - reach), count + reach) + return min(max(target, mks_can.MIN_AXIS), mks_can.MAX_AXIS), True + + def start_hold(self, index, now): + self.hold_until[index] = now + HOLD_S + self.send_hold(index, now) + + def send_holds(self, now): + for index in range(len(self.map.drives)): + if now < self.hold_until[index] and self.hold_tick[index] != self.ticks: + self.send_hold(index, now) + + def send_hold(self, index, now): + """Send a drive its hold target, unless it may have lost the zero that target uses.""" + held, count, heard = self.held[index], self.counts[index], self.heard[index] + if (held is None or count is None or heard is None or now - heard > REPLY_TIMEOUT_S + or abs(held - count) > self.following_error or index in self.stopping + or not self.zeroed[index] or self.lost[index] or self.estop_pressed): + return + can_id = self.map.drives[index].can_id + # Not a last command: a refused hold simply goes out again on the next tick. + if self.bus.send(can_id, mks_can.absolute_axis( + can_id, held, min(HOLD_RPM, self.max_rpm), self.acc)): + self.hold_tick[index] = self.ticks + + def settle(self, index, step): + """Let a stopped drive move again once an encoder step shows it no longer runs on.""" + stopped_at, old = self.settling[index] + if ((self.completed[index] > stopped_at and abs(step) < SETTLED_STEP_COUNTS) + or (time.monotonic() - stopped_at > SETTLE_S and step * old <= 0)): + self.settling[index] = None def drain(self, now, zeroing=False): while (reply := self.bus.receive()) is not None: @@ -465,7 +759,8 @@ def on_refused(self, can_id, data, zeroing): if data[0] == mks_can.ABSOLUTE_AXIS: if self.last_command[index] != mks_can.hex_frame(can_id, data): return - # Only stops go out while disarmed, and send_stops repeats a stop until it is sent. + # While disarmed the last command is a stop, as holds never are one, and + # send_stops repeats a stop until it is sent. if self.authorized: self.sent[index] = None else: @@ -487,7 +782,9 @@ def on_reply(self, can_id, data, now): return if self.estop_pressed and not pressed: # The e-stop cuts the drives' power; Start is refused until it is released. + # A drive may restart with a new count, so no hold goes out after the release. self.stop_all('E-stop pressed') + self.hold_until = [-math.inf] * len(self.map.drives) self.get_logger().error('E-stop pressed; every drive is stopped') return index = self.index.get(can_id) @@ -503,8 +800,13 @@ def on_reply(self, can_id, data, now): # It may have been power-cycled, which loses its settings and its zero. self.lost[index] = False self.set_up(index) - self.get_logger().warning( - f'{self.map.drives[index].name} answers again. {self.zero_hint()}') + name = self.map.drives[index].name + if index in self.saved_zero: + self.check_zero(index, 'restore') + self.get_logger().warning( + f'{name} answers again; checking whether it kept its zero') + else: + self.get_logger().warning(f'{name} answers again. {self.zero_hint()}') failed = None jump = None try: @@ -517,13 +819,27 @@ def on_reply(self, can_id, data, now): if previous is not None and abs(count - previous) > most: jump = count - previous self.counts[index], self.since_count[index] = count, 0.0 + if index in self.checks: + self.checks[index]['count'] = count + if self.settling[index] is not None and previous is not None: + self.settle(index, count - previous) + elif code == mks_can.READ_RAW_ENCODER: + if index in self.checks: + self.checks[index]['raw'] = mks_can.encoder_value(arguments) + elif code == mks_can.READ_ZERO_STATUS: + if index in self.checks: + self.checks[index]['set'] = mks_can.zero_is_set(arguments) elif code == mks_can.ABSOLUTE_AXIS and arguments: self.state[index] = mks_can.RUN_STATUS.get(arguments[0], f'status {arguments[0]}') if arguments[0] in RUN_FAULTS: failed = self.state[index] + elif arguments[0] == 2: + self.completed[index] = time.monotonic() elif code == mks_can.SET_ZERO and arguments[:1] == b'\x01': # Later encoder replies were read after the zero. self.zeroed[index], self.counts[index] = True, None + if self.zero_state: + self.check_zero(index, 'save') elif arguments[:1] == b'\x00': self.state[index] = f'setup {code:02X}h failed' elif code in SETUP: @@ -538,7 +854,9 @@ def on_reply(self, can_id, data, now): if jump is not None: # A drive that browned out and restarted answers well before it counts as silent. self.lose(index, f'encoder jumped {jump:+d} counts') - # Only stop frames go out while disarmed, and a released motor refuses those too. + 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: self.fault(index, failed) @@ -567,8 +885,11 @@ def report(self): 'enabled' if self.authorized else 'stopped', '', self.stop_reason or 'Receiving validated teleop setpoints')) if not all(self.zeroed): - statuses.append(status('arm.zero', DiagnosticStatus.WARN, 'no', '', - f'Not zeroed. {self.zero_hint()}')) + 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) commanded = self.commanded or {} @@ -715,14 +1036,23 @@ def close(self): if self.interface == 'slcan': # The carrier may refuse a stop after send() returned True, and no later tick # would send it again, so write the stops now, then wait for the carrier's - # answers and repeat refused stops before closing it. + # answers and repeat refused stops before closing it. The holds behind the + # stops go out every period meanwhile, as on any tick. deadline = time.monotonic() + CLOSE_TIMEOUT_S self.drain(time.monotonic()) - while (self.bus.connected and (self.stopping or self.bus.unanswered) - and time.monotonic() < deadline): + last_hold = time.monotonic() + while self.bus.connected and time.monotonic() < deadline: + now = time.monotonic() + holding = any(now < until for until in self.hold_until) + if not (self.stopping or self.bus.unanswered or holding): + break time.sleep(0.002) - self.drain(time.monotonic()) + now = time.monotonic() + self.drain(now) self.send_stops() + if now - last_hold >= self.period: + last_hold, self.ticks = now, self.ticks + 1 + self.send_holds(now) finally: # Even if a second Ctrl+C lands here, the queued stops and C still go out. self.bus.shutdown() @@ -736,14 +1066,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise except RuntimeError as error: - # Jazzy may surface this binding error when SIGINT invalidates a subscription. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): + if not is_shutdown_error(error): raise finally: if node is not None: diff --git a/waybionic_teleop/waybionic_teleop/sim_drives.py b/waybionic_teleop/waybionic_teleop/sim_drives.py index 032a6491..4fc08b11 100644 --- a/waybionic_teleop/waybionic_teleop/sim_drives.py +++ b/waybionic_teleop/waybionic_teleop/sim_drives.py @@ -6,6 +6,11 @@ from waybionic_teleop import mks_can MAX_STEP_S = 0.01 +# Firmware V1.0.9 keeps a target behind a running move. Bench runs sent 250 targets up to one +# 120 Hz host tick of travel behind the drive without one being kept, so only a target farther +# behind than this much travel is kept here. The bench drives also kept an occasional target +# ahead of the move, which tests set as latched directly. +LATCH_MARGIN_S = 0.01 def ramp_rpm_per_s(acc): @@ -31,10 +36,17 @@ def __init__(self, can_id, bitrate=500000): self.quiet_ms = 0.0 self.heartbeat_stops = 0 self.axis = 0.0 + # The raw encoder (35h) is the axis plus this shift, which a zero (92h) grows by the + # axis it clears; power-on resets the axis to 0 at the shaft's magnetic angle. + self.raw_shift = 0 + self.zero_set = False self.rpm = 0.0 self.target = None self.speed = 0 self.acc = 0 + # Firmware V1.0.9 keeps a target that reverses a running move, as on the bench, and + # runs to it once the moves stop: at a stop, an emergency stop or the last target. + self.latched = None def set_test_fault(self, fault=None): """Activate or clear a simulator-only drive fault.""" @@ -47,7 +59,14 @@ def set_test_fault(self, fault=None): if fault == 'disabled': self._enabled_before_test_fault = self.enabled self.enabled = False - self.target, self.rpm = None, 0.0 + self.target, self.rpm, self.latched = None, 0.0, None + + def power_cycle(self, magnetic_angle=0): + """Lose power and come back where the shaft is: settings, move and zero are gone.""" + self.mode, self.enabled, self.heartbeat_ms, self.quiet_ms = None, False, 0, 0.0 + self.respond, self.active = True, True + self.target, self.rpm, self.latched, self.speed, self.acc = None, 0.0, None, 0, 0 + self.axis, self.raw_shift, self.zero_set = 0.0, int(magnetic_angle), False def receive(self, data, address=None): """Handle one command sent to address (by default this drive's ID); return the replies.""" @@ -61,6 +80,14 @@ def _handle(self, code, arguments): value = round(self.axis).to_bytes(6, 'big', signed=True) return ([mks_can.frame(self.can_id, code, value)] if self._responding() else []) + if code == mks_can.READ_RAW_ENCODER and not arguments: + value = (round(self.axis) + self.raw_shift).to_bytes(6, 'big', signed=True) + return ([mks_can.frame(self.can_id, code, value)] + if self._responding() else []) + if code == mks_can.READ_ZERO_STATUS and not arguments: + value = [2, 1 if self.zero_set else 2] + return ([mks_can.frame(self.can_id, code, value)] + if self._responding() else []) if code == mks_can.SET_MODE and len(arguments) == 1: self.mode, status = arguments[0], 1 elif code == mks_can.SET_RESPONSE and len(arguments) == 2: @@ -68,16 +95,19 @@ def _handle(self, code, arguments): elif code == mks_can.SET_HEARTBEAT and len(arguments) == 4: self.heartbeat_ms, status = int.from_bytes(arguments, 'big'), 1 elif code == mks_can.SET_ZERO and not arguments: - self.axis, self.rpm, self.target, status = 0.0, 0.0, None, 1 + self.raw_shift += round(self.axis) + self.axis, self.rpm, self.target, self.latched, status = 0.0, 0.0, None, None, 1 + self.zero_set = True elif code == mks_can.ENABLE and len(arguments) == 1: self.enabled = bool(arguments[0]) and self.test_fault != 'disabled' status = 1 if not self.enabled: - self.target, self.rpm = None, 0.0 + self.target, self.rpm, self.latched = None, 0.0, None elif code == mks_can.ABSOLUTE_AXIS and len(arguments) == 6: status = self.start_move(arguments) elif code == mks_can.EMERGENCY_STOP and not arguments: self.target, self.rpm, status = None, 0.0, 1 + self._run_latched() elif code == mks_can.SET_BITRATE and len(arguments) == 1: rates = {value: rate for rate, value in mks_can.BITRATES.items()} status = int(arguments[0] in rates) @@ -109,11 +139,23 @@ def start_move(self, arguments): self.target = None if not self.acc: self.rpm = 0.0 - return 2 + return 1 if self._run_latched() else 2 return 1 - self.target = int.from_bytes(arguments[3:], 'big', signed=True) + target = int.from_bytes(arguments[3:], 'big', signed=True) + margin = abs(self.rpm) / 60.0 * mks_can.COUNTS_PER_REV * LATCH_MARGIN_S + if (self.rpm * (target - self.axis) < 0 and abs(target - self.axis) > margin + and self.latched is None): + self.latched = (target, self.speed, self.acc) + self.target = target return 1 + def _run_latched(self): + """Start the move to a latched target, as V1.0.9 does once its moves stop.""" + if self.latched is None: + return False + (self.target, self.speed, self.acc), self.latched = self.latched, None + return True + def step(self, dt): """Advance the motor by dt seconds and return any frames it sends unprompted.""" frames = [] @@ -154,6 +196,8 @@ def _advance(self, dt): remaining = self.target - self.axis if abs(remaining) < 0.5 or (move * remaining > 0 and abs(move) >= abs(remaining)): self.axis, self.rpm, self.target = float(self.target), 0.0, None + if self._run_latched(): + return [] if self._responding() and self.active: return [mks_can.frame(self.can_id, mks_can.ABSOLUTE_AXIS, [2])] return [] diff --git a/waybionic_teleop/waybionic_teleop/slcan_bus.py b/waybionic_teleop/waybionic_teleop/slcan_bus.py index 08133f17..04d2abcc 100644 --- a/waybionic_teleop/waybionic_teleop/slcan_bus.py +++ b/waybionic_teleop/waybionic_teleop/slcan_bus.py @@ -12,14 +12,22 @@ followed by an empty line, which the carrier answers with CR, so every answer can be matched to the line it belongs to. take_refused() hands back the refused frames to be sent again. No more lines go unanswered at once than the carrier can queue; a frame beyond that is refused here. + +SLCAN has no sessions, so the carrier can still have answers to send from before: the last +program may have closed the port with answers still in the carrier's USB buffer, or a quiet +carrier may answer lines written before it was opened again. Each start therefore asks for the +version first and drops everything until that answer, so no old answer is pinned on a new line. +Shutdown waits briefly for the close acknowledgement before releasing USB: write() alone +does not guarantee the carrier has received the final line. """ from collections import deque +import logging import time import serial -from waybionic_teleop import mks_can +from waybionic_teleop import carrier, mks_can BITRATE_CODES = {125000: b'4', 250000: b'5', 500000: b'6', 1000000: b'8'} DEFAULT_BAUDRATE = 1000000 @@ -27,6 +35,7 @@ # A carrier that stops reading its port fails the write, so the link is reopened rather than # the control loop blocking. WRITE_TIMEOUT_S = 0.1 +CLOSE_TIMEOUT_S = 0.25 # The carrier sends its status ten times a second while open, so this much quiet means it is # closed: it reset, or it was still booting when the port opened. SILENCE_S = 1.0 @@ -58,6 +67,9 @@ def parse_line(line): class SlcanBus: """Send and receive standard 11-bit frames through the carrier, without blocking.""" + # The carrier's status arrives from this ID, so no drive can use it through the carrier. + reserved_ids = frozenset({carrier.STATUS_ID}) + 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') @@ -142,22 +154,41 @@ def step(self, dt): self._start() def shutdown(self): - if self.serial is not None: + if self.serial is None: + return + errors, refused = self.errors, self.refused + try: self.outgoing += b'C\r' self.queued.append(b'C') self._flush() - if self.serial is not None: - self.serial.close() - self.serial = None + deadline = time.monotonic() + CLOSE_TIMEOUT_S + while self.serial is not None and self.pending and time.monotonic() < deadline: + self._read() + if self.pending: + time.sleep(0.001) + if self.serial is not None and self.pending: + self.errors += 1 + self.problem = f'carrier did not acknowledge close within {CLOSE_TIMEOUT_S:g} s' + if self.errors > errors or self.refused > refused: + if not self.problem: + self.problem = 'carrier refused a command or sent malformed data while closing' + logging.getLogger(__name__).warning('Carrier close: %s', self.problem) + finally: + if self.serial is not None: + try: + self.serial.close() + finally: + self.serial = None def _start(self): - # Close in case it was left open, set the bit rate, open. Each answers \r, or \a. + # Close in case it was left open, set the bit rate, open. Each answers \r, or \a. The + # version's answer, such as V0100, comes first and marks where this start's answers begin. commands = [b'C', b'S' + BITRATE_CODES[self.bitrate], b'O'] - self.outgoing[:0] = b''.join(command + b'\r' for command in commands) + self.outgoing[:0] = b'V\r' + b''.join(command + b'\r' for command in commands) self.queued[:0] = commands - # A carrier that reset will never answer the lines written before. + # Answers to the lines written before are dropped until the version's answer. self.pending.clear() - self.bell, self.full_since = False, None + self.syncing, self.bell, self.full_since = True, False, None self.heard = time.monotonic() self._flush() @@ -190,7 +221,10 @@ def _read(self): continue line = bytes(self.incoming[start:end]) start = end + 1 - if byte == BELL: + if self.syncing: + # Bytes from before may run into the answer, so look only at the line's end. + self.syncing = not (byte == CR and line[-5:-4] == b'V') + elif byte == BELL: self._refused() elif not line: self._answered() @@ -212,8 +246,11 @@ def _refused(self): self.bell = True return if self.pending and self.pending.popleft() == b'O': - # The carrier keeps the bit rate it first opened at until it resets. - self.problem = f'the carrier would not open at {self.bitrate} bit/s; replug it' + # An R4's own CAN controller keeps the rate it first opened at until it resets. + self.problem = (f'the carrier would not open CAN at {self.bitrate} bit/s: an 8 MHz ' + 'MCP2515 runs 500000 at most, one that opened at another rate ' + 'needs a replug, and an MCP2515 that is missing or fails its link ' + 'self-test (check its SPI wiring and power) is refused too') self.errors += 1 def _answered(self): diff --git a/waybionic_teleop/waybionic_teleop/teleop.py b/waybionic_teleop/waybionic_teleop/teleop.py index bd003642..7a997bc7 100644 --- a/waybionic_teleop/waybionic_teleop/teleop.py +++ b/waybionic_teleop/waybionic_teleop/teleop.py @@ -134,8 +134,13 @@ def check_config(config): class ArmTeleop: """Hold joint targets and move them with the active group's sticks while enabled.""" - def __init__(self, config, limits, kinematics=None, collision=None): - """Take the config, {joint: (lower, upper)} radians, ArmKinematics and ArmCollision.""" + def __init__(self, config, limits, kinematics=None, collision=None, locked=None): + """ + Take the config, {joint: (lower, upper)} radians, ArmKinematics and ArmCollision. + + locked gives {joint: angle} for joints that cannot move on this arm, which then stay + at that angle as if it were both of their limits. + """ check_config(config) self.config = config self.kinematics = kinematics @@ -153,6 +158,10 @@ def __init__(self, config, limits, kinematics=None, collision=None): f'{group.mode.capitalize()} group {group.name} does not match the URDF chain') self.limits = dict(limits) self.limits[config.tool_joint] = config.tool_limits + self.locked = {joint: angle for joint, angle in (locked or {}).items() + if joint in self.limits} + for joint, angle in self.locked.items(): + self.limits[joint] = (angle, angle) self.enabled = False self.group = 0 self.level = config.speed_level @@ -261,6 +270,7 @@ def enable(self, measured, axes): self.targets = {joint: measured[joint] for joint in self.limits} self.command_targets = dict(self.targets) self.velocities = dict.fromkeys(self.limits, 0.0) + self.pin_locked() self.stop_cartesian() self.wait_for_center = False self.enabled, self.note, self.warning = True, '', False @@ -275,6 +285,13 @@ def disable(self, measured, note, warning=False): self.targets.update({joint: measured[joint] for joint in self.limits if joint in measured and math.isfinite(measured[joint])}) self.command_targets = dict(self.targets) + self.pin_locked() + + 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(): + self.targets[joint] = self.command_targets[joint] = angle + self.velocities[joint] = 0.0 def stop_cartesian(self): self.linear, self.tilt, self.roll, self.insert = (0.0, 0.0, 0.0), 0.0, 0.0, 0.0 @@ -325,6 +342,7 @@ def move(self, axes, homing, dt): self.command_targets[joint] = clamp( target + velocity * config.period, min(lower, target), max(upper, target)) self.avoid_collisions(before) + self.pin_locked() def avoid_collisions(self, before): """Undo this step's arm motion if it would take a link into the table or the base.""" diff --git a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py index 1d71cf3c..9a5cc3d4 100644 --- a/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py +++ b/waybionic_teleop/waybionic_teleop/xbox_teleop_node.py @@ -2,8 +2,9 @@ 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; -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. +a joint the arm profile (``arm_profile``) locks stays at its angle. 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. """ import math @@ -11,7 +12,6 @@ from diagnostic_msgs.msg import DiagnosticArray, DiagnosticStatus, KeyValue import rclpy -from rclpy._rclpy_pybind11 import RCLError from rclpy.executors import ExternalShutdownException from rclpy.node import Node from rclpy.qos import DurabilityPolicy, QoSProfile @@ -19,9 +19,11 @@ from std_msgs.msg import Bool, String from visualization_msgs.msg import Marker, MarkerArray +from waybionic_teleop.arm_profile import load_profile from waybionic_teleop.collision import ArmCollision from waybionic_teleop.gamepad import AXES, BUTTON, BUTTONS from waybionic_teleop.kinematics import ArmKinematics, joint_limits +from waybionic_teleop.ros_shutdown import is_shutdown_error from waybionic_teleop.teleop import ArmTeleop, config_from_parameters JAW_SIZE = (0.006, 0.014, 0.03) @@ -67,6 +69,7 @@ def __init__(self, **kwargs): self.base_frame = params['base_frame'] 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 self.teleop = None self.problem = 'Waiting for robot_description' self.joy = None @@ -126,7 +129,7 @@ def load(self, message): kinematics = None self.get_logger().warning(f'Cartesian group unavailable: {error}') try: - self.teleop = ArmTeleop(self.config, limits, kinematics, collision) + self.teleop = ArmTeleop(self.config, limits, kinematics, collision, self.locked) except ValueError as error: self.teleop, self.problem = None, str(error) self.get_logger().error(f'Teleop disabled: {error}') @@ -341,14 +344,8 @@ def main(): rclpy.spin(node) except (KeyboardInterrupt, ExternalShutdownException): pass - except RCLError as error: - # SIGINT can shut down the context before spin recreates its wait set. - if rclpy.ok() or 'the given context is not valid' not in str(error): - raise except RuntimeError as error: - # Jazzy may surface this binding error when SIGINT invalidates a subscription. - if (rclpy.ok() or not str(error).startswith( - "Unable to convert call argument '0' to Python object")): + if not is_shutdown_error(error): raise finally: node.destroy_node()