Home Assistant Unofficial Reference 2024.12.1
util.py
Go to the documentation of this file.
1 """Utils for System Monitor."""
2 
3 import logging
4 import os
5 
6 from psutil._common import shwtemp
7 import psutil_home_assistant as ha_psutil
8 
9 from homeassistant.core import HomeAssistant
10 
11 from .const import CPU_SENSOR_PREFIXES
12 
13 _LOGGER = logging.getLogger(__name__)
14 
15 SKIP_DISK_TYPES = {"proc", "tmpfs", "devtmpfs"}
16 
17 
19  hass: HomeAssistant, psutil_wrapper: ha_psutil.PsutilWrapper
20 ) -> set[str]:
21  """Return all disk mount points on system."""
22  disks: set[str] = set()
23  for part in psutil_wrapper.psutil.disk_partitions(all=True):
24  if os.name == "nt":
25  if "cdrom" in part.opts or part.fstype == "":
26  # skip cd-rom drives with no disk in it; they may raise
27  # ENOENT, pop-up a Windows GUI error for a non-ready
28  # partition or just hang.
29  continue
30  if part.fstype in SKIP_DISK_TYPES:
31  # Ignore disks which are memory
32  continue
33  try:
34  if not os.path.isdir(part.mountpoint):
35  _LOGGER.debug(
36  "Mountpoint %s was excluded because it is not a directory",
37  part.mountpoint,
38  )
39  continue
40  usage = psutil_wrapper.psutil.disk_usage(part.mountpoint)
41  except PermissionError:
42  _LOGGER.debug(
43  "No permission for running user to access %s", part.mountpoint
44  )
45  continue
46  except OSError as err:
47  _LOGGER.debug(
48  "Mountpoint %s was excluded because of: %s", part.mountpoint, err
49  )
50  continue
51  if usage.total > 0 and part.device != "":
52  disks.add(part.mountpoint)
53  _LOGGER.debug("Adding disks: %s", ", ".join(disks))
54  return disks
55 
56 
58  hass: HomeAssistant, psutil_wrapper: ha_psutil.PsutilWrapper
59 ) -> set[str]:
60  """Return all network interfaces on system."""
61  interfaces: set[str] = set()
62  for interface in psutil_wrapper.psutil.net_if_addrs():
63  if interface.startswith("veth"):
64  # Don't load docker virtual network interfaces
65  continue
66  interfaces.add(interface)
67  _LOGGER.debug("Adding interfaces: %s", ", ".join(interfaces))
68  return interfaces
69 
70 
71 def get_all_running_processes(hass: HomeAssistant) -> set[str]:
72  """Return all running processes on system."""
73  psutil_wrapper = ha_psutil.PsutilWrapper()
74  processes: set[str] = set()
75  for proc in psutil_wrapper.psutil.process_iter(["name"]):
76  if proc.name() not in processes:
77  processes.add(proc.name())
78  _LOGGER.debug("Running processes: %s", ", ".join(processes))
79  return processes
80 
81 
82 def read_cpu_temperature(temps: dict[str, list[shwtemp]]) -> float | None:
83  """Attempt to read CPU / processor temperature."""
84  entry: shwtemp
85 
86  _LOGGER.debug("CPU Temperatures: %s", temps)
87  for name, entries in temps.items():
88  for i, entry in enumerate(entries, start=1):
89  # In case the label is empty (e.g. on Raspberry PI 4),
90  # construct it ourself here based on the sensor key name.
91  _label = f"{name} {i}" if not entry.label else entry.label
92  # check both name and label because some systems embed cpu# in the
93  # name, which makes label not match because label adds cpu# at end.
94  if _label in CPU_SENSOR_PREFIXES or name in CPU_SENSOR_PREFIXES:
95  return round(entry.current, 1)
96 
97  return None
set[str] get_all_running_processes(HomeAssistant hass)
Definition: util.py:71
float|None read_cpu_temperature(dict[str, list[shwtemp]] temps)
Definition: util.py:82
set[str] get_all_disk_mounts(HomeAssistant hass, ha_psutil.PsutilWrapper psutil_wrapper)
Definition: util.py:20
set[str] get_all_network_interfaces(HomeAssistant hass, ha_psutil.PsutilWrapper psutil_wrapper)
Definition: util.py:59