| 1 |
""" |
| 2 |
A library reading under voltage bit from the official Raspberry Pi Kernel. |
| 3 |
|
| 4 |
Minimal Kernel needed is 4.14+ |
| 5 |
""" |
| 6 |
import logging |
| 7 |
import os |
| 8 |
from typing import Optional, Text |
| 9 |
|
| 10 |
_LOGGER = logging.getLogger(__name__) |
| 11 |
|
| 12 |
HWMON_NAME = "rpi_volt" |
| 13 |
|
| 14 |
SYSFILE_HWMON_DIR = "/sys/class/hwmon" |
| 15 |
SYSFILE_HWMON_FILE = "in0_lcrit_alarm" |
| 16 |
SYSFILE_LEGACY = "/sys/devices/platform/soc/soc:firmware/get_throttled" |
| 17 |
|
| 18 |
UNDERVOLTAGE_STICKY_BIT = 1 << 16 |
| 19 |
|
| 20 |
|
| 21 |
def get_rpi_volt_hwmon() -> Optional[Text]: |
| 22 |
"""Find rpi_volt hwmon device.""" |
| 23 |
try: |
| 24 |
hwmons = os.listdir(SYSFILE_HWMON_DIR) |
| 25 |
except FileNotFoundError: |
| 26 |
return None |
| 27 |
|
| 28 |
for hwmon in hwmons: |
| 29 |
name_file = os.path.join(SYSFILE_HWMON_DIR, hwmon, "name") |
| 30 |
if os.path.isfile(name_file): |
| 31 |
with open(name_file) as file: |
| 32 |
hwmon_name = file.read().strip() |
| 33 |
if hwmon_name == HWMON_NAME: |
| 34 |
return os.path.join(SYSFILE_HWMON_DIR, hwmon) |
| 35 |
|
| 36 |
return None |
| 37 |
|
| 38 |
|
| 39 |
class UnderVoltage: |
| 40 |
"""Read under voltage status.""" |
| 41 |
|
| 42 |
def get(self) -> bool: |
| 43 |
"""Get under voltage status.""" |
| 44 |
|
| 45 |
|
| 46 |
class UnderVoltageNew(UnderVoltage): |
| 47 |
"""Read under voltage status from new entry.""" |
| 48 |
|
| 49 |
def __init__(self, hwmon: Text): |
| 50 |
"""Initialize the under voltage class.""" |
| 51 |
self._hwmon = hwmon |
| 52 |
|
| 53 |
def get(self) -> bool: |
| 54 |
"""Get under voltage status.""" |
| 55 |
|
| 56 |
with open(os.path.join(self._hwmon, SYSFILE_HWMON_FILE)) as file: |
| 57 |
bit = file.read()[:-1] |
| 58 |
_LOGGER.debug("Get under voltage status: %s", bit) |
| 59 |
return bit == "1" |
| 60 |
|
| 61 |
|
| 62 |
class UnderVoltageLegacy(UnderVoltage): |
| 63 |
"""Read under voltage status from legacy entry.""" |
| 64 |
|
| 65 |
def get(self) -> bool: |
| 66 |
"""Get under voltage status.""" |
| 67 |
|
| 68 |
with open(SYSFILE_LEGACY) as file: |
| 69 |
throttled = file.read()[:-1] |
| 70 |
_LOGGER.debug("Get throttled value: %s", throttled) |
| 71 |
return ( |
| 72 |
int(throttled, base=16) & UNDERVOLTAGE_STICKY_BIT == UNDERVOLTAGE_STICKY_BIT |
| 73 |
) |
| 74 |
|
| 75 |
|
| 76 |
def new_under_voltage() -> Optional[UnderVoltage]: |
| 77 |
"""Create new UnderVoltage object.""" |
| 78 |
hwmon = get_rpi_volt_hwmon() |
| 79 |
if hwmon: |
| 80 |
return UnderVoltageNew(hwmon) |
| 81 |
if os.path.isfile(SYSFILE_LEGACY): |
| 82 |
return UnderVoltageLegacy() |
| 83 |
return None |