refactor(esc_4way): start on USB through SYS_USB_AUTO=1 only

PASSTHRU_EN belongs to the MAVLink serial passthrough. Its value 2
reused that boot without output drivers for the ESC configuration
server, which stops the outputs itself, and was a second way to hand
the USB port to it. USB protocol detection already does that.

Assisted-by: Claude:claude-fable-5-2
This commit is contained in:
Jacob Dahl authored and Peter van der Perk committed 2026-11-16 16:34:58 +01:00
1 parent cfd11919f2
commit 0e8ff0d538
8 files changed
+66 -101

No files matched your search

+5 -9
View File
@@ -550,10 +550,12 @@ else
else
commander start
# PASSTHRU_EN > 0 (serial passthrough or ESC configuration):
# leave the ESC lines free, it is reset below for the next boot
if ! param greater -s PASSTHRU_EN 0
if param greater -s PASSTHRU_EN 0
then
# serial passthrough requested: leave the ESC lines free and
# reset so the next boot starts the outputs normally
param set PASSTHRU_EN 0
else
dshot start
pwm_out start
fi
@@ -619,12 +621,6 @@ else
fi
fi
# After cdcacm_autostart, which reads PASSTHRU_EN=2 at start
if param greater -s PASSTHRU_EN 0
then
param set PASSTHRU_EN 0
fi
#
# Play the startup tune (if not disabled or there is an error)
#
+24 -38
View File
@@ -34,7 +34,7 @@
"""ESC configuration over a flight controller's MSP + 4way interface.
Talks to the PX4 esc_4way server (USB port after PASSTHRU_EN=2), any other
Talks to the PX4 esc_4way server (USB port with SYS_USB_AUTO=1) or any other
MSP + 4way flight controller.
Tools/esc_4way.py [--setup] [--no-exit] [-d DEVICE] [--target N] COMMAND
@@ -49,10 +49,10 @@ MSP + 4way flight controller.
settings AM32 settings block, raw and decoded
direction set 0|1 AM32 motor direction (or: direction toggle)
A port that sends MAVLink heartbeats is switched to the ESC configuration
server first (PASSTHRU_EN=2 and a reboot, needs pymavlink), and the tool waits
for MAVLink to come back after the session; --setup does that switch without
listening for heartbeats first. --no-exit leaves the session open: the port then
A port that sends MAVLink heartbeats is first freed for the ESC configuration
server: the tool sets SYS_USB_AUTO=1, which stays set, and reboots the board
(needs pymavlink); --setup does that without listening for heartbeats first.
--no-exit leaves the session open: the port then
keeps DTR raised after it is closed, also for other programs, until a run without
--no-exit or the board's next reboot. Exit code 0 on success.
@@ -381,7 +381,7 @@ def run(fd, no_esc, variant, target, toggle_direction=False):
step('InterfaceExit')
# MAVLink entry and exit (PX4 only)
# MAVLink entry (PX4 only)
def _wait_port(path, timeout=30):
"""Wait for a serial device to drop and come back (a reboot); returns its current path.
@@ -449,43 +449,35 @@ def _after_reboot(path, timeout, baud):
raise CheckFailed(f'{path}: {e}')
def mavlink_esc_mode(path, enter=True, baud=115200):
"""Move a PX4 board on a MAVLink serial port into or out of the ESC configuration server.
def mavlink_esc_mode(path, baud=115200):
"""Free the MAVLink USB port of a PX4 board for the ESC configuration server.
enter=True: PASSTHRU_EN=2, wait for its echo and the parameter autosave, reboot, wait for
the port to return and confirm it is quiet (no heartbeat for 3 s). Returns the port path.
enter=False: after InterfaceExit of a served session the board reboots; wait for the port and
its heartbeat (normal MAVLink mode). Returns the port path.
SYS_USB_AUTO=1 (the port then starts whatever talks to it first, and stays that way), wait for
its echo and the parameter autosave, reboot, wait for the port to return and confirm it is
quiet (no heartbeat for 3 s). Returns the port path.
"""
mavutil = _mavutil()
if not enter:
path, hb = _after_reboot(path, 30, baud)
check(hb, f'{path}: no heartbeat after the session')
print(f'MAVLink heartbeat on {path} (sysid {hb.get_srcSystem()}): normal mode restored')
return path
mav = mavutil.mavlink_connection(path, baud=baud)
hb = _heartbeat(mav, 3)
if hb is None:
mav.close()
print(f'{path}: no heartbeat, assuming the ESC configuration server is already running')
print(f'{path}: no heartbeat, assuming the port already waits for its first program')
return path
mav.target_system, mav.target_component = hb.get_srcSystem(), hb.get_srcComponent()
print('Setting PASSTHRU_EN=2')
mav.mav.param_set_send(mav.target_system, mav.target_component, b'PASSTHRU_EN',
struct.unpack('<f', struct.pack('<i', 2))[0], mavutil.mavlink.MAV_PARAM_TYPE_INT32)
print('Setting SYS_USB_AUTO=1 (stays set)')
mav.mav.param_set_send(mav.target_system, mav.target_component, b'SYS_USB_AUTO',
struct.unpack('<f', struct.pack('<i', 1))[0], mavutil.mavlink.MAV_PARAM_TYPE_INT32)
deadline = time.monotonic() + 3
while time.monotonic() < deadline:
msg = mav.recv_match(type='PARAM_VALUE', blocking=True, timeout=deadline - time.monotonic())
if msg and msg.param_id == 'PASSTHRU_EN':
check(struct.unpack('<i', struct.pack('<f', msg.param_value))[0] == 2,
f'PASSTHRU_EN echo {msg.param_value}')
if msg and msg.param_id == 'SYS_USB_AUTO':
check(struct.unpack('<i', struct.pack('<f', msg.param_value))[0] == 1,
f'SYS_USB_AUTO echo {msg.param_value}')
break
else:
mav.close()
raise CheckFailed('no PARAM_VALUE echo for PASSTHRU_EN')
raise CheckFailed('no PARAM_VALUE echo for SYS_USB_AUTO')
time.sleep(3) # parameter autosave
print('Rebooting')
for _ in range(5): # commander may reject it briefly, e.g. right after boot
@@ -502,8 +494,8 @@ def mavlink_esc_mode(path, enter=True, baud=115200):
raise CheckFailed('reboot not accepted')
mav.close()
path, hb = _after_reboot(path, 3, baud)
check(hb is None, f'{path}: still sending MAVLink heartbeats, server not started')
print(f'{path}: quiet for 3 s, ESC configuration server assumed')
check(hb is None, f'{path}: still sending MAVLink heartbeats')
print(f'{path}: quiet for 3 s, waiting for its first program')
return path
@@ -693,7 +685,7 @@ def main(argv=None):
p.add_argument('-d', '--device', default=default or '/dev/ttyACM0', help='serial device (default /dev/ttyACM0)')
p.add_argument('--target', type=int, default=default or 0, help='ESC channel (default 0)')
p.add_argument('--setup', action='store_true', default=default or False,
help='switch to the ESC configuration server over MAVLink without listening for heartbeats first')
help='set SYS_USB_AUTO=1 and reboot over MAVLink without listening for heartbeats first')
p.add_argument('--no-exit', action='store_true', default=default or False,
help='leave the session open (no InterfaceExit, no reboot)')
sub = parser.add_subparsers(dest='command', required=True)
@@ -731,7 +723,7 @@ def main(argv=None):
setup = mavlink_heartbeat_seen(seen)
if setup:
os.close(fd)
print(f'{device}: MAVLink heartbeats, switching to the ESC configuration server')
print(f'{device}: MAVLink heartbeats, freeing the port for the ESC configuration server')
if setup:
device = mavlink_esc_mode(device)
fd = open_serial(device, keep_dtr=args.no_exit)[0]
@@ -761,16 +753,10 @@ def main(argv=None):
finally:
os.close(fd)
# a session ends in a reboot after InterfaceExit or, on USB, when the port closes
if exited and not setup:
if exited:
_wait_gone(device) # a next run must not open the port of a board that is rebooting
if status:
return status
if setup and not args.no_exit:
try:
mavlink_esc_mode(device, enter=False)
except CheckFailed as e:
print(f'FAIL: {e}')
return 1
print('PASS' if args.command == 'check' else 'done')
return 0
+14 -25
View File
@@ -31,34 +31,22 @@ The configurator numbers the ESCs by motor: ESC 1 is the output assigned to Moto
## Configure the ESCs
1. Connect the flight controller to QGroundControl and set the parameter [PASSTHRU_EN](../advanced_config/parameter_reference.md#PASSTHRU_EN) to `2` (_USB ESC configuration server_).
1. Reboot the flight controller.
On this boot the motor outputs stay off and the USB port is used by the ESC configuration server instead of MAVLink, so QGroundControl will not connect.
`PASSTHRU_EN` resets itself to `0` during this boot.
1. Power the ESCs (connect the battery).
1. Close QGroundControl (or any other program that holds the USB port), then open [am32.ca](https://am32.ca) or [esc-configurator.com](https://esc-configurator.com) in a browser that supports WebSerial (Chrome or Edge).
1. Set the parameter [SYS_USB_AUTO](../advanced_config/parameter_reference.md#SYS_USB_AUTO) to `1` (_Auto-detect_) and reboot the flight controller.
1. Plug in the USB cable and power the ESCs (connect the battery).
1. Before any other program opens the USB port, open [am32.ca](https://am32.ca) or [esc-configurator.com](https://esc-configurator.com) in a browser that supports WebSerial (Chrome or Edge).
1. Click **Connect** and select the flight controller's USB port.
The flight controller recognises the configurator and starts the ESC configuration server; the motor outputs are switched off at that moment.
1. Read, change and write the ESC settings, or flash new ESC firmware.
1. Click **Disconnect** when you are done.
The flight controller reboots, so the USB connection drops.
After that reboot the motor outputs work normally again and QGroundControl can connect.
After that reboot the motor outputs work normally again.
The USB port is given to the first program that talks to it after it is plugged in.
If _QGroundControl_ connected first, unplug and replug the USB cable or reboot the flight controller.
If you unplug the USB cable or close the configurator without disconnecting, the flight controller also reboots.
Server mode lasts for a single boot: any reboot or power cycle, also in the middle of a session, returns the flight controller to normal operation.
## Alternative: Plug In and Connect
If [SYS_USB_AUTO](../advanced_config/parameter_reference.md#SYS_USB_AUTO) is set to `1` (auto-detect), you do not need to set `PASSTHRU_EN`:
1. Plug in the USB cable and power the ESCs.
1. Before any other program opens the USB port, open the configurator and click **Connect**.
The flight controller recognises the configurator and starts the ESC configuration server; the motor outputs are switched off at that moment.
1. Click **Disconnect** when you are done; the flight controller reboots as above.
This only works while nothing else has claimed the USB port since it was plugged in.
If QGroundControl connected first, unplug and replug the USB cable.
Any program that first sends a valid MSP request to the USB port starts the ESC configuration server in this mode, and the motor outputs then stay off until the flight controller reboots.
Any program that first sends a valid MSP request to the USB port starts the ESC configuration server, and the motor outputs then stay off until the flight controller reboots.
## Command Line Tools
@@ -77,8 +65,9 @@ Tools/esc_4way.py write 0xF800 settings.bin
Tools/esc_4way.py check /dev/ttyACM0 # protocol self-check
```
When the port sends MAVLink heartbeats, the tool first sets `PASSTHRU_EN` to `2` over MAVLink and reboots the flight controller into the ESC configuration server, and waits for MAVLink to return after the session ends.
`--setup` does that switch without listening for heartbeats first.
When the port sends MAVLink heartbeats, the tool first sets `SYS_USB_AUTO` to `1` over MAVLink and reboots the flight controller, which frees the port for the ESC configuration server.
The parameter stays set.
`--setup` does that without listening for heartbeats first.
Use `-d` to select the serial device (default `/dev/ttyACM0`), `--target` for the ESC (default 0) and `--no-exit` to keep the session open.
The tool needs `pymavlink` for the switch over MAVLink.
@@ -94,7 +83,7 @@ esc_4way start -d /dev/ttyS3
Use the device node of the port, for example `/dev/ttyS3` for a UART or `/dev/ttyACM0` for USB.
The port must not be used by another module (for example MAVLink), so free it first.
Then connect the host tool or configurator to the other end of that serial link, for example with `Tools/esc_4way.py -d <host serial device> info`.
The server is started manually in this case, so `PASSTHRU_EN` and USB auto-detection are not involved.
The server is started manually in this case, so USB auto-detection is not involved.
Stop it with `esc_4way stop`, or reboot the flight controller.
## USB Vendor ID
@@ -114,7 +103,7 @@ CONFIG_SERIALPASSTHROUGH_BITBANG=y
CONFIG_DRIVERS_ESC_4WAY=y
```
`PASSTHRU_EN=2` and USB auto-detection need the board's USB port to be managed by `cdcacm_autostart` (`CONFIG_DRIVERS_CDCACM_AUTOSTART=y`); without it, start the server manually with `esc_4way start -d <device>`.
USB auto-detection needs the board's USB port to be managed by `cdcacm_autostart` (`CONFIG_DRIVERS_CDCACM_AUTOSTART=y`); without it, start the server manually with `esc_4way start -d <device>`.
On STM32 boards the UART bit timing comes from a spare hardware timer, `CONFIG_UART_BITBANG_TIMER` (default `13`).
That timer must be enabled in the board's NuttX configuration (`CONFIG_STM32H7_TIM13=y` or `CONFIG_STM32F7_TIM13=y` in `nuttx-config/nsh/defconfig`), and nothing else on the board may use it: not the HRT, the tone alarm, an LED, or a PWM/DShot output timer.
@@ -92,13 +92,6 @@ int CdcAcmAutostart::Start()
PX4_INFO("Starting CDC/ACM autostart");
UpdateParams(true);
#if defined(CONFIG_DRIVERS_ESC_4WAY)
// Read before rcS resets PASSTHRU_EN for the next boot
int32_t passthru_en = 0;
param_get(param_find("PASSTHRU_EN"), &passthru_en);
_esc_4way = (passthru_en == 2);
#endif
ScheduleNow();
return PX4_OK;
@@ -228,8 +221,7 @@ void CdcAcmAutostart::state_connecting()
// /dev/ttyACM0 immediately, but open() returns -ENOTCONN until the host has
// enumerated. mavlink exits if its own open retries run out, so only spawn it
// once the port is known to be openable, then release the probe.
// PASSTHRU_EN=2 starts the ESC configuration server the same way, instead of MAVLink.
if (_sys_usb_auto.get() == 2 || _esc_4way) {
if (_sys_usb_auto.get() == 2) {
if (_ttyacm_fd < 0) {
_ttyacm_fd = px4_open(USB_DEVICE_PATH, O_RDONLY | O_NONBLOCK);
}
@@ -240,11 +232,11 @@ void CdcAcmAutostart::state_connecting()
}
close_ttyacm();
PX4_INFO("Starting %s on %s", _esc_4way ? "esc_4way" : "mavlink", USB_DEVICE_PATH);
PX4_INFO("Starting mavlink on %s (SYS_USB_AUTO=2)", USB_DEVICE_PATH);
if (_esc_4way ? start_esc_4way() : start_mavlink()) {
if (start_mavlink()) {
_state = UsbAutoStartState::connected;
_active_protocol = _esc_4way ? UsbProtocol::esc_4way : UsbProtocol::mavlink;
_active_protocol = UsbProtocol::mavlink;
} else {
_state = UsbAutoStartState::disconnecting;
@@ -603,6 +595,7 @@ bool CdcAcmAutostart::start_nsh()
return execute_process(argv) > 0;
}
#if defined(CONFIG_DRIVERS_ESC_4WAY)
// The server stops the output drivers itself at the first valid request
bool CdcAcmAutostart::start_esc_4way()
{
@@ -618,12 +611,9 @@ bool CdcAcmAutostart::start_esc_4way()
char *argv[] { (char *)"esc_4way", (char *)"start", (char *)"-d", (char *)USB_DEVICE_PATH, (char *)"-r", request, nullptr };
if (request[0] == '\0') {
argv[4] = nullptr;
}
return execute_process(argv) > 0;
}
#endif
#if defined(CONFIG_SERIAL_PASSTHRU_UBLOX)
bool CdcAcmAutostart::start_ublox_serial_passthru(speed_t baudrate)
@@ -107,7 +107,9 @@ private:
bool start_mavlink();
void stop_mavlink();
bool start_nsh();
#if defined(CONFIG_DRIVERS_ESC_4WAY)
bool start_esc_4way();
#endif
#if defined(CONFIG_SERIAL_PASSTHRU_UBLOX)
bool start_ublox_serial_passthru(speed_t baudrate);
#endif
@@ -120,12 +122,13 @@ private:
UsbProtocol _active_protocol{UsbProtocol::none};
bool _vbus_present{false};
bool _vbus_present_prev{false};
bool _esc_4way{false}; ///< PASSTHRU_EN=2 at boot: ESC configuration server instead of MAVLink
int _ttyacm_fd{-1};
char _buffer[80] {};
int _bytes_read{0};
int _msp_offset{-1}; ///< start of the MSP request found in _buffer, handed to esc_4way
#if defined(CONFIG_DRIVERS_ESC_4WAY)
int _msp_offset {-1}; ///< start of the MSP request found in _buffer, handed to esc_4way
#endif
uint32_t _reschedule_time{0};
+4 -3
View File
@@ -6,6 +6,7 @@ menuconfig DRIVERS_ESC_4WAY
Serves the BLHeli/AM32 4way interface protocol to ESC configurators
(am32.ca, esc-configurator.com) through the flight controller: MSP on
the host side, the ESC bootloader protocol on the ESC signal pins via
the bit-bang UART backend. Started by cdcacm_autostart when
PASSTHRU_EN=2 or by "esc_4way start -d <device>". The outputs are
stopped for the session and the board reboots afterwards.
the bit-bang UART backend. Started by cdcacm_autostart on an MSP
request when SYS_USB_AUTO=1, or by "esc_4way start -d <device>".
The outputs are stopped for the session and the board reboots
afterwards.
+2 -1
View File
@@ -877,7 +877,8 @@ on the outputs assigned to motors. At the first valid request it stops the dshot
session ends with a reboot when the configurator disconnects, the USB host closes the port or
the serial device goes away. Requests are ignored while armed.
Started by cdcacm_autostart on the USB port when `PASSTHRU_EN` is 2, or manually on any serial port.
Started by cdcacm_autostart on the USB port when `SYS_USB_AUTO` is 1 and an ESC configurator
connects first, or manually on any serial port.
### Examples
$ esc_4way start -d /dev/ttyACM0
+6 -7
View File
@@ -5,12 +5,11 @@ parameters:
definitions:
PASSTHRU_EN:
description:
short: Serial passthrough mode
long: When not 0, dshot and pwm_out are not started at boot and the parameter resets to 0, so the next boot starts them again.
type: enum
values:
0: Disabled
1: MAVLink serial passthrough (SERIAL_CONTROL to the ESC pins)
2: USB ESC configuration server (esc_4way instead of MAVLink, for am32.ca or esc-configurator.com)
short: Serial passthrough enable
long: |
When enabled, the serial passthrough mode is active and the
normal motor output drivers (dshot, pwm_out) are not started
at boot.
type: boolean
default: 0
reboot_required: true