diff --git a/README.md b/README.md index 4008cf0..1d1bb3d 100644 --- a/README.md +++ b/README.md @@ -82,7 +82,7 @@ Last reviewed **2026-10-27**, on the maintainer's Tianma Mi 8 Lite. The tested camera installation uses **kernel 7.2.12-sdm660, r9 boot plus r11 sensor module**, with signed `platina-libcamera` **0.7.1-r31** and isolated Mesa -26.1.6. The checked-in kernel recipe is the **7.2.12-r12 development candidate**, +26.1.6. The checked-in kernel recipe is the **7.2.12-r13 development candidate**, with device 5-r31 and the public source firmware recipe 2-r5. That combined kernel and a new full 0.8.1 image have **not** passed a complete hardware installation test. Camera packages are built/installed separately; `make images` does not yet add them. diff --git a/docs/BUILDING.md b/docs/BUILDING.md index 6e0d226..a021c81 100644 --- a/docs/BUILDING.md +++ b/docs/BUILDING.md @@ -2,9 +2,9 @@ This is a source-only development port. Integration **0.8.1**, signed camera userspace **0.7.1-r31** and the existing r9-boot/r11-sensor runtime combination -were checked on one Tianma Mi 8 Lite. The public kernel recipe is **7.2.12-r12**, +were checked on one Tianma Mi 8 Lite. The public kernel recipe is **7.2.12-r13**, a development candidate, not the exact tested boot/modules combination. -A combined r12 kernel and a new full 0.8.1 installation image are not hardware +A combined r13 kernel and a new full 0.8.1 installation image are not hardware qualified. The last full base image was built/audited for 0.3.1. Camera packages are separate; see [CAMERA.md](CAMERA.md). @@ -95,6 +95,19 @@ inert without a separately supplied `/etc/platina/usb-power.json` policy; no hos identity or increased-current allowance is cloned from the development phone. Wi-Fi credentials and monitoring credentials also remain per-installation inputs. +New images also install and enable `platina-battery-guard`. It requests charging +between 50% and 65%, pauses charging at 45°C until the battery cools to 42°C, and +requests orderly shutdown at 5% while discharging. An active thermal cutoff stays +latched if a temperature read fails. Emergency shutdown uses init directly and +keeps retrying if shutdown fails; it does not depend on the display helper. + +Charging control requires a writable `charging_enabled` switch or a +`charge_behaviour` interface supporting `auto` and `inhibit-charge`. The guard +never changes `current_max` or `charge_control_limit_max`. If neither switch is +available it logs `Charging control unavailable`; the charge/temperature policy +then cannot be enforced, while low-battery shutdown remains active. Qualify the +actual switch and charge/discharge behavior on the phone before relying on it. + The mkinitfs version used by this port can copy full-rootfs module indexes into an initramfs containing only some modules. The builder automatically regenerates indexes for the modules actually included in the exported boot image. The final @@ -125,7 +138,7 @@ screens. See [display setup](DISPLAY.md) and [shutdown behavior](SHUTDOWN.md). After preparing the candidate environment, build the isolated Mesa and camera packages locally with `scripts/build-camera-userspace.py`; see the complete [camera guide](CAMERA.md#source-build-and-installation-boundary). The camera -package pins libcamera 0.7.1-r31 and the active control/GPU patches. Inactive DMA, +package pins libcamera 0.7.1-r32 and the active control/GPU patches. Inactive DMA, LUT and other rejected experiment patches are not part of this source release. No camera credentials, host-specific deployment helpers or prebuilt APKs are included. `make images` currently integrates the base display/shutdown runtime, diff --git a/docs/CAMERA.md b/docs/CAMERA.md index 9d8c6a1..ca6ec71 100644 --- a/docs/CAMERA.md +++ b/docs/CAMERA.md @@ -85,16 +85,20 @@ python3 scripts/build-camera-userspace.py --component mesa --lax python3 scripts/build-camera-userspace.py --component userspace --lax ``` -This builds isolated Mesa/Freedreno 26.1.6 and `platina-libcamera` 0.7.1-r31. -The latter includes the camera consumer, HTTP/MQTT controller, UI, OpenRC service +This builds isolated Mesa/Freedreno 26.1.6 and `platina-libcamera` 0.7.1-r32. +The r32 source fixes authentication configuration handling: an existing invalid +or unreadable `/etc/platina-camera/auth.json` prevents startup. An absent file or +an explicit JSON `"enabled": false` retains the optional anonymous mode. The +previously tested phone uses r31; r32 still requires server build and phone testing. +The r32 package includes the camera consumer, HTTP/MQTT controller, UI, OpenRC service and the active libcamera patches. Neither command connects to a phone. These packages are not automatically installed by `make images`. Before any installation, qualify a matching camera-enabled kernel and modules, the IMX363/CCI/CAMSS media graph and DW9714 actuator on your own device. A -display-only kernel is insufficient. The source kernel candidate is 7.2.12-r12; +display-only kernel is insufficient. The source kernel candidate is 7.2.12-r13; the tested installation instead uses the separately tested r9 boot and r11 sensor -module runtime combination. **The combined r12 kernel and a new full 0.8.1 image +module runtime combination. **The combined r13 kernel and a new full 0.8.1 image have not passed a complete hardware installation test.** Do not replace a working boot/modules set merely to install the camera userspace. diff --git a/docs/INSTALLATION.md b/docs/INSTALLATION.md index e99c391..ca900d5 100644 --- a/docs/INSTALLATION.md +++ b/docs/INSTALLATION.md @@ -2,7 +2,7 @@ **Development port.** The maintainer's existing phone runs integration0.8.1 with a separately qualified r9 boot/r11 camera-sensor runtime. The source kernel -recipe is7.2.12-r12; its combined full installation has not been hardware accepted. +recipe is7.2.12-r13; its combined full installation has not been hardware accepted. The last new base image was built/audited for0.3.1. Current camera packages are installed separately and are not included automatically by `make images`. There is no supported prebuilt installer. See [BUILDING.md](BUILDING.md) and diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch b/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch index f31f918..cb830d6 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/0040-platina-touch-dual-panel-vsp-power-dvfs.patch @@ -8,7 +8,7 @@ Subject: [PATCH] arm64: dts: qcom: platina: add dual touch, BOE panel, cut VSP/V --- a/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts +++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina.dts -@@ -1182,3 +1182,53 @@ +@@ -1182,3 +1182,50 @@ &pm660_haptics { status = "okay"; }; @@ -61,7 +61,7 @@ Subject: [PATCH] arm64: dts: qcom: platina: add dual touch, BOE panel, cut VSP/V +}; --- /dev/null +++ b/arch/arm64/boot/dts/qcom/sdm660-xiaomi-platina-boe.dts -@@ -0,0 +1,14 @@ +@@ -0,0 +1,11 @@ +// SPDX-License-Identifier: GPL-2.0-only +/dts-v1/; +#include "sdm660-xiaomi-platina.dts" @@ -75,6 +75,6 @@ Subject: [PATCH] arm64: dts: qcom: platina: add dual touch, BOE panel, cut VSP/V +}; --- a/arch/arm64/boot/dts/qcom/Makefile +++ b/arch/arm64/boot/dts/qcom/Makefile -@@ -95,3 +95,4 @@ +@@ -95,1 +95,2 @@ dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-platina.dtb +dtb-$(CONFIG_ARCH_QCOM) += sdm660-xiaomi-platina-boe.dtb diff --git a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD index 6f56d9b..49f4710 100644 --- a/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD +++ b/ports/candidate/linux-postmarketos-qcom-sdm660/APKBUILD @@ -3,7 +3,7 @@ maintainer="Alexey Minnekhanov " _flavor="postmarketos-qcom-sdm660" pkgname=linux-$_flavor pkgver=7.2.12 -pkgrel=12 +pkgrel=13 pkgdesc="Close to mainline linux kernel for Qualcomm Snapdragon 660 SoC" arch="aarch64" url="https://kernel.org/" @@ -163,7 +163,7 @@ ecfee5c3fde9c5342195d5e25f7103d909144d9602497aa4de713fc55d9c03f89601081535d43da7 62031fc20f13bec1bc9a0a67134a2967acbf76cd2d9d3eea9cf5d8176d5bbe61e0063b165b9caf959ec8d923fbb8897cb7421c723d38d695da51a2cb3eddf6c2 0037-imx363-full-field-binning.patch b1094708de883b3aecaf52ddc7f9315c150f6234165ab02ef7a021bc18da4d56cc5eab0f9239583a3b596c307ef71b891f0d735d889156e783b7bb21ba26b448 0038-imx363-platina-legacy-frequency.patch 61a598e63d83c0489ba130231cd0a4c2dc4351de5c122cef9b7170f7f516bae7573c744535035c53e2642a96d13fe5048c07e4c908de8f64c90a3cd8809ee84c 0039-venus-legacy-h264-transform.patch -cc1ea90682e52f9b381cab306705672b0e223e7f486790d9f8c8736b41fd4bb49527330242a95a55fdf10a3fad4d9e626e2af5f5afbc5edd2a9e50219114a213 0040-platina-touch-dual-panel-vsp-power-dvfs.patch +10c8cfcdb1dd5019d02f2657fdb6bc8a53fe9ac1fe3fd64a1ebaea3aee67717492606b1a97f47d58d6d9812c0ae332e8633e3abaac0d6e08050dbaf800ca563b 0040-platina-touch-dual-panel-vsp-power-dvfs.patch 1a7f9cf2443c0f059ac64a78dddee77fca584288edeea943aa45db05fb5e3b7b2930dab595f6c0911671bf5517bd64550a65b097f47d5179cc7454ec90db56cd stable-7.2.3-4.patch 303d4a717c67d5dbb5d17c37882b3ef1b6b44b3cf9b17723a611efe1f028019d5ef53c0e3595ed79f5468a46ede2d640171b9dd97ce2dd99b487d0406ef79f16 stable-7.2.4-5.patch b09a94d0eb3c0382ad8998843019ea0d52ae5a89ad7ba54072b21eeea2c7ee602c57a32a0d9b99a2c5ae1f581dadc4d4395096e905b54678affc18125d9b8cba stable-7.2.5-6.patch diff --git a/project/camera/libcamera-headless/APKBUILD b/project/camera/libcamera-headless/APKBUILD index 661e348..4d2f421 100644 --- a/project/camera/libcamera-headless/APKBUILD +++ b/project/camera/libcamera-headless/APKBUILD @@ -1,7 +1,7 @@ # Headless GPU-enabled camera development build for Platina. pkgname=platina-libcamera pkgver=0.7.1 -pkgrel=31 +pkgrel=32 pkgdesc="Headless libcamera with GPU/CPU software ISP for Platina" url="https://libcamera.org/" arch="aarch64" @@ -83,7 +83,7 @@ d4efc6815992d7e79b12583839f5394700c06f26c057feb2027391cfa9e12fe3bdeb4a7279dea4b1 8938ab20e273c06ab284f825b248e0190167165290d3f54dfdeba3066754dcbca0bde16ed6e29e455e1657fea44bf3fb2e962cdc9e2e3aad0fab214fc09b339b platina_exposure.h d083da94fbd1dd6e7d2e41ea22767e90e9fe8fcba9c4708676683e248c4131d5fbe45a6e4fc0d84680e2f17dbf9ebda75f99dc64e45172138cacb8c24b52de71 platina_zoom.h c28e44e939b3f212fd275967762f67e41a831b52a82a2a512ca21f1d77093ab8a2b1e926b55f775aa42b19e4339ffcf9d66d0223106e0ed41722828c01441441 capture.cpp -4c5a42e531579783f03cd06d444e53ca159ef7ad043aafe8b6f9344e7f347e45d6fcf52600a2c0fec71921d4ccb39ab5f66f865ee9f804a897273859fa9ea615 serve.py +f3fa9e95a83c687cc586d2f6c1cdd8c587eb7dff26e3ff964ce650413415725857c513697e773f7c90798742c05c8452b1c4a32cbab17c8da7ee5301a8fb0df7 serve.py 8c8951b57b88f7e0a24d2f9f2fd9a2aaf0a717c2069e4b44a89c09e4c4891d10d7ff1732b3f3ba3a71e376c30738698a25ffb37949cedb515726aedbf6477cf5 camera_mqtt.py 19550862ce07ec281021923a22d5149d582126bf202a7b4a7214d4cd5001c8ceadc351ddcc2fe7cf7909db53e2a6e77304fc7e7c514b174b49fd6ba5843ebf79 platina-camera.openrc 3a89c3955e01ab24478f0806df294d40cced80b8b17b9421727a176449908da38d7c1f4f9fb61d8ba193fc58b303b0665b996014ab446fab18994c1f97c486ed preview.html diff --git a/project/camera/libcamera-headless/serve.py b/project/camera/libcamera-headless/serve.py index db0a2a1..45bb127 100644 --- a/project/camera/libcamera-headless/serve.py +++ b/project/camera/libcamera-headless/serve.py @@ -321,21 +321,25 @@ class Audio: def load_auth(path): - if not path or not path.exists(): + if path is None: return None try: data = json.loads(path.read_text()) - if not isinstance(data, dict): + except FileNotFoundError: + if not path.is_symlink(): return None - if not data.get('enabled', True): - return None - user = data.get('username') - pwd = data.get('password') - if user and pwd: - return {'username': str(user), 'password': str(pwd)} - except Exception: - pass - return None + raise ValueError('Authentication configuration is unavailable') from None + except (OSError, ValueError): + raise ValueError('Authentication configuration cannot be read') from None + if not isinstance(data, dict) or type(data.get('enabled', True)) is not bool: + raise ValueError('Invalid authentication configuration') + if data.get('enabled') is False: + return None + user, pwd = data.get('username'), data.get('password') + if (not isinstance(user, str) or not user or ':' in user or + not isinstance(pwd, str) or not pwd): + raise ValueError('Authentication requires a username and password') + return {'username': user, 'password': pwd} def make_handler(camera, shutdown, audio=None, auth=None): diff --git a/project/sources.lock.json b/project/sources.lock.json index f7dd5ca..e36f373 100644 --- a/project/sources.lock.json +++ b/project/sources.lock.json @@ -16,7 +16,7 @@ "candidate": { "ports": "ports/candidate", "kernel": "7.2.12", - "kernel_package": "7.2.12-r12", + "kernel_package": "7.2.12-r13", "device_package": "5-r31", "firmware_package": "2-r5" } diff --git a/scripts/Audit-Server-Image.sh b/scripts/Audit-Server-Image.sh index d57efa5..64bd51c 100755 --- a/scripts/Audit-Server-Image.sh +++ b/scripts/Audit-Server-Image.sh @@ -31,7 +31,7 @@ for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos- grep -q "^$package=" /etc/apk/world done python3 /usr/local/libexec/platina-image-runtime audit -for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord; do +for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord platina-battery-guard; do test -L "/etc/runlevels/default/$service" done for key in /etc/ssh/ssh_host_*_key; do diff --git a/scripts/Harden-Server-Image.sh b/scripts/Harden-Server-Image.sh index 8b0ae15..b8cc8e3 100755 --- a/scripts/Harden-Server-Image.sh +++ b/scripts/Harden-Server-Image.sh @@ -55,7 +55,7 @@ for package in device-xiaomi-platina firmware-xiaomi-platina linux-postmarketos- set -- "$@" "$package=$version" done apk add --no-network "$@" -for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord; do +for service in sshd dbus networkmanager usb-moded chronyd local avahi-daemon platina-power-chord platina-battery-guard; do rc-update add "$service" default done printf 'Image configured for SSH keys and passwordless sudo for the dedicated administrator.\n' diff --git a/scripts/image-runtime.py b/scripts/image-runtime.py index 4921723..06fae98 100644 --- a/scripts/image-runtime.py +++ b/scripts/image-runtime.py @@ -21,6 +21,8 @@ HELPERS = { 'scripts/phone-poweroff.py': 'usr/local/sbin/platina-poweroff', 'scripts/phone-power-chord.py': 'usr/local/sbin/platina-power-chord', 'scripts/phone-power-chord.openrc': 'etc/init.d/platina-power-chord', + 'scripts/phone-battery-guard.py': 'usr/local/sbin/platina-battery-guard', + 'scripts/phone-battery-guard.openrc': 'etc/init.d/platina-battery-guard', 'scripts/phone-headless.start': 'etc/local.d/platina-headless.start', 'scripts/phone-usb-power.py': 'usr/local/sbin/platina-usb-power', 'scripts/phone-usb-power-dispatcher.sh': 'etc/NetworkManager/dispatcher.d/90-platina-usb-power', @@ -40,7 +42,8 @@ def layout(version): modes[base + '/' + sub + name] = 0o644 links = {'usr/local/share/platina/current': 'releases/' + version, 'etc/platina-release': '../usr/local/share/platina/current/version', - 'etc/runlevels/default/platina-power-chord': '../../init.d/platina-power-chord'} + 'etc/runlevels/default/platina-power-chord': '../../init.d/platina-power-chord', + 'etc/runlevels/default/platina-battery-guard': '../../init.d/platina-battery-guard'} return base, modes, links @@ -88,7 +91,8 @@ def audit_contents(manifest, read): if len(raw) != display['raw_bytes'] or hashlib.sha256(raw).hexdigest() != display['raw_sha256']: raise ValueError('Screen decoded checksum mismatch') return {'version': version, 'runtime_files': len(modes), 'screens_verified': 2, - 'power_chord_active': True, 'usb_poweroff_requires_unplug': True} + 'power_chord_active': True, 'battery_guard_active': True, + 'usb_poweroff_requires_unplug': True} def audit(root): diff --git a/scripts/phone-battery-guard.openrc b/scripts/phone-battery-guard.openrc index 287bb4f..65d8c56 100755 --- a/scripts/phone-battery-guard.openrc +++ b/scripts/phone-battery-guard.openrc @@ -3,7 +3,10 @@ description="Platina battery health and emergency shutdown daemon (50-65% SoC, a command="/usr/local/sbin/platina-battery-guard" command_user="root:root" command_args="--low ${low:-50} --high ${high:-65} --max-temp ${max_temp:-45} --shutdown-at ${shutdown_at:-5} --interval ${interval:-60}" -command_background="yes" +supervisor="supervise-daemon" +respawn_delay=5 +respawn_max=5 +respawn_period=1800 pidfile="/run/platina-battery-guard.pid" output_log="/var/log/platina-battery-guard.log" error_log="/var/log/platina-battery-guard.log" diff --git a/scripts/phone-battery-guard.py b/scripts/phone-battery-guard.py index d5b70ed..e187c0b 100755 --- a/scripts/phone-battery-guard.py +++ b/scripts/phone-battery-guard.py @@ -49,9 +49,9 @@ class BatteryPolicy: if current_state is not None: self.charging_state = current_state - # Temperature safety cutoff: prevent thermal runaway and pouch swelling + # Power-supply sysfs reports temperature in tenths of a degree Celsius. if temp is not None: - deg_c = temp / 10.0 if temp > 150 else float(temp) + deg_c = temp / 10.0 if deg_c >= self.max_temp: self.thermal_throttled = True self.charging_state = False @@ -62,6 +62,9 @@ class BatteryPolicy: self.thermal_throttled = False else: return False + elif self.thermal_throttled: + self.charging_state = False + return False if capacity >= self.high: self.charging_state = False @@ -126,66 +129,46 @@ def is_battery_discharging(battery_dir, charger_dir=None): def trigger_shutdown(executor=subprocess.run): - """Sync filesystem and execute safe poweroff.""" - print('platina-battery-guard: CRITICAL: battery <= 5% and discharging; emergency poweroff to protect filesystem', flush=True) + """Request orderly init shutdown without relying on a display or suspend helper.""" + print('platina-battery-guard: CRITICAL: battery below shutdown threshold and discharging; emergency poweroff', flush=True) try: os.sync() except Exception: pass - bin_candidates = [ - shutil.which('platina-poweroff'), - '/usr/local/sbin/platina-poweroff', - shutil.which('poweroff'), - '/usr/sbin/poweroff', - ] - target_bin = next((b for b in bin_candidates if b and (Path(b).exists() or shutil.which(b))), '/usr/sbin/poweroff') - return executor([target_bin], check=True) + candidates = ['/usr/sbin/poweroff', '/sbin/poweroff', shutil.which('poweroff')] + attempted = set() + for command in candidates: + if not command or command in attempted: + continue + attempted.add(command) + try: + return executor([command], check=True, timeout=10) + except (OSError, subprocess.SubprocessError): + continue + raise RuntimeError('No orderly poweroff command succeeded') def set_charging(battery_dir, charger_dir, enable): - applied = False - val = '1' if enable else '0' - - # 1. Try battery charging_enabled - if battery_dir: - for node in ('charging_enabled', 'charge_control_limit_max'): - target = battery_dir / node - if target.exists(): - try: - target.write_text(val + '\n') - applied = True - except OSError: - pass - - # 2. Try charger module charging_enabled - if charger_dir: - for node in ('charging_enabled',): - target = charger_dir / node - if target.exists(): - try: - target.write_text(val + '\n') - applied = True - except OSError: - pass - # 3. Fallback: throttle charger current to 0 on disable - if not enable: - cur_target = charger_dir / 'current_max' - if cur_target.exists(): - try: - cur_target.write_text('0\n') - applied = True - except OSError: - pass - else: - cur_target = charger_dir / 'current_max' - if cur_target.exists(): - try: - cur_target.write_text('1500000\n') - applied = True - except OSError: - pass - - return applied + """Use charging switches only; USB input-current policy belongs to the driver/USB helper.""" + for supply in (battery_dir, charger_dir): + if supply is None: + continue + behaviour = supply / 'charge_behaviour' + try: + supported = behaviour.read_text().replace('[', '').replace(']', '').split() + if {'auto', 'inhibit-charge'} <= set(supported): + behaviour.write_text(('auto' if enable else 'inhibit-charge') + '\n') + return True + except OSError: + pass + target = supply / 'charging_enabled' + if target.exists(): + try: + target.write_text(('1' if enable else '0') + '\n') + return True + except OSError: + pass + return False def main(): @@ -219,16 +202,21 @@ def main(): if capacity is not None: # Emergency low-battery safety shutdown: prevent brownout filesystem corruption if policy.should_shutdown(capacity, is_discharging=discharging): - trigger_shutdown() - break + try: + trigger_shutdown() + except RuntimeError as error: + print(f'platina-battery-guard: {error}; retrying next poll', file=sys.stderr, flush=True) + # Keep monitoring until init actually terminates the daemon. action = policy.evaluate(capacity, temp=temp) - set_charging(battery_dir, charger_dir, action) - if policy.thermal_throttled: + applied = set_charging(battery_dir, charger_dir, action) + if not applied: + status_str = 'Charging control unavailable (no writable charging switch); input limit unchanged' + elif policy.thermal_throttled: status_str = 'Charging paused (thermal limit exceeded)' else: status_str = 'Charging enabled' if action else 'Charging paused (protective threshold reached)' - temp_str = f', temp={temp/10:.1f}°C' if temp is not None and temp > 150 else (f', temp={temp}°C' if temp is not None else '') + temp_str = f', temp={temp/10:.1f}°C' if temp is not None else '' power_mode = 'discharging' if discharging else 'external-power' print(f'platina-battery-guard: capacity={capacity}%{temp_str}, power={power_mode}, threshold=[{args.low}%-{args.high}%], state={status_str}', flush=True) diff --git a/scripts/project.py b/scripts/project.py index 2949655..f4d6b8a 100755 --- a/scripts/project.py +++ b/scripts/project.py @@ -17,6 +17,7 @@ ROOT = Path(__file__).resolve().parents[1] RECIPES = ('device-xiaomi-platina', 'firmware-xiaomi-platina', 'linux-postmarketos-qcom-sdm660') ARCHIVES = {'linux-v6.19.10-sdm660.tar.gz', 'linux-dd1ed52c8ceef4f16715118ed0252fe75adbe71d.tar.gz'} +CAMERA_ARCHIVES = {'libcamera-v0.7.1.tar.gz', 'mesa-26.1.6.tar.xz'} def run(command, **kwargs): @@ -77,9 +78,9 @@ def checksums(recipe): return {name.strip(): value for value, name in rows} -def recipe_checks(directory, external): +def recipe_checks(directory, external, packages=RECIPES): # Parse only: never evaluate arbitrary APKBUILD shell code on the host. - for name in RECIPES: + for name in packages: recipe = directory / name / 'APKBUILD' for filename, expected in checksums(recipe).items(): if filename in external: @@ -92,6 +93,11 @@ def recipe_checks(directory, external): install = re.search(r'^install="\$pkgname([^"\n]+)"$', recipe.read_text(), re.M) if install and not (recipe.parent / (name + install[1])).is_file(): raise ValueError('Missing package install hook: ' + name) + for source in sorted(recipe.parent.glob('*.patch')): + result = subprocess.run(['git', 'apply', '--numstat', str(source.resolve())], + capture_output=True, text=True) + if result.returncode: + raise ValueError('Invalid patch format: ' + name + '/' + source.name) def check(): @@ -126,6 +132,8 @@ def check(): if digest(branding / 'platina-linux-logo.png') != provenance['sha256']: raise ValueError('Logo changed without updating provenance') data = lock() + recipe_checks(ROOT / 'project/camera', CAMERA_ARCHIVES, + packages=('libcamera-headless', 'mesa-freedreno')) for profile in data['profiles'].values(): recipe_checks(ROOT / profile['ports'], set(data['local_firmware']) | ARCHIVES) for package, field in zip(RECIPES, ('device_package', 'firmware_package', 'kernel_package')): diff --git a/tests/test_battery_guard.py b/tests/test_battery_guard.py index ad5c0ba..1b09148 100644 --- a/tests/test_battery_guard.py +++ b/tests/test_battery_guard.py @@ -1,8 +1,12 @@ """Verify battery charging guard policy and sysfs integration.""" import importlib.util +import contextlib +import io from pathlib import Path +import subprocess import tempfile import unittest +from unittest.mock import patch ROOT = Path(__file__).resolve().parents[1] spec = importlib.util.spec_from_file_location('battery_guard', ROOT / 'scripts/phone-battery-guard.py') @@ -43,20 +47,50 @@ class BatteryGuardTests(unittest.TestCase): (battery / 'charging_enabled').write_text('1\n') (charger / 'charging_enabled').write_text('1\n') (charger / 'current_max').write_text('1500000\n') + (battery / 'charge_control_limit_max').write_text('100\n') # Disable charging applied = guard.set_charging(battery, charger, False) self.assertTrue(applied) self.assertEqual((battery / 'charging_enabled').read_text().strip(), '0') - self.assertEqual((charger / 'charging_enabled').read_text().strip(), '0') - self.assertEqual((charger / 'current_max').read_text().strip(), '0') + self.assertEqual((charger / 'current_max').read_text().strip(), '1500000') # Enable charging applied = guard.set_charging(battery, charger, True) self.assertTrue(applied) self.assertEqual((battery / 'charging_enabled').read_text().strip(), '1') - self.assertEqual((charger / 'charging_enabled').read_text().strip(), '1') self.assertEqual((charger / 'current_max').read_text().strip(), '1500000') + self.assertEqual((battery / 'charge_control_limit_max').read_text().strip(), '100') + + def test_usb_input_limits_are_never_used_as_charging_switches(self): + with tempfile.TemporaryDirectory() as temp: + charger = Path(temp) + for limit in (500000, 750000, 900000): + with self.subTest(limit=limit): + (charger / 'current_max').write_text(str(limit) + '\n') + for enable in (False, True): + self.assertFalse(guard.set_charging(None, charger, enable)) + self.assertEqual((charger / 'current_max').read_text(), str(limit) + '\n') + (charger / 'charging_enabled').write_text('1\n') + for enable in (False, True): + self.assertTrue(guard.set_charging(None, charger, enable)) + self.assertEqual((charger / 'current_max').read_text(), str(limit) + '\n') + (charger / 'charging_enabled').unlink() + + def test_standard_charge_behaviour_switch(self): + with tempfile.TemporaryDirectory() as temp: + charger = Path(temp) + behaviour = charger / 'charge_behaviour' + for enable, selected in ((False, 'inhibit-charge'), (True, 'auto')): + behaviour.write_text('[auto] inhibit-charge force-discharge\n') + self.assertTrue(guard.set_charging(None, charger, enable)) + self.assertEqual(behaviour.read_text(), selected + '\n') + + def test_failed_charging_switch_reports_unavailable(self): + with tempfile.TemporaryDirectory() as temp: + supply = Path(temp) + (supply / 'charging_enabled').mkdir() + self.assertFalse(guard.set_charging(supply, None, False)) def test_thermal_protection(self): policy = guard.BatteryPolicy(low=50, high=65, max_temp=45) @@ -71,6 +105,20 @@ class BatteryGuardTests(unittest.TestCase): self.assertTrue(policy.evaluate(45, temp=410)) self.assertFalse(policy.thermal_throttled) + def test_missing_temperature_keeps_thermal_cutoff_until_confirmed_cool(self): + policy = guard.BatteryPolicy() + self.assertFalse(policy.evaluate(40, temp=460)) + self.assertFalse(policy.evaluate(40, temp=None)) + self.assertTrue(policy.thermal_throttled) + self.assertFalse(policy.evaluate(40, temp=440)) + self.assertTrue(policy.evaluate(40, temp=420)) + self.assertFalse(policy.thermal_throttled) + + def test_cold_sysfs_temperatures_are_also_tenths_of_a_degree(self): + policy = guard.BatteryPolicy() + for temp in (-50, 0, 100, 150): + self.assertTrue(policy.evaluate(40, temp=temp)) + def test_emergency_low_battery_shutdown(self): policy = guard.BatteryPolicy(low=50, high=65, shutdown_at=5) # Above shutdown threshold: no shutdown @@ -117,9 +165,56 @@ class BatteryGuardTests(unittest.TestCase): called.append(cmd) return None - guard.trigger_shutdown(executor=mock_executor) + with patch.object(guard.os, 'sync'): + guard.trigger_shutdown(executor=mock_executor) self.assertEqual(len(called), 1) - self.assertTrue(any('poweroff' in part for part in called[0])) + self.assertEqual(called[0], ['/usr/sbin/poweroff']) + + def test_shutdown_bypasses_display_and_falls_back_on_missing_binary(self): + called = [] + + def executor(cmd, **kwargs): + called.append(cmd) + self.assertEqual(kwargs, dict(check=True, timeout=10)) + if len(called) == 1: + raise FileNotFoundError('missing') + + with patch.object(guard.os, 'sync'): + guard.trigger_shutdown(executor=executor) + self.assertEqual(called, [['/usr/sbin/poweroff'], ['/sbin/poweroff']]) + + def test_shutdown_reports_failure_if_all_orderly_commands_fail(self): + def executor(cmd, **kwargs): + raise subprocess.TimeoutExpired(cmd, 10) + + with patch.object(guard.os, 'sync'), patch.object(guard.shutil, 'which', return_value=None): + with self.assertRaisesRegex(RuntimeError, 'No orderly poweroff'): + guard.trigger_shutdown(executor=executor) + + def test_daemon_retries_shutdown_and_waits_for_actual_init_shutdown(self): + signals = {} + sleeps = [] + + def sleep(interval): + sleeps.append(interval) + if len(sleeps) == 2: + signals[guard.signal.SIGTERM]() + + with patch.object(guard.sys, 'argv', ['guard']), \ + patch.object(guard, 'find_supply', return_value=None), \ + patch.object(guard, 'get_capacity', return_value=5), \ + patch.object(guard, 'get_temp', return_value=300), \ + patch.object(guard, 'is_battery_discharging', return_value=True), \ + patch.object(guard, 'set_charging', return_value=False), \ + patch.object(guard, 'trigger_shutdown', side_effect=[RuntimeError('failed'), None]) as shutdown, \ + patch.object(guard.signal, 'signal', side_effect=lambda sig, handler: signals.update({sig: handler})), \ + patch.object(guard.time, 'sleep', side_effect=sleep), \ + contextlib.redirect_stdout(io.StringIO()) as output, \ + contextlib.redirect_stderr(io.StringIO()) as errors: + guard.main() + self.assertEqual(shutdown.call_count, 2) + self.assertIn('retrying next poll', errors.getvalue()) + self.assertIn('Charging control unavailable', output.getvalue()) if __name__ == '__main__': diff --git a/tests/test_camera_control.py b/tests/test_camera_control.py index fb42b47..936d063 100644 --- a/tests/test_camera_control.py +++ b/tests/test_camera_control.py @@ -27,6 +27,39 @@ serve = module('serve') mqtt = module('camera_mqtt') +class AuthenticationConfigTests(unittest.TestCase): + def test_optional_and_explicitly_disabled_authentication(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / 'auth.json' + self.assertIsNone(serve.load_auth(path)) + path.write_text(json.dumps({'enabled': False})) + self.assertIsNone(serve.load_auth(path)) + path.write_text(json.dumps({'username': 'operator', 'password': 'test-password'})) + self.assertEqual(serve.load_auth(path), {'username': 'operator', 'password': 'test-password'}) + + def test_invalid_authentication_never_falls_back_to_anonymous(self): + with tempfile.TemporaryDirectory() as temp: + path = Path(temp) / 'auth.json' + for content in ('{broken', '[]', '{}', '{"enabled": "false"}', + '{"username": "operator"}', '{"username": "", "password": "value"}', + '{"username": 123, "password": "value"}'): + with self.subTest(content=content): + path.write_text(content) + with self.assertRaises(ValueError): + serve.load_auth(path) + path.unlink() + path.symlink_to('missing-credentials') + with self.assertRaises(ValueError): + serve.load_auth(path) + + def test_unreadable_authentication_aborts_without_exposing_credentials(self): + path = Mock() + path.read_text.side_effect = PermissionError('sensitive contents') + with self.assertRaisesRegex(ValueError, 'cannot be read') as error: + serve.load_auth(path) + self.assertNotIn('sensitive', str(error.exception)) + + class ControlTests(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() diff --git a/tests/test_image_runtime.py b/tests/test_image_runtime.py index fa55891..5b89584 100644 --- a/tests/test_image_runtime.py +++ b/tests/test_image_runtime.py @@ -37,6 +37,9 @@ class ImageRuntimeTests(unittest.TestCase): self.assertEqual(runtime.audit(self.root), self.result) self.assertEqual(self.result['screens_verified'], 2) self.assertTrue((self.root / 'etc/runlevels/default/platina-power-chord').is_file()) + self.assertTrue(self.result['battery_guard_active']) + self.assertTrue((self.root / 'etc/runlevels/default/platina-battery-guard').is_file()) + self.assertTrue((self.root / 'usr/local/sbin/platina-battery-guard').is_file()) self.assertIn('dry_run=no', (self.root / runtime.CONFIG).read_text()) self.assertEqual((self.root / 'etc/platina-release').read_text(), 'Platina Linux ' + self.result['version'] + '\n') @@ -66,6 +69,14 @@ class ImageRuntimeTests(unittest.TestCase): with self.assertRaisesRegex(ValueError, 'symlink'): runtime.audit(self.root) + def test_battery_guard_missing_or_disabled_is_rejected(self): + (self.root / 'etc/runlevels/default/platina-battery-guard').unlink() + with self.assertRaisesRegex(ValueError, 'symlink'): + runtime.audit(self.root) + (self.root / 'usr/local/sbin/platina-battery-guard').unlink() + with self.assertRaises(FileNotFoundError): + runtime.audit(self.root) + def test_manifest_cannot_add_unrelated_or_traversing_files(self): path = self.root / runtime.MANIFEST manifest = json.loads(path.read_text()) diff --git a/tests/test_workflow.py b/tests/test_workflow.py index b82590a..446c293 100644 --- a/tests/test_workflow.py +++ b/tests/test_workflow.py @@ -75,6 +75,41 @@ class ArtifactTests(unittest.TestCase): self.verify() +class RecipeChecksTests(unittest.TestCase): + def setUp(self): + self.temp = tempfile.TemporaryDirectory() + self.addCleanup(self.temp.cleanup) + self.root = Path(self.temp.name) + self.package = self.root / 'camera' + self.package.mkdir() + + def recipe(self, name, content): + source = self.package / name + source.write_text(content) + (self.package / 'APKBUILD').write_text( + 'sha512sums="\n' + workflow.digest(source, 'sha512') + ' ' + name + '\n"\n') + return source + + def check(self): + workflow.recipe_checks(self.root, set(), packages=('camera',)) + + def test_camera_source_checksum_is_checked(self): + source = self.recipe('serve.py', 'print("original")\n') + self.check() + source.write_text('print("changed")\n') + with self.assertRaisesRegex(ValueError, 'Recipe input'): + self.check() + + def test_patch_syntax_is_checked_even_with_matching_checksum(self): + self.recipe('bad.patch', '--- a/file\n+++ b/file\n@@ -1 +1,2 @@\n-old\n+new\n') + with self.assertRaisesRegex(ValueError, 'Invalid patch format'): + self.check() + + def test_valid_patch_is_accepted_without_upstream_checkout(self): + self.recipe('valid.patch', '--- a/file\n+++ b/file\n@@ -1 +1 @@\n-old\n+new\n') + self.check() + + class PrepareTests(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory()