mpremote option to wait until device connected and/or reconnect
Description
For devices that provide a REPL over USB/VCP, it can be tricky to get the initial set of data send over the terminal using mpremote (or other serial terminal), as the serial device doesn't exist until the device is plugged in (as compared to a terminal over UART, which can be constant connected to the host computer and monitored across reboots).
If mpremote can have an option to monitor the USB system, waiting for a device connection/appearing, then immediately connect the serial terminal, it could make debugging/developing early-boot situations. Could also set up a re-connect option to persist an mpremote session across hard reboots.
The following code works for this purpose, and could be adapted relatively easily (for linux hosts at least) to include more specific USB identifiers.
# borrowed from **https://unix.stackexchange.com/questions/65891/how-to-execute-a-shellscript-when-i-plug-in-a-usb-device
import pyudev
import subprocess
import sys
from functools import partial
def main():
context = pyudev.Context()
monitor = pyudev.Monitor.from_netlink(context)
monitor.filter_by(subsystem='usb')
monitor.start()
while True:
# avoid too many invocations of the external command by waiting until
# no other events occur and we timeout
device = monitor.poll(timeout=None)
for device in iter(partial(monitor.poll, 1), None):
pass
subprocess.call(['mpremote'])
Code Size
No response
Implementation
I intend to implement this feature and would submit a Pull Request if desirable
Code of Conduct
Yes, I agree
tools/mpremote: Add automatic reconnection feature
Summary
This PR adds automatic reconnection capability to mpremote and makes it the default behavior. When a MicroPython device disconnects, mpremote automatically reconnects to the same device, eliminating the need to manually restart the tool during development.
Reconnection is now enabled by default. Users can opt-out via:
- The
oncecommand for per-invocation control MPREMOTE_RECONNECTenvironment variable (supports 0/1/true/false/yes/no/on, case-insensitive)- Config file setting (
reconnect = Falsein~/.config/mpremote/config.py) - Priority:
oncecommand > env var > config file > default (enabled)
Key features:
- Always reconnects to the exact same port that was previously connected when originally started in
connect automode - Always reconnects to the exact same device (on any port) when started in
connect id:abc123mode - Preserves resume state through reconnections
- Handles Windows COM port timing issues with retry logic
Usage:
# Reconnect is now the default
mpremote repl
# Disable reconnect for this invocation
mpremote once repl
# Disable via environment variable
MPREMOTE_RECONNECT=0 mpremote repl
# Disable via config file
echo "reconnect = False" >> ~/.config/mpremote/config.py
This builds on the existing disconnect handling improvements that were previously merged.
Testing
Manual testing was performed on Linux with Pyboard D and Windows 11 with ESP32S2 devices. Tests used scripted USB power cycling (via uhubctl) to simulate disconnects and verify reconnection behavior. Testing covered default auto-reconnect, the once command opt-out, environment variable control (including priority override behavior where once takes precedence over MPREMOTE_RECONNECT=1), auto mode port-specific reconnection, ID mode device tracking across port changes, multiple device scenarios, resume state preservation, and environment variable parsing with various formats.
Trade-offs and Alternatives
Making reconnect the default is a breaking change for scripts that expect mpremote to exit on disconnect. These scripts will need to use the once command or set MPREMOTE_RECONNECT=0. However, the new default is more intuitive for the primary use case (interactive development).
Design decisions:
- Default changed based on maintainer feedback
- Always reconnects to the exact same port (even in auto mode) rather than any available device, prioritizing safety in multi-device environments
- Added retry logic with delays specifically for Windows COM port timing issues
- Multiple opt-out mechanisms with clear priority order provide flexibility for different use cases
oncecommand takes highest priority as it's the most explicit user intention
The code size increase from the reconnect logic is justified by the significant improvement in developer workflow.