Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions docs/operator_guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -451,14 +451,20 @@ setup panel in RViz then walks through what is left: put the arm in its zero pos
Windows, so do this every time. Closing RViz, or Ctrl+C in the script's window, stops the
ground station first, so each drive gets its stop, then the bridges.

The bridge finds the carrier itself: the only Arduino, or failing that the only USB serial
port, since a clone board's USB-serial chip does not show Arduino's vendor ID. If it can't,
the script waits up to a minute, then prints what the bridge said (for example, which COM ports
Windows lists) instead of just failing. With several Arduinos or USB serial devices plugged in,
name the carrier's port: `scripts\windows-arm.cmd COM5`.

**Step by step,** from the repository root. The bridge serves one connection at a time, so
let each command finish before the next. If `docker` is not recognized, see
[its troubleshooting](../BuildInstructions.md#docker-is-not-recognized-on-windows).

1. Start the bridge in its own PowerShell window and leave it running. It looks for the
Arduino's COM port each time it opens the carrier, so plugging the carrier in after it
starts, or replugging it under another COM number, is fine; with several Arduinos plugged
in, pass `--port COM5`. Wait for `Carrier open; waiting for the ground station`: the
starts, or replugging it under another COM number, is fine; with several Arduinos or USB
serial devices plugged in, pass `--port COM5`. Wait for `Carrier open; waiting for the ground station`: the
drive node stops at start-up if nothing is listening.

```powershell
Expand Down
2 changes: 1 addition & 1 deletion scripts/windows-arm.cmd
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
@echo off
rem Drives the real arm from Windows. Plug in the carrier, then double-click this file or run it from a terminal.
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0windows-arm.ps1"
powershell -NoProfile -ExecutionPolicy Bypass -File "%~dp0windows-arm.ps1" %*
23 changes: 20 additions & 3 deletions scripts/windows-arm.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@
# controller bridge and the ground station. Docker Desktop cannot open COM ports, so the
# carrier bridge relays the carrier's port to 127.0.0.1:47320 and the drive node connects to it.
# Run windows-arm.cmd, or: powershell -ExecutionPolicy Bypass -File scripts\windows-arm.ps1
# The bridge finds the carrier's COM port itself. With several Arduinos or USB serial devices
# plugged in, name it: windows-arm.cmd COM5 (or set WAYBIONIC_CARRIER=COM5).
param([string]$Port = $env:WAYBIONIC_CARRIER)

$root = Split-Path -Parent $PSScriptRoot
$teleop = Join-Path $root 'waybionic_teleop'
Expand Down Expand Up @@ -64,11 +67,19 @@ if ($LASTEXITCODE -ne 0) {
exit 1
}

# The bridge also writes what it says here, so that this script can show it if the bridge fails.
$bridgeLog = Join-Path $env:TEMP 'waybionic-carrier-bridge.log'
Remove-Item $bridgeLog -ErrorAction SilentlyContinue
$bridgeArguments = @('-m', 'waybionic_teleop.carrier_relay', '--log-file', $bridgeLog)
if ($Port) {
$bridgeArguments += @('--port', $Port)
}

$carrier = $null
$controller = $null
try {
$carrier = Start-Process -FilePath $python.Source -PassThru -WorkingDirectory $teleop `
-ArgumentList ($pythonArguments + @('-m', 'waybionic_teleop.carrier_relay'))
-ArgumentList ($pythonArguments + $bridgeArguments)

Write-Host ('Waiting for the carrier (up to a minute): plug it in if you have not; the ' +
'bridge window says what it sees...')
Expand All @@ -79,8 +90,14 @@ try {
-ErrorAction SilentlyContinue
} until ($listening -or $carrier.HasExited -or (Get-Date) -gt $deadline)
if (-not $listening) {
Write-Error ('The carrier bridge is not ready. Plug in only the carrier, or run ' +
'python -m waybionic_teleop.carrier_relay from waybionic_teleop to see why.')
Write-Host 'The carrier bridge said:' -ForegroundColor Yellow
if (Test-Path $bridgeLog) {
Get-Content $bridgeLog -Tail 6 | ForEach-Object { Write-Host " $_" }
} else {
Write-Host ' (nothing)'
}
Write-Error ('The carrier bridge is not ready. Plug in only the carrier, or name its ' +
'port: scripts\windows-arm.cmd COM5')
exit 1
}

Expand Down
83 changes: 63 additions & 20 deletions waybionic_teleop/test/test_carrier_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,67 +114,106 @@ def test_port_in_use_exits_with_a_message():
taken.close()


ARDUINO, CLONE = carrier_relay.ARDUINO_VID, 0x1A86


class ComPorts:
"""The COM ports Windows lists, which a test changes as the carrier is plugged in."""
"""The COM ports Windows lists, as (name, USB vendor ID) pairs a test plugs in and out."""

def __init__(self, *devices):
self.devices, self.opened = list(devices), []

def arduino(self, device):
return SimpleNamespace(device=device, vid=carrier_relay.ARDUINO_VID)

def listed(self):
return [self.arduino(device) if device.startswith('COM') else
SimpleNamespace(device=device, vid=0x1A86) for device in self.devices]
return [SimpleNamespace(device=name, vid=vid, pid=0x0069 if vid == ARDUINO else 0x7523,
description=f'device on {name}') for name, vid in self.devices]

def open_serial(self, name, baudrate, timeout):
self.opened.append((name, baudrate))
return name


def opener(ports, port=None):
def opener(ports, port=None, messages=None):
return carrier_relay.carrier_opener(
port, 1000000, open_serial=ports.open_serial, list_com_ports=ports.listed,
log=lambda message: None)
log=(messages if messages is not None else []).append)


