esphome-flasher/esphomeflasher/helpers.py

39 lines
1.0 KiB
Python
Raw Normal View History

2018-11-07 21:24:25 +01:00
from __future__ import print_function
import os
import sys
import serial
2021-10-29 12:48:46 +02:00
# pylint: disable=unspecified-encoding,consider-using-with
DEVNULL = open(os.devnull, "w")
2018-11-07 21:24:25 +01:00
def list_serial_ports():
# from https://github.com/pyserial/pyserial/blob/master/serial/tools/list_ports.py
from serial.tools.list_ports import comports
2021-10-29 12:48:46 +02:00
2018-11-07 21:24:25 +01:00
result = []
for port, desc, info in comports():
if not port or "VID:PID" not in info:
continue
2021-10-29 12:48:46 +02:00
split_desc = desc.split(" - ")
2018-11-07 21:24:25 +01:00
if len(split_desc) == 2 and split_desc[0] == split_desc[1]:
desc = split_desc[0]
result.append((port, desc))
result.sort()
return result
def prevent_print(func, *args, **kwargs):
orig_sys_stdout = sys.stdout
sys.stdout = DEVNULL
try:
return func(*args, **kwargs)
except serial.SerialException as err:
from esphomeflasher.common import EsphomeflasherError
2021-10-29 12:48:46 +02:00
raise EsphomeflasherError(f"Serial port closed: {err}") from err
2018-11-07 21:24:25 +01:00
finally:
sys.stdout = orig_sys_stdout