1 """Helper functions for the Crownstone integration."""
3 from __future__
import annotations
7 from serial.tools.list_ports_common
import ListPortInfo
11 from .const
import DONT_USE_USB, MANUAL_PATH, REFRESH_LIST
15 serial_ports: list[ListPortInfo], no_usb_option: bool =
True
17 """Represent currently available serial ports as string.
19 Adds option to not use usb on top of the list,
20 option to use manual path or refresh list at the end.
22 ports_as_string: list[str] = []
25 ports_as_string.append(DONT_USE_USB)
27 ports_as_string.extend(
28 usb.human_readable_device_name(
33 f
"{hex(port.vid)[2:]:0>4}".upper()
if port.vid
else None,
34 f
"{hex(port.pid)[2:]:0>4}".upper()
if port.pid
else None,
36 for port
in serial_ports
39 ports_as_string.append(MANUAL_PATH)
40 ports_as_string.append(REFRESH_LIST)
42 return ports_as_string
46 """Get the port that the by-id link points to."""
48 by_id =
"/dev/serial/by-id"
49 if by_id
not in dev_path:
53 return f
"/dev/{os.path.basename(os.readlink(dev_path))}"
54 except FileNotFoundError:
58 def map_from_to(val: int, in_min: int, in_max: int, out_min: int, out_max: int) -> int:
59 """Map a value from a range to another."""
60 return int((val - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
int map_from_to(int val, int in_min, int in_max, int out_min, int out_max)
list[str] list_ports_as_str(list[ListPortInfo] serial_ports, bool no_usb_option=True)
str|None get_port(str dev_path)