battery_boost.helper_functions

Helper functions for Battery Boost.

command_on_path

Return True if command is available in PATH, else False.

Source code in src/battery_boost/helper_functions.py
20
21
22
def command_on_path(command: str) -> bool:
    """Return True if command is available in PATH, else False."""
    return bool(shutil.which(command))

get_battery_stats

Retrieve raw statistics from battery.

Failure of tlp_get_stats() may be non-fatal, so we just return the message for display and let the user decide what to do.

Returns:

Name Type Description
BatteryInfo BatteryInfo

discharge status, and battery statistics or

BatteryInfo

an error message.

Source code in src/battery_boost/helper_functions.py
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
def get_battery_stats() -> BatteryInfo:
    """Retrieve raw statistics from battery.

    Failure of `tlp_get_stats()` may be non-fatal, so we just return
    the message for display and let the user decide what to do.

    Returns:
        BatteryInfo: discharge status, and battery statistics or
        an error message.
    """
    try:
        raw_stats = tlp_get_stats()
        return parse_tlp_stats(raw_stats)
    except TlpCommandError as exc:
        return {'discharging': False, 'info': f"Error: {exc}"}

on_ac_power

Return True if on AC power, else False.

Raises:

Type Description
RuntimeError

If AC power cannot be determined.

Source code in src/battery_boost/helper_functions.py
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
def on_ac_power() -> bool:
    """Return True if on AC power, else False.

    Raises:
        RuntimeError: If AC power cannot be determined.
   """
    base = Path("/sys/class/power_supply")
    if base.is_dir():
        for child in base.iterdir():
            type_file = child / "type"
            try:
                # Check for AC adaptor.
                if type_file.is_file() and type_file.read_text().strip() == "Mains":
                    # Then check if it online.
                    online_file = child / "online"
                    if online_file.is_file():
                        return online_file.read_text().strip() == "1"
            except OSError:
                pass
    # Unsupported system
    raise RuntimeError("Power supply information not available.")

parse_args

Parse command-line arguments and return configuration.

Parameters:

Name Type Description Default
argv list[str]

List of command-line arguments.

required

Returns:

Name Type Description
tuple Config

(theme_dict, standard_font, small_font, scale_factor).

Source code in src/battery_boost/helper_functions.py
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
def parse_args(argv: list[str]) -> Config:
    """Parse command-line arguments and return configuration.

    Args:
        argv: List of command-line arguments.

    Returns:
        tuple: (theme_dict, standard_font, small_font, scale_factor).
    """
    parser = argparse.ArgumentParser(
        description="A simple GUI to enable `tlp fullcharge`.",
        # Automatically add defaults to help text.
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument('-v', '--version',
                        action='version',
                        version=f"Battery Boost {version('tlp-battery-boost')}")

    parser.add_argument(
        '-f', '--font-size',
        type=int,
        choices=range(1, 6),
        default=3,
        metavar="{1-5}",
        help="Font size [1-5] (1=smallest, 5=largest)")

    parser.add_argument(
        '-t', '--theme',
        choices=['light', 'dark'],
        default='light' if DEFAULT_THEME == THEME[ThemeName.LIGHT] else 'dark',
        help="Color theme")

    parsed_args = parser.parse_args(argv)
    standard_font, small_font, scale_factor = FONT_SIZES[parsed_args.font_size]
    return THEME[ThemeName(parsed_args.theme)], standard_font, small_font, scale_factor