From 8017246fd57d73477269cab624bf108fb4629ab4 Mon Sep 17 00:00:00 2001 From: Philippe Teuwen Date: Sat, 29 Aug 2026 14:45:17 +0200 Subject: [PATCH] Battery test scripts --- client/pyscripts/pm5_battery_test.py | 77 +++++++++++++++ client/pyscripts/pm5_battery_test_graph.py | 107 +++++++++++++++++++++ 2 files changed, 184 insertions(+) create mode 100755 client/pyscripts/pm5_battery_test.py create mode 100755 client/pyscripts/pm5_battery_test_graph.py diff --git a/client/pyscripts/pm5_battery_test.py b/client/pyscripts/pm5_battery_test.py new file mode 100755 index 000000000..e28b213d4 --- /dev/null +++ b/client/pyscripts/pm5_battery_test.py @@ -0,0 +1,77 @@ +#!/usr/bin/env -S uv run pm3 -y + +import re +import time +import csv +import os +import pm3 + + +# Limit the number of loops +DEBUG_LIMIT = 0 +# DEBUG_LIMIT = 5 + +# To test fast discharge, you can activate the HF field before running this script +# hf 14a raw -ak 00 + + +def main(): + p = pm3.pm3() + + voltage = current = temp = capacity = soc = 0 + stop = False + + csv_path = f"battery_log_{time.strftime('%Y-%m-%d_%H-%M-%S')}.csv" + csv_file = open(csv_path, "w", newline="") + writer = csv.writer(csv_file) + writer.writerow(["timestamp", "voltage_mV", "current_mA", "temp_C", "capacity_mAh", "soc_percent"]) + + n = 0 + while DEBUG_LIMIT == 0 or n < DEBUG_LIMIT: + p.console("hw status") + for line in p.grabbed_output.split('\n'): + if "Battery voltage" in line: + # print(line) + voltage = float(re.search(r"([\d.]+)\s*mV", line).group(1)) + if voltage < 3200: + print(f"Voltage {voltage} mV is below 3200 mV, stopping test.") + stop = True + if "Battery current" in line: + # print(line) + current = float(re.search(r"([\d.]+)\s*mA", line).group(1)) + if "idle" in line: + stop = True + if "Battery SoC" in line: + # print(line) + soc = float(re.search(r"([\d.]+)\s*%", line).group(1)) + if "Temp (gauge)" in line: + # print(line) + temp = float(re.search(r"([\d.]+)\s*C", line).group(1)) + if "Remaining capacity" in line: + # print(line) + capacity = float(re.search(r"([\d.]+)\s*mAh", line).group(1)) + timestamp = time.strftime("%Y-%m-%d %H:%M:%S") + print(f"[{timestamp}] Voltage: {voltage} mV, Current: {current} mA, " + f"Temp: {temp} C, Capacity: {capacity} mAh, SoC: {soc} %") + writer.writerow([timestamp, voltage, current, temp, capacity, soc]) + csv_file.flush() + os.fsync(csv_file.fileno()) + if stop or (DEBUG_LIMIT != 0 and n >= DEBUG_LIMIT): + break + + time.sleep(10) + # if current > 0: + # # Charging + # time.sleep(10) + # else: + # # Discharging + # p.console("hf 14a read -n 20") + # p.console("hf 14a raw -ak 00") + n += 1 + + csv_file.close() + p.console("hf 14a read --drop") + + +if __name__ == '__main__': + main() \ No newline at end of file diff --git a/client/pyscripts/pm5_battery_test_graph.py b/client/pyscripts/pm5_battery_test_graph.py new file mode 100755 index 000000000..5e5efecd2 --- /dev/null +++ b/client/pyscripts/pm5_battery_test_graph.py @@ -0,0 +1,107 @@ +#!/usr/bin/env python3 +""" +Plot battery log CSV (timestamp, voltage_mV, current_mA, temp_C, capacity_mAh). + +Since the logging script didn't sleep between iterations, rows can be much +closer together than 10s apart. This script keeps only one row per 10-second +window (the first row seen in each window) before plotting, so the graphs +aren't overcrowded with near-duplicate points. + +Usage: + python plot_battery_log.py [input_csv] [output_png] + +Defaults: + input_csv = battery_log.csv + output_png = battery_log.png +""" + +import sys +import csv +from datetime import datetime + +import matplotlib +matplotlib.use("Agg") +import matplotlib.pyplot as plt +import matplotlib.dates as mdates +from PIL import Image + + +def load_and_downsample(csv_path, min_interval_s=10): + rows = [] + with open(csv_path, newline="") as f: + reader = csv.DictReader(f) + for row in reader: + try: + ts = datetime.strptime(row["timestamp"], "%Y-%m-%d %H:%M:%S") + except (KeyError, ValueError): + continue + rows.append({ + "timestamp": ts, + "voltage_mV": float(row["voltage_mV"]) if row["voltage_mV"] else None, + "current_mA": float(row["current_mA"]) if row["current_mA"] else None, + "temp_C": float(row["temp_C"]) if row["temp_C"] else None, + "capacity_mAh": float(row["capacity_mAh"]) if row["capacity_mAh"] else None, + "soc_percent": float(row["soc_percent"]) if row["soc_percent"] else None, + }) + + rows.sort(key=lambda r: r["timestamp"]) + + if min_interval_s > 0: + downsampled = [] + last_ts = None + for r in rows: + if last_ts is None or (r["timestamp"] - last_ts).total_seconds() >= min_interval_s: + downsampled.append(r) + last_ts = r["timestamp"] + return downsampled + else: + return rows + + +def plot(rows, output_path): + timestamps = [r["timestamp"] for r in rows] + fields = [ + ("voltage_mV", "Voltage (mV)"), + ("current_mA", "Current (mA)"), + ("temp_C", "Temperature (C)"), + ("capacity_mAh", "Remaining capacity (mAh)"), + ("soc_percent", "Battery SoC (%)"), + ] + + fig, axes = plt.subplots(len(fields), 1, figsize=(10, 12), sharex=True) + + for ax, (key, label) in zip(axes, fields): + values = [r[key] for r in rows] + ax.plot(timestamps, values, marker="o", markersize=3, linewidth=1) + ax.set_ylabel(label) + ax.grid(True, alpha=0.3) + + axes[-1].set_xlabel("Time") + axes[-1].xaxis.set_major_formatter(mdates.DateFormatter("%H:%M:%S")) + fig.autofmt_xdate() + fig.suptitle("Battery status over time") + fig.tight_layout(rect=[0, 0, 1, 0.97]) + fig.savefig(output_path, dpi=150) + print(f"Saved plot to {output_path}") + return output_path + + +def main(): + input_csv = sys.argv[1] if len(sys.argv) > 1 else "battery_log.csv" + output_png = sys.argv[2] if len(sys.argv) > 2 else "battery_log.png" + + min_interval_s = 10 + rows = load_and_downsample(input_csv, min_interval_s=min_interval_s) + if not rows: + print("No valid rows found in CSV.") + return + if min_interval_s > 0: + print(f"{len(rows)} points after downsampling") + + output_path = plot(rows, output_png) + img = Image.open(output_path) + img.show() + + +if __name__ == "__main__": + main()