def test_a_carrier_plugged_in_after_the_relay_started_is_found():
ports = ComPorts()
open_carrier = opener(ports)
with pytest.raises(serial.SerialException, match='no Arduino COM port found.*plug in'):
open_carrier()
ports.devices.append('COM5')
ports.devices.append(('COM5', ARDUINO))
assert open_carrier() == 'COM5'
assert ports.opened == [('COM5', 1000000)]


def test_a_replugged_carrier_is_found_under_its_new_com_number():
ports = ComPorts('COM5')
ports = ComPorts(('COM5', ARDUINO))
open_carrier = opener(ports)
assert open_carrier() == 'COM5'
ports.devices[:] = ['COM7']
ports.devices[:] = [('COM7', ARDUINO)]
assert open_carrier() == 'COM7'


def test_other_serial_devices_are_not_mistaken_for_the_carrier():
ports = ComPorts('/dev/ttyUSB0')
with pytest.raises(serial.SerialException, match='no Arduino COM port found'):
opener(ports)()
assert ports.opened == []
def test_an_arduino_is_preferred_to_other_usb_serial_devices():
ports = ComPorts(('COM3', CLONE), ('COM5', ARDUINO))
assert opener(ports)() == 'COM5'


def test_the_relay_does_not_guess_between_several_arduinos():
ports = ComPorts('COM3', 'COM5')
ports = ComPorts(('COM3', ARDUINO), ('COM5', ARDUINO))
with pytest.raises(serial.SerialException, match=r'COM3, COM5.*--port'):
opener(ports)()
assert ports.opened == []


def test_a_lone_usb_serial_device_of_another_make_is_used_and_said_so():
# A clone board has its own USB-serial chip, so it does not show Arduino's vendor ID.
ports, messages = ComPorts(('COM7', CLONE)), []
assert opener(ports, messages=messages)() == 'COM7'
assert any('COM7' in message and 'only USB serial port' in message and '--port' in message
for message in messages)


def test_several_usb_serial_devices_without_an_arduino_are_not_guessed_between():
ports = ComPorts(('COM3', CLONE), ('COM7', CLONE))
with pytest.raises(serial.SerialException,
match=r'several USB serial ports.*COM3.*COM7.*--port'):
opener(ports)()
assert ports.opened == []


def test_ports_that_are_not_usb_are_never_taken_for_the_carrier():
# COM1 and Bluetooth ports have no USB vendor ID.
ports = ComPorts(('COM1', None), ('COM4', None))
with pytest.raises(serial.SerialException, match=r'no Arduino COM port found.*COM1.*COM4'):
opener(ports)()
assert ports.opened == []


def test_a_port_that_is_given_is_opened_without_looking_for_it():
ports = ComPorts()
assert opener(ports, port='COM9')() == 'COM9'


def test_what_the_relay_says_is_also_written_to_a_file(tmp_path, capsys):
path = tmp_path / 'bridge.log'
log = carrier_relay.make_log(str(path))
log('Carrier unavailable, retrying every second: no Arduino COM port found')
log('Carrier on COM5')
assert path.read_text(encoding='utf-8').splitlines() == [
'Carrier unavailable, retrying every second: no Arduino COM port found',
'Carrier on COM5']
assert 'Carrier on COM5' in capsys.readouterr().out


def test_a_log_file_that_cannot_be_written_does_not_stop_the_relay(tmp_path, capsys):
log = carrier_relay.make_log(str(tmp_path / 'missing' / 'bridge.log'))
log('Carrier on COM5')
assert 'Carrier on COM5' in capsys.readouterr().out


def test_the_relay_starts_listening_once_the_carrier_is_plugged_in():
probe = socket.create_server(('127.0.0.1', 0))
tcp_port = probe.getsockname()[1]
Expand All @@ -193,7 +232,7 @@ def test_the_relay_starts_listening_once_the_carrier_is_plugged_in():
with pytest.raises(OSError):
socket.create_connection(('127.0.0.1', tcp_port), timeout=0.5)
assert any('plug in the carrier' in message for message in messages)
ports.devices.append('COM5')
ports.devices.append(('COM5', ARDUINO))
deadline = time.monotonic() + 4.0
while True:
try:
Expand All @@ -203,8 +242,12 @@ def test_the_relay_starts_listening_once_the_carrier_is_plugged_in():
assert time.monotonic() < deadline, 'the relay never listened'
time.sleep(0.05)
client.settimeout(2.0)
client.sendall(b't00121234\r')
assert client.recv(64) == b't00121234\r'
frame = b't00121234\r'
client.sendall(frame)
echoed = b''
while len(echoed) < len(frame):
echoed += client.recv(64)
assert echoed == frame
client.close()
assert 'Carrier on COM5' in messages
finally:
Expand Down
75 changes: 62 additions & 13 deletions waybionic_teleop/waybionic_teleop/carrier_relay.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,15 @@
python -m waybionic_teleop.carrier_relay

