Skip to content

Commit

Permalink
feat(esploader): Enable context manager for esp instances
Browse files Browse the repository at this point in the history
  • Loading branch information
radimkarnis committed Apr 22, 2024
1 parent 248dc9a commit d4c8cb3
Showing 1 changed file with 10 additions and 2 deletions.
12 changes: 10 additions & 2 deletions esptool/loader.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,8 @@ class ESPLoader(object):
Don't instantiate this base class directly, either instantiate a subclass or
call cmds.detect_chip() which will interrogate the chip and return the
appropriate subclass instance.
appropriate subclass instance. You can also use a context manager as
"with detect_chip() as esp:" to ensure the serial port is closed when done.
"""

Expand Down Expand Up @@ -281,7 +282,8 @@ def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
"""Base constructor for ESPLoader bootloader interaction
Don't call this constructor, either instantiate a specific
ROM class directly, or use cmds.detect_chip().
ROM class directly, or use cmds.detect_chip(). You can use the with
statement to ensure the serial port is closed when done.
This base class has all of the instance methods for bootloader
functionality supported across various chips & stub
Expand Down Expand Up @@ -365,6 +367,12 @@ def __init__(self, port=DEFAULT_PORT, baud=ESP_ROM_BAUD, trace_enabled=False):
# need to set the property back to None or it will continue to fail
self._port.write_timeout = None

def __enter__(self):
return self

def __exit__(self, exc_type, exc_value, traceback):
self._port.close()

@property
def serial_port(self):
return self._port.port
Expand Down

0 comments on commit d4c8cb3

Please sign in to comment.