Home Assistant Unofficial Reference 2024.12.1
helpers.py
Go to the documentation of this file.
1 """Helper functions for the Crownstone integration."""
2 
3 from __future__ import annotations
4 
5 import os
6 
7 from serial.tools.list_ports_common import ListPortInfo
8 
9 from homeassistant.components import usb
10 
11 from .const import DONT_USE_USB, MANUAL_PATH, REFRESH_LIST
12 
13 
15  serial_ports: list[ListPortInfo], no_usb_option: bool = True
16 ) -> list[str]:
17  """Represent currently available serial ports as string.
18 
19  Adds option to not use usb on top of the list,
20  option to use manual path or refresh list at the end.
21  """
22  ports_as_string: list[str] = []
23 
24  if no_usb_option:
25  ports_as_string.append(DONT_USE_USB)
26 
27  ports_as_string.extend(
28  usb.human_readable_device_name(
29  port.device,
30  port.serial_number,
31  port.manufacturer,
32  port.description,
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,
35  )
36  for port in serial_ports
37  )
38 
39  ports_as_string.append(MANUAL_PATH)
40  ports_as_string.append(REFRESH_LIST)
41 
42  return ports_as_string
43 
44 
45 def get_port(dev_path: str) -> str | None:
46  """Get the port that the by-id link points to."""
47  # not a by-id link, but just given path
48  by_id = "/dev/serial/by-id"
49  if by_id not in dev_path:
50  return dev_path
51 
52  try:
53  return f"/dev/{os.path.basename(os.readlink(dev_path))}"
54  except FileNotFoundError:
55  return None
56 
57 
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)
Definition: helpers.py:58
list[str] list_ports_as_str(list[ListPortInfo] serial_ports, bool no_usb_option=True)
Definition: helpers.py:16