It looks for the Arduino's COM port each time it opens the carrier, so a carrier plugged in
after it starts, or replugged under another COM number, is found. With several Arduinos plugged
in, name the carrier's: --port COM5.
after it starts, or replugged under another COM number, is found. A board whose USB-serial chip
is not Arduino's is used if it is the only USB serial port. With several candidates, name the
carrier's: --port COM5.
"""

import argparse
import socket
import threading
import traceback

import serial
from serial.tools import list_ports
Expand All @@ -31,29 +33,65 @@
CHUNK = 4096


def describe(info):
"""Return a COM port's name with what Windows calls it, as the operator sees it listed."""
description = getattr(info, 'description', '')
if description and description != 'n/a':
return f'{info.device} ({description})'
return info.device


def make_log(path):
"""Return log(), which prints each message and, given a path, appends it to that file too."""
def log(message):
print(message, flush=True)
if path:
try:
with open(path, 'a', encoding='utf-8') as stream:
stream.write(f'{message}\n')
except OSError:
pass
return log


def carrier_opener(port, baudrate, open_serial=serial.Serial, list_com_ports=list_ports.comports,
log=print):
"""
Return the open_port that serve() calls whenever it needs the carrier.

With no port it looks for the only Arduino COM port every time, because the carrier may be
plugged in after the relay starts, still be enumerating, or come back under another COM
number. It never guesses between several Arduinos.
With no port it looks for the carrier every time, because the carrier may be plugged in
after the relay starts, still be enumerating, or come back under another COM number. It
takes the only Arduino, or failing that the only USB serial port, as a clone board's
USB-serial chip is not Arduino's. It never guesses between several.
"""
def open_carrier():
name = port
if name is None:
infos = list_com_ports()
arduinos = sorted(info.device for info in infos if info.vid == ARDUINO_VID)
if not arduinos:
listed = ', '.join(sorted(info.device for info in infos)) or 'none'
raise serial.SerialException(
f'no Arduino COM port found (COM ports: {listed}); plug in the carrier')
usb = sorted((info for info in infos if info.vid is not None),
key=lambda info: info.device)
if len(arduinos) > 1:
raise serial.SerialException(
f'several Arduino COM ports ({", ".join(arduinos)}); plug in only the '
'carrier, or pass --port')
name = arduinos[0]
if arduinos:
name = arduinos[0]
elif len(usb) == 1:
name = usb[0].device
log(f'{describe(usb[0])} does not show the Arduino USB vendor ID, but it is the '
'only USB serial port, so it is used as the carrier. Pass --port if that '
'is wrong.')
elif usb:
raise serial.SerialException(
'no Arduino COM port found, and several USB serial ports '
f'({", ".join(describe(info) for info in usb)}); plug in only the carrier, '
'or pass --port')
else:
listed = ', '.join(describe(info) for info in sorted(
infos, key=lambda info: info.device)) or 'none'
raise serial.SerialException(
f'no Arduino COM port found (COM ports: {listed}); plug in the carrier')
link = open_serial(name, baudrate, timeout=POLL_S)
log(f'Carrier on {name}')
return link
Expand Down Expand Up @@ -205,14 +243,25 @@ def main():
parser.add_argument('--bind', default='127.0.0.1',
help='listen address; keep it local, this drives the arm')
parser.add_argument('--tcp-port', type=int, default=DEFAULT_TCP_PORT)
parser.add_argument('--log-file',
help='also write what it says to this file, which the launcher shows '
'if the bridge does not start')
args = parser.parse_args()
print(f'Relaying the carrier to {args.bind}:{args.tcp_port} (Ctrl+C to stop)')
print(f'Ground station: drive_channel:=socket://host.docker.internal:{args.tcp_port}')
log = make_log(args.log_file)
log(f'Relaying the carrier to {args.bind}:{args.tcp_port} (Ctrl+C to stop)')
log(f'Ground station: drive_channel:=socket://host.docker.internal:{args.tcp_port}')
stop = threading.Event()
try:
serve(carrier_opener(args.port, args.baudrate), args.bind, args.tcp_port, stop)
serve(carrier_opener(args.port, args.baudrate, log=log), args.bind, args.tcp_port, stop,
log)
except KeyboardInterrupt:
pass
except SystemExit as error:
log(str(error.code))
raise
except Exception:
log(traceback.format_exc())
raise
finally:
stop.set()

Expand Down