battery_boost.tlp_parser

Parsing utilities for interpreting tlp-stat -b output.

BatteryInfo

Bases: TypedDict

Battery info object.

Source code in src/battery_boost/tlp_parser.py
 9
10
11
12
class BatteryInfo(TypedDict):
    """Battery info object."""
    discharging: bool
    info: str

parse_tlp_stats

Parse TLP battery stats and return a human-readable summary.

Parameters:

Name Type Description Default
tlp_stats str

Output string from tlp_get_stats().

required

Returns:

Name Type Description
BatteryInfo BatteryInfo

discharge status, and battery statistics or an error message.

Source code in src/battery_boost/tlp_parser.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
def parse_tlp_stats(tlp_stats: str) -> BatteryInfo:
    """Parse TLP battery stats and return a human-readable summary.

    Args:
        tlp_stats: Output string from `tlp_get_stats()`.

    Returns:
        BatteryInfo: discharge status, and battery statistics or an error message.
    """
    if not tlp_stats.strip():
        return {'discharging': False, 'info': "No battery data found."}

    is_discharging = False
    lines = tlp_stats.splitlines()
    stats = []
    current_battery = ""
    battery_info: defaultdict[str, str] = defaultdict(lambda: UNKNOWN)

    for line in lines:
        line = line.strip()
        # Detect start of a new battery section
        if line.startswith('+++ ') and 'Battery Status:' in line:
            # Save previous battery (if any)
            if current_battery:
                stats.append(_format_battery_str(current_battery, battery_info))

            # Start new one
            try:
                current_battery = line.split('Battery Status:')[1].strip()
            except IndexError:
                pass
            battery_info = defaultdict(lambda: UNKNOWN)
            continue

        # Parse values.
        if 'charge_control_start_threshold' in line:
            battery_info['start'] = _get_battery_value(line)
        elif 'charge_control_end_threshold' in line:
            battery_info['end'] = _get_battery_value(line)
        elif line.startswith('Charge'):
            battery_info['charge'] = _get_battery_value(line)
        elif line.startswith('Capacity'):
            battery_info['capacity'] = _get_battery_value(line)
        elif 'status' in line:
            battery_info['status'] = _get_battery_status(line)
            if battery_info['status'].strip().lower() == 'discharging':
                is_discharging = True  # If any batery is discharging.

    # Add the last battery
    if current_battery and battery_info:
        stats.append(_format_battery_str(current_battery, battery_info))

    info = '\n'.join(stats) if stats else "No battery data found."
    return {'discharging': is_discharging, 'info': info}