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
mpremote: Fix disconnect handling on Windows and Linux.
Summary
Improves device disconnection handling in mpremote to show a clean "device disconnected" message instead of stack traces on Windows and fixes terminal formatting issues on Linux.
Problem
When a device disconnects during an mpremote session:
- Windows: Shows a full stack trace with ClearCommError failed or similar errors
- Linux: 'device disconnected' with unclear terminal formatting, causing indentation issues
Solution
This PR fixes disconnect handling to:
- Catch serial disconnection exceptions in both console.py and repl.py
- Properly exit terminal raw mode before showing the message
- Display a clean "device disconnected" message after terminal cleanup
- Ensure consistent behavior across Windows and Linux platforms
File Changes
tools/mpremote/mpremote/console.py:
- Windows: Modified waitchar() to catch SerialException and re-raise with cleaner message
- Added proper exception handling for ClearCommError failed cases
tools/mpremote/mpremote/repl.py:
- Modified do_repl_main_loop() to catch serial exceptions and return disconnect state
- Added checks for both Windows and Linux disconnect error patterns
tools/mpremote/mpremote/main.py:
- Modified main loop to handle disconnect state after console cleanup
- Added newline and message printing after terminal mode is restored
Testing
Before/After Examples - I connected to ESP32S2 (usb serial) and once confirmed the repl is working, physically unplug the devices.
Windows (Before)
PS C:\Users\anl> mpremote
Connected to MicroPython at COM7
Use Ctrl-] or Ctrl-x to exit this shell
MicroPython v1.25.0-1.ge7b0fe4775.dirty on 2025-05-09; Generic ESP32S2 module with ESP32S2
Type "help()" for more information.
>>>
>>> Traceback (most recent call last):
File "C:\Users\anl\AppData\Roaming\uv\python\cpython-3.10.11-windows-x86_64-none\lib\runpy.py", line 196, in _run_module_as_main
return _run_code(code, main_globals, None,
File "C:\Users\anl\AppData\Roaming\uv\python\cpython-3.10.11-windows-x86_64-none\lib\runpy.py", line 86, in _run_code
exec(code, run_globals)
File "c:\users\anl\.local\bin\mpremote.exe\__main__.py", line 8, in <module>
File "C:\Users\anl\AppData\Roaming\uv\tools\mpremote\lib\site-packages\mpremote\main.py", line 584, in main
disconnected = do_repl(state, argparse_repl().parse_args([]))
File "C:\Users\anl\AppData\Roaming\uv\tools\mpremote\lib\site-packages\mpremote\repl.py", line 102, in do_repl
disconnected = do_repl_main_loop(
File "C:\Users\anl\AppData\Roaming\uv\tools\mpremote\lib\site-packages\mpremote\repl.py", line 11, in do_repl_main_loop
console_in.waitchar(state.transport.serial)
File "C:\Users\anl\AppData\Roaming\uv\tools\mpremote\lib\site-packages\mpremote\console.py", line 99, in waitchar
while not (self.inWaiting() or pyb_serial.inWaiting()):
File "C:\Users\anl\AppData\Roaming\uv\tools\mpremote\lib\site-packages\serial\serialutil.py", line 594, in inWaiting
return self.in_waiting
File "C:\Users\anl\AppData\Roaming\uv\tools\mpremote\lib\site-packages\serial\serialwin32.py", line 259, in in_waiting
raise SerialException("ClearCommError failed ({!r})".format(ctypes.WinError()))
serial.serialutil.SerialException: ClearCommError failed (PermissionError(13, 'The device does not recognize the command.', None, 22))
PS C:\Users\anl>
Windows (After)
PS C:\Users\anl> mpremote
Connected to MicroPython at COM7
Use Ctrl-] or Ctrl-x to exit this shell
MicroPython v1.25.0-1.ge7b0fe4775.dirty on 2025-05-09; Generic ESP32S2 module with ESP32S2
Type "help()" for more information.
>>>
>>>
>>>
device disconnected
PS C:\Users\anl>
Linux (Before)
anl@ANL2-LAP:~/micropython/tools/mpremote$ mpremote
Connected to MicroPython at /dev/ttyACM0
Use Ctrl-] or Ctrl-x to exit this shell
MicroPython v1.25.0-1.ge7b0fe4775.dirty on 2025-05-09; Generic ESP32S2 module with ESP32S2
Type "help()" for more information.
>>>
>>> device disconnected
anl@ANL2-LAP:~/micropython/tools/mpremote$
Linux (After)
anl@ANL2-LAP:~/micropython/tools/mpremote$ mpremote
Connected to MicroPython at /dev/ttyACM0
Use Ctrl-] or Ctrl-x to exit this shell
MicroPython v1.25.0-1.ge7b0fe4775.dirty on 2025-05-09; Generic ESP32S2 module with ESP32S2
Type "help()" for more information.
>>>
>>>
device disconnected
anl@ANL2-LAP:~/micropython/tools/mpremote$
- Tested on Windows 11 with ESP32S2 USB serial
- Tested on Linux (Ubuntu WSL) with ESP32S2 USB serial
- Verified terminal formatting is restored properly
- Confirmed clean exit without stack traces