Files
mi8-platina-linux/scripts/phone-status-screen.py
T
2026-11-18 01:39:26 +09:00

702 lines
30 KiB
Python
Executable File

#!/usr/bin/env python3
"""Render live system status or offline charger screen onto Platina /dev/fb0 (stdlib only)."""
import argparse
import fcntl
import json
import mmap
import os
from pathlib import Path
import signal
import struct
import subprocess
import sys
import time
BACKLIGHT = Path('/sys/class/backlight/backlight')
DRIVER = Path('/sys/bus/mipi-dsi/devices/c994000.dsi.0/driver')
PANEL = b'xiaomi,platina-tianma-nt36672a'
SPLASH_LOCK = Path('/run/platina-splash.lock')
FBIOBLANK = 0x4611
# BGRX8888 4-byte pixel helpers (little-endian: B, G, R, X=0)
def bgrx(r, g, b):
return bytes((b & 0xff, g & 0xff, r & 0xff, 0))
COL_BG = bgrx(6, 10, 14)
COL_CARD = bgrx(14, 21, 28)
COL_BORDER = bgrx(36, 53, 66)
COL_TEXT = bgrx(226, 236, 244)
COL_MUTED = bgrx(138, 160, 178)
COL_ACCENT = bgrx(64, 184, 248)
COL_GREEN = bgrx(56, 208, 128)
COL_AMBER = bgrx(248, 184, 48)
COL_RED = bgrx(240, 82, 82)
COL_BAR_BG = bgrx(24, 34, 44)
# Crisp 8x8 bitmap font for printable ASCII (0x20..0x7E); bit 7 is leftmost pixel.
FONT_8X8 = {
' ': (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
'!': (0x18, 0x3c, 0x3c, 0x18, 0x18, 0x00, 0x18, 0x00),
'"': (0x6c, 0x6c, 0x48, 0x00, 0x00, 0x00, 0x00, 0x00),
'#': (0x36, 0x36, 0x7f, 0x36, 0x7f, 0x36, 0x36, 0x00),
'$': (0x18, 0x3e, 0x60, 0x3c, 0x06, 0x7c, 0x18, 0x00),
'%': (0x62, 0x64, 0x08, 0x10, 0x26, 0x46, 0x00, 0x00),
'&': (0x38, 0x44, 0x38, 0x74, 0x4c, 0x44, 0x3a, 0x00),
"'": (0x18, 0x18, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00),
'(': (0x0c, 0x18, 0x30, 0x30, 0x30, 0x18, 0x0c, 0x00),
')': (0x30, 0x18, 0x0c, 0x0c, 0x0c, 0x18, 0x30, 0x00),
'*': (0x00, 0x66, 0x3c, 0xff, 0x3c, 0x66, 0x00, 0x00),
'+': (0x00, 0x18, 0x18, 0x7e, 0x18, 0x18, 0x00, 0x00),
',': (0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x30),
'-': (0x00, 0x00, 0x00, 0x7e, 0x00, 0x00, 0x00, 0x00),
'.': (0x00, 0x00, 0x00, 0x00, 0x00, 0x18, 0x18, 0x00),
'/': (0x06, 0x0c, 0x18, 0x30, 0x60, 0xc0, 0x80, 0x00),
'0': (0x3c, 0x66, 0x6e, 0x76, 0x66, 0x66, 0x3c, 0x00),
'1': (0x18, 0x38, 0x18, 0x18, 0x18, 0x18, 0x7e, 0x00),
'2': (0x3c, 0x66, 0x06, 0x1c, 0x30, 0x60, 0x7e, 0x00),
'3': (0x3c, 0x66, 0x06, 0x1c, 0x06, 0x66, 0x3c, 0x00),
'4': (0x0c, 0x1c, 0x3c, 0x6c, 0x7e, 0x0c, 0x0c, 0x00),
'5': (0x7e, 0x60, 0x7c, 0x06, 0x06, 0x66, 0x3c, 0x00),
'6': (0x3c, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x3c, 0x00),
'7': (0x7e, 0x66, 0x06, 0x0c, 0x18, 0x18, 0x18, 0x00),
'8': (0x3c, 0x66, 0x66, 0x3c, 0x66, 0x66, 0x3c, 0x00),
'9': (0x3c, 0x66, 0x66, 0x3e, 0x06, 0x0c, 0x38, 0x00),
':': (0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x00, 0x00),
';': (0x00, 0x18, 0x18, 0x00, 0x18, 0x18, 0x30, 0x00),
'<': (0x0c, 0x18, 0x30, 0x60, 0x30, 0x18, 0x0c, 0x00),
'=': (0x00, 0x00, 0x7e, 0x00, 0x7e, 0x00, 0x00, 0x00),
'>': (0x30, 0x18, 0x0c, 0x06, 0x0c, 0x18, 0x30, 0x00),
'?': (0x3c, 0x66, 0x06, 0x0c, 0x18, 0x00, 0x18, 0x00),
'@': (0x3c, 0x66, 0x6e, 0x6e, 0x60, 0x62, 0x3c, 0x00),
'A': (0x18, 0x3c, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x00),
'B': (0x7c, 0x66, 0x66, 0x7c, 0x66, 0x66, 0x7c, 0x00),
'C': (0x3c, 0x66, 0x60, 0x60, 0x60, 0x66, 0x3c, 0x00),
'D': (0x78, 0x6c, 0x66, 0x66, 0x66, 0x6c, 0x78, 0x00),
'E': (0x7e, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x7e, 0x00),
'F': (0x7e, 0x60, 0x60, 0x7c, 0x60, 0x60, 0x60, 0x00),
'G': (0x3c, 0x66, 0x60, 0x6e, 0x66, 0x66, 0x3e, 0x00),
'H': (0x66, 0x66, 0x66, 0x7e, 0x66, 0x66, 0x66, 0x00),
'I': (0x3c, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00),
'J': (0x1e, 0x0c, 0x0c, 0x0c, 0x6c, 0x6c, 0x38, 0x00),
'K': (0x66, 0x6c, 0x78, 0x70, 0x78, 0x6c, 0x66, 0x00),
'L': (0x60, 0x60, 0x60, 0x60, 0x60, 0x60, 0x7e, 0x00),
'M': (0x63, 0x77, 0x7f, 0x6b, 0x63, 0x63, 0x63, 0x00),
'N': (0x66, 0x76, 0x7e, 0x7e, 0x6e, 0x66, 0x66, 0x00),
'O': (0x3c, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00),
'P': (0x7c, 0x66, 0x66, 0x7c, 0x60, 0x60, 0x60, 0x00),
'Q': (0x3c, 0x66, 0x66, 0x66, 0x6a, 0x6c, 0x36, 0x00),
'R': (0x7c, 0x66, 0x66, 0x7c, 0x6c, 0x66, 0x66, 0x00),
'S': (0x3c, 0x66, 0x60, 0x3c, 0x06, 0x66, 0x3c, 0x00),
'T': (0x7e, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00),
'U': (0x66, 0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x00),
'V': (0x66, 0x66, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x00),
'W': (0x63, 0x63, 0x63, 0x6b, 0x7f, 0x77, 0x63, 0x00),
'X': (0x66, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0x66, 0x00),
'Y': (0x66, 0x66, 0x66, 0x3c, 0x18, 0x18, 0x18, 0x00),
'Z': (0x7e, 0x06, 0x0c, 0x18, 0x30, 0x60, 0x7e, 0x00),
'[': (0x3c, 0x30, 0x30, 0x30, 0x30, 0x30, 0x3c, 0x00),
'\\': (0x80, 0xc0, 0x60, 0x30, 0x18, 0x0c, 0x06, 0x00),
']': (0x3c, 0x0c, 0x0c, 0x0c, 0x0c, 0x0c, 0x3c, 0x00),
'^': (0x18, 0x3c, 0x66, 0x00, 0x00, 0x00, 0x00, 0x00),
'_': (0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x00),
'`': (0x30, 0x18, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00),
'a': (0x00, 0x00, 0x3c, 0x06, 0x3e, 0x66, 0x3e, 0x00),
'b': (0x60, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x7c, 0x00),
'c': (0x00, 0x00, 0x3c, 0x66, 0x60, 0x66, 0x3c, 0x00),
'd': (0x06, 0x06, 0x3e, 0x66, 0x66, 0x66, 0x3e, 0x00),
'e': (0x00, 0x00, 0x3c, 0x66, 0x7e, 0x60, 0x3c, 0x00),
'f': (0x1c, 0x30, 0x7c, 0x30, 0x30, 0x30, 0x30, 0x00),
'g': (0x00, 0x00, 0x3e, 0x66, 0x66, 0x3e, 0x06, 0x3c),
'h': (0x60, 0x60, 0x7c, 0x66, 0x66, 0x66, 0x66, 0x00),
'i': (0x18, 0x00, 0x38, 0x18, 0x18, 0x18, 0x3c, 0x00),
'j': (0x0c, 0x00, 0x1c, 0x0c, 0x0c, 0x6c, 0x6c, 0x38),
'k': (0x60, 0x60, 0x66, 0x6c, 0x78, 0x6c, 0x66, 0x00),
'l': (0x38, 0x18, 0x18, 0x18, 0x18, 0x18, 0x3c, 0x00),
'm': (0x00, 0x00, 0x66, 0x7f, 0x7f, 0x6b, 0x63, 0x00),
'n': (0x00, 0x00, 0x7c, 0x66, 0x66, 0x66, 0x66, 0x00),
'o': (0x00, 0x00, 0x3c, 0x66, 0x66, 0x66, 0x3c, 0x00),
'p': (0x00, 0x00, 0x7c, 0x66, 0x66, 0x7c, 0x60, 0x60),
'q': (0x00, 0x00, 0x3e, 0x66, 0x66, 0x3e, 0x06, 0x06),
'r': (0x00, 0x00, 0x6c, 0x76, 0x60, 0x60, 0x60, 0x00),
's': (0x00, 0x00, 0x3e, 0x60, 0x3c, 0x06, 0x7c, 0x00),
't': (0x30, 0x30, 0x7c, 0x30, 0x30, 0x34, 0x18, 0x00),
'u': (0x00, 0x00, 0x66, 0x66, 0x66, 0x66, 0x3e, 0x00),
'v': (0x00, 0x00, 0x66, 0x66, 0x66, 0x3c, 0x18, 0x00),
'w': (0x00, 0x00, 0x63, 0x6b, 0x7f, 0x7f, 0x36, 0x00),
'x': (0x00, 0x00, 0x66, 0x3c, 0x18, 0x3c, 0x66, 0x00),
'y': (0x00, 0x00, 0x66, 0x66, 0x66, 0x3e, 0x06, 0x3c),
'z': (0x00, 0x00, 0x7e, 0x0c, 0x18, 0x30, 0x7e, 0x00),
'{': (0x0e, 0x18, 0x18, 0x70, 0x18, 0x18, 0x0e, 0x00),
'|': (0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x18, 0x00),
'}': (0x70, 0x18, 0x18, 0x0e, 0x18, 0x18, 0x70, 0x00),
'~': (0x3b, 0x6e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00),
}
_GLYPH_CACHE = {}
def _read_text(path):
try:
return Path(path).read_text().strip()
except OSError:
return None
def _read_int(path):
text = _read_text(path)
if text is None:
return None
try:
return int(text)
except ValueError:
return None
def _parse_active_bracket(raw):
if not raw:
return None
start = raw.find('[')
end = raw.find(']', start + 1)
if start != -1 and end != -1:
return raw[start + 1:end]
return raw.split()[0] if raw.split() else None
def _format_uptime(seconds):
total = int(seconds)
days, rem = divmod(total, 86400)
hours, rem = divmod(rem, 3600)
minutes, secs = divmod(rem, 60)
if days:
return f'{days}d {hours:02d}h {minutes:02d}m'
return f'{hours:02d}h {minutes:02d}m {secs:02d}s'
def collect_telemetry(sys_path='/sys', proc_path='/proc', run=subprocess.run):
"""Collect power, battery, cellular, network, and host load telemetry safely."""
sys_root = Path(sys_path)
proc_root = Path(proc_path)
uptime_raw = _read_text(proc_root / 'uptime')
uptime_s = 0.0
if uptime_raw:
try:
uptime_s = float(uptime_raw.split()[0])
except ValueError:
pass
load_raw = _read_text(proc_root / 'loadavg')
load_avg = ' '.join(load_raw.split()[:3]) if load_raw else 'n/a'
mem_total_kb = mem_avail_kb = None
mem_raw = _read_text(proc_root / 'meminfo')
if mem_raw:
for line in mem_raw.splitlines():
if line.startswith('MemTotal:'):
mem_total_kb = int(line.split()[1])
elif line.startswith('MemAvailable:'):
mem_avail_kb = int(line.split()[1])
mem_total_mb = (mem_total_kb // 1024) if mem_total_kb else None
mem_used_mb = ((mem_total_kb - mem_avail_kb) // 1024) if (mem_total_kb and mem_avail_kb is not None) else None
bat_dir = sys_root / 'class/power_supply/qcom-battery'
chg_dir = sys_root / 'class/power_supply/pm660-charger'
cap = _read_int(bat_dir / 'capacity')
bat_status = _read_text(bat_dir / 'status') or 'Unknown'
volt_uv = _read_int(bat_dir / 'voltage_now')
temp_deci = _read_int(bat_dir / 'temp')
chg_online = _read_text(chg_dir / 'online') == '1'
usb_type = _parse_active_bracket(_read_text(chg_dir / 'usb_type'))
charge_behaviour = _parse_active_bracket(_read_text(chg_dir / 'charge_behaviour'))
inhibited = charge_behaviour == 'inhibit-charge'
if inhibited and chg_online:
power_state = 'Paused (80% Guard)'
elif chg_online:
power_state = bat_status
else:
power_state = 'Discharging'
ipa_ready = _read_text(sys_root / 'devices/platform/soc@0/147c0000.ipa/modem/datapath_ready') == '1'
usb0_carrier = _read_text(sys_root / 'class/net/usb0/carrier') == '1'
cpu_max_mhz = []
cpufreq_dir = sys_root / 'devices/system/cpu/cpufreq'
if cpufreq_dir.exists():
for policy in sorted(cpufreq_dir.glob('policy*')):
freq_khz = _read_int(policy / 'scaling_max_freq')
if freq_khz:
cpu_max_mhz.append(freq_khz // 1000)
default_dev = None
iface_ips = {}
try:
r_def = run(['ip', '-4', 'route', 'show', 'default'],
capture_output=True, text=True, timeout=0.8)
if r_def.returncode == 0 and r_def.stdout.strip():
parts = r_def.stdout.splitlines()[0].split()
if 'dev' in parts:
default_dev = parts[parts.index('dev') + 1]
except (OSError, subprocess.SubprocessError):
pass
try:
r_addr = run(['ip', '-4', '-o', 'addr', 'show'],
capture_output=True, text=True, timeout=0.8)
if r_addr.returncode == 0:
for line in r_addr.stdout.splitlines():
cols = line.split()
if len(cols) >= 4 and cols[2] == 'inet':
iface_ips[cols[1]] = cols[3].split('/')[0]
except (OSError, subprocess.SubprocessError):
pass
cell_state = 'unregistered'
cell_operator = None
cell_tech = None
cell_signal = None
try:
r_mm = run(['mmcli', '-m', 'any', '-K'],
capture_output=True, text=True, timeout=0.8)
if r_mm.returncode == 0:
for line in r_mm.stdout.splitlines():
if ':' not in line:
continue
k, v = [p.strip() for p in line.split(':', 1)]
if v in ('--', ''):
continue
if k == 'modem.generic.state':
cell_state = v
elif k == 'modem.3gpp.operator-name':
cell_operator = v
elif k == 'modem.generic.access-technologies.value[1]':
cell_tech = v
elif k == 'modem.generic.signal-quality.value':
try:
cell_signal = int(v)
except ValueError:
pass
except (OSError, subprocess.SubprocessError):
pass
return {
'timestamp': time.strftime('%Y-%m-%d %H:%M:%S'),
'clock': time.strftime('%H:%M:%S'),
'date': time.strftime('%Y-%m-%d'),
'uptime_s': round(uptime_s, 1),
'uptime_str': _format_uptime(uptime_s),
'load_avg': load_avg,
'mem_used_mb': mem_used_mb,
'mem_total_mb': mem_total_mb,
'cpu_max_mhz': cpu_max_mhz,
'battery': {
'capacity': cap,
'status': bat_status,
'power_state': power_state,
'voltage_v': round(volt_uv / 1e6, 2) if volt_uv is not None else None,
'temp_c': round(temp_deci / 10.0, 1) if temp_deci is not None else None,
'charger_online': chg_online,
'usb_type': usb_type,
'inhibited': inhibited,
},
'cellular': {
'datapath_ready': ipa_ready,
'state': cell_state,
'operator': cell_operator,
'access_tech': cell_tech,
'signal_percent': cell_signal,
'ip': iface_ips.get('qmapmux0.0'),
'is_default': default_dev == 'qmapmux0.0',
},
'network': {
'default_dev': default_dev,
'wlan0_ip': iface_ips.get('wlan0'),
'usb0_ip': iface_ips.get('usb0'),
'usb0_carrier': usb0_carrier,
'tun0_ip': iface_ips.get('tun0'),
},
}
def _glyph_rows(ch, scale, fg_px, bg_px):
key = (ch, scale, fg_px, bg_px)
cached = _GLYPH_CACHE.get(key)
if cached is not None:
return cached
bits = FONT_8X8.get(ch, FONT_8X8[' '])
rows = []
for row_mask in bits:
row_bytes = bytearray()
for col in range(8):
px = fg_px if (row_mask & (0x80 >> col)) else bg_px
row_bytes.extend(px * scale)
immutable = bytes(row_bytes)
for _ in range(scale):
rows.append(immutable)
if len(_GLYPH_CACHE) > 2048:
_GLYPH_CACHE.clear()
_GLYPH_CACHE[key] = rows
return rows
def fill_rect(buf, width, height, x, y, w, h, color_px):
x0 = max(0, x)
y0 = max(0, y)
x1 = min(width, x + w)
y1 = min(height, y + h)
if x0 >= x1 or y0 >= y1:
return
row_bytes = color_px * (x1 - x0)
span = len(row_bytes)
stride = width * 4
for row in range(y0, y1):
start = row * stride + x0 * 4
buf[start:start + span] = row_bytes
def draw_rect_border(buf, width, height, x, y, w, h, border_px, thickness=2):
fill_rect(buf, width, height, x, y, w, thickness, border_px)
fill_rect(buf, width, height, x, y + h - thickness, w, thickness, border_px)
fill_rect(buf, width, height, x, y, thickness, h, border_px)
fill_rect(buf, width, height, x + w - thickness, y, thickness, h, border_px)
def draw_text(buf, width, height, x, y, text, scale=3, fg_px=COL_TEXT, bg_px=COL_CARD):
advance = 8 * scale
glyph_w = 8 * scale
stride = width * 4
cur_x = x
for raw_ch in str(text):
ch = raw_ch if raw_ch in FONT_8X8 else '?'
if cur_x + glyph_w > width:
break
if cur_x >= 0 and y >= 0 and y + glyph_w <= height:
rows = _glyph_rows(ch, scale, fg_px, bg_px)
for dy, row_bytes in enumerate(rows):
start = (y + dy) * stride + cur_x * 4
buf[start:start + len(row_bytes)] = row_bytes
cur_x += advance
def draw_progress_bar(buf, width, height, x, y, w, h, percent, fill_px, bg_px=COL_BAR_BG, border_px=COL_BORDER):
fill_rect(buf, width, height, x, y, w, h, bg_px)
draw_rect_border(buf, width, height, x, y, w, h, border_px, thickness=2)
pct = max(0, min(100, int(percent or 0)))
inner_w = max(0, (w - 8) * pct // 100)
if inner_w > 0:
fill_rect(buf, width, height, x + 4, y + 4, inner_w, h - 8, fill_px)
def draw_signal_bars(buf, width, height, x, y, percent):
filled = 0 if percent is None else max(1, min(4, (percent + 24) // 25))
bar_heights = (14, 22, 30, 38)
for idx, bh in enumerate(bar_heights):
bx = x + idx * 14
by = y + 38 - bh
color = COL_GREEN if idx < filled else COL_BAR_BG
fill_rect(buf, width, height, bx, by, 10, bh, color)
def render_dashboard_bgrx(telemetry, mode='status', width=1080, height=2280):
"""Render telemetry into a BGRX8888 bytearray matching 1080x2280 display."""
buf = bytearray(COL_BG * (width * height))
bat = telemetry['battery']
cap = bat.get('capacity')
volt = bat.get('voltage_v')
temp = bat.get('temp_c')
volt_str = f'{volt:.2f}V' if volt is not None else 'n/a'
temp_str = f'{temp:.1f}C' if temp is not None else 'n/a'
cap_str = f'{cap}%' if cap is not None else '--%'
bat_color = COL_GREEN if (cap or 0) >= 35 else (COL_AMBER if (cap or 0) >= 15 else COL_RED)
if mode == 'charger':
draw_text(buf, width, height, 72, 110, 'PLATINA LINUX CHARGER', scale=4, fg_px=COL_ACCENT, bg_px=COL_BG)
draw_text(buf, width, height, 72, 175, f"{telemetry['date']} {telemetry['clock']}", scale=3, fg_px=COL_MUTED, bg_px=COL_BG)
# Centered battery icon + fill
bx, by, bw, bh = 310, 480, 460, 740
fill_rect(buf, width, height, bx + 150, by - 46, 160, 46, COL_BORDER)
fill_rect(buf, width, height, bx, by, bw, bh, COL_CARD)
draw_rect_border(buf, width, height, bx, by, bw, bh, COL_BORDER, thickness=8)
pct = max(0, min(100, int(cap or 0)))
fill_h = (bh - 32) * pct // 100
if fill_h > 0:
fill_rect(buf, width, height, bx + 16, by + bh - 16 - fill_h, bw - 32, fill_h, bat_color)
draw_text(buf, width, height, 340, 1290, cap_str.center(5), scale=10, fg_px=COL_TEXT, bg_px=COL_BG)
state_lbl = 'PAUSED AT 80% GUARD' if bat.get('inhibited') else ('CHARGING' if bat.get('charger_online') else 'DISCHARGING')
draw_text(buf, width, height, 180, 1430, state_lbl, scale=4, fg_px=bat_color, bg_px=COL_BG)
draw_text(buf, width, height, 180, 1510, f"VOLTAGE: {volt_str} TEMP: {temp_str}", scale=4, fg_px=COL_MUTED, bg_px=COL_BG)
draw_text(buf, width, height, 180, 1575, f"SUPPLY: {bat.get('usb_type') or 'USB'}", scale=3, fg_px=COL_MUTED, bg_px=COL_BG)
fill_rect(buf, width, height, 60, 2060, 960, 110, COL_CARD)
draw_rect_border(buf, width, height, 60, 2060, 960, 110, COL_BORDER, thickness=2)
draw_text(buf, width, height, 100, 2085, 'TAP POWER: SLEEP SCREEN', scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 100, 2125, 'HOLD POWER 3S: BOOT LINUX | UNPLUG: OFF', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
return buf
# Header card
draw_text(buf, width, height, 68, 90, telemetry['clock'], scale=8, fg_px=COL_TEXT, bg_px=COL_BG)
draw_text(buf, width, height, 68, 175, f"{telemetry['date']} UP {telemetry['uptime_str']}", scale=3, fg_px=COL_MUTED, bg_px=COL_BG)
draw_text(buf, width, height, 68, 222, 'PLATINA LINUX SERVER', scale=3, fg_px=COL_ACCENT, bg_px=COL_BG)
def card(cy, ch, title):
fill_rect(buf, width, height, 60, cy, 960, ch, COL_CARD)
draw_rect_border(buf, width, height, 60, cy, 960, ch, COL_BORDER, thickness=2)
draw_text(buf, width, height, 92, cy + 26, title, scale=3, fg_px=COL_ACCENT, bg_px=COL_CARD)
# Card 1: Battery & Power
card(310, 340, 'BATTERY & POWER')
draw_text(buf, width, height, 92, 382, cap_str, scale=7, fg_px=bat_color, bg_px=COL_CARD)
draw_text(buf, width, height, 340, 392, bat['power_state'], scale=4, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 340, 442, f"{volt_str} {temp_str} {bat.get('usb_type') or 'BATT'}", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_progress_bar(buf, width, height, 92, 515, 896, 44, cap or 0, bat_color)
draw_text(buf, width, height, 92, 585, 'GUARD: 50-80% SOC | 45C CUTOFF | 5% OFF', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
# Card 2: Cellular 4G
cell = telemetry['cellular']
card(690, 370, 'CELLULAR 4G (IPA V2.6L)')
draw_signal_bars(buf, width, height, 92, 760, cell.get('signal_percent'))
op = (cell.get('operator') or 'NO CARRIER')[:16]
tech = (cell.get('access_tech') or '--').upper()
sig_str = f"{cell['signal_percent']}%" if cell.get('signal_percent') is not None else '--%'
draw_text(buf, width, height, 175, 762, f"{op} {tech} {sig_str}", scale=4, fg_px=COL_TEXT, bg_px=COL_CARD)
def_tag = ' [DEFAULT]' if cell.get('is_default') else ''
draw_text(buf, width, height, 92, 845, f"STATE : {cell['state']}{def_tag}", scale=3, fg_px=COL_GREEN if cell.get('is_default') else COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 895, f"IPv4 : {cell.get('ip') or 'none'} (metric 700)", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 945, f"IPA : {'datapath ready' if cell.get('datapath_ready') else 'offline'}", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
# Card 3: Network & Mesh
net = telemetry['network']
card(1100, 380, 'NETWORK & MESH ROUTING')
draw_text(buf, width, height, 92, 1175, f"DEFAULT : {net.get('default_dev') or 'none'}", scale=4, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1245, f"WI-FI : {net.get('wlan0_ip') or 'disconnected'} (m 600)", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1295, f"USB NCM : {net.get('usb0_ip') or 'down'} ({'link' if net.get('usb0_carrier') else 'unplugged'})", scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1345, f"EASYTIER: {net.get('tun0_ip') or 'stopped'}", scale=3, fg_px=COL_GREEN if net.get('tun0_ip') else COL_MUTED, bg_px=COL_CARD)
# Card 4: Compute
card(1520, 270, 'SYSTEM RESOURCES')
ram_str = f"{telemetry['mem_used_mb']} / {telemetry['mem_total_mb']} MB" if telemetry.get('mem_total_mb') else 'n/a'
cpus = telemetry.get('cpu_max_mhz') or []
cpu_str = '/'.join(str(m) for m in cpus) + ' MHz' if cpus else 'n/a'
draw_text(buf, width, height, 92, 1600, f"CPU : {cpu_str} | LOAD {telemetry['load_avg']}", scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1655, f"RAM : {ram_str}", scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 1710, 'MODE : LIGHTWEIGHT SERVER (DVFS/CPUIDLE)', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
# Footer controls
fill_rect(buf, width, height, 60, 2020, 960, 140, COL_CARD)
draw_rect_border(buf, width, height, 60, 2020, 960, 140, COL_BORDER, thickness=2)
draw_text(buf, width, height, 92, 2050, 'TAP POWER : SLEEP SCREEN (AUTO 12S)', scale=3, fg_px=COL_TEXT, bg_px=COL_CARD)
draw_text(buf, width, height, 92, 2098, 'HOLD 3S : SHUTDOWN / CHARGER MODE', scale=3, fg_px=COL_MUTED, bg_px=COL_CARD)
return buf
def _validate_panel():
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
raise ValueError('This command requires Platina')
if DRIVER.resolve(strict=True).name != 'panel-novatek-nt36672a':
raise ValueError('Integrated Tianma driver required')
compatible = (DRIVER.parent / 'of_node/compatible').read_bytes().split(b'\0')
if PANEL not in compatible:
raise ValueError('Unexpected panel variant')
if Path('/sys/module/platina_panel_dcs').exists():
raise ValueError('Temporary LCD module loaded; refusing display write')
def _fb_geometry(variable, fixed):
v = struct.unpack_from('=40I', variable)
memory = struct.unpack_from('=I', fixed, 24)[0]
stride = struct.unpack_from('=I', fixed, 48)[0]
width, height, virtual_width, virtual_height, xoff, yoff, bpp = v[:7]
if (width, height, bpp) != (1080, 2280, 32):
raise ValueError('Framebuffer resolution/pixel depth mismatch')
if xoff + width > virtual_width or yoff + height > virtual_height:
raise ValueError('Framebuffer viewport exceeds virtual dimensions')
if stride < (xoff + width) * 4 or not 0 < memory <= 64_000_000:
raise ValueError('Invalid framebuffer memory layout')
offset = yoff * stride + xoff * 4
if offset + (height - 1) * stride + width * 4 > memory:
raise ValueError('Framebuffer viewport exceeds mapped memory')
return width, height, stride, offset, memory
def _fb_paint(target, raw, layout):
width, height, stride, offset, _ = layout
row = width * 4
for y in range(height):
start = offset + y * stride
target[start:start + row] = raw[y * row:(y + 1) * row]
def _set_brightness(percent):
pct = max(0, min(100, int(percent)))
maximum = int((BACKLIGHT / 'max_brightness').read_text())
level = max(1, maximum * pct // 100) if pct else 0
(BACKLIGHT / 'brightness').write_text(str(level) + '\n')
class StatusDisplaySession:
"""Exclusive owner of /dev/fb0 while a temporary status/charger screen is illuminated."""
def __init__(self, brightness=25, mode='status'):
if os.geteuid() != 0:
raise ValueError('Run display changes on the phone as root')
_validate_panel()
self.brightness = brightness
self.mode = mode
self._lock_fh = None
self._fb = None
self._tty = None
self._prev_kd = None
self._mmap = None
self._layout = None
self._closed = True
def open(self, telemetry=None, mode=None):
if mode is not None:
self.mode = mode
lock_fh = SPLASH_LOCK.open('a')
try:
fcntl.flock(lock_fh, fcntl.LOCK_EX | fcntl.LOCK_NB)
fb = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
try:
var, fixed = bytearray(160), bytearray(80)
fcntl.ioctl(fb, 0x4600, var, True)
fcntl.ioctl(fb, 0x4602, fixed, True)
layout = _fb_geometry(var, fixed)
tty = os.open('/dev/tty0', os.O_RDWR | os.O_CLOEXEC)
kd = bytearray(4)
fcntl.ioctl(tty, 0x4B3B, kd, True)
prev_kd = struct.unpack('=i', kd)[0]
fcntl.ioctl(tty, 0x4B3A, 1) # KD_GRAPHICS
screen = mmap.mmap(fb, layout[4], access=mmap.ACCESS_WRITE)
except BaseException:
os.close(fb)
raise
except BaseException:
lock_fh.close()
raise
self._lock_fh = lock_fh
self._fb = fb
self._tty = tty
self._prev_kd = prev_kd
self._mmap = screen
self._layout = layout
self._closed = False
try:
_set_brightness(0)
self.refresh(telemetry=telemetry, mode=self.mode)
fcntl.ioctl(fb, FBIOBLANK, 0)
(BACKLIGHT / 'bl_power').write_text('0\n')
_set_brightness(self.brightness)
except BaseException:
self.close()
raise
def refresh(self, telemetry=None, mode=None):
if self._closed:
return
active_mode = mode or self.mode
data = telemetry or collect_telemetry()
raw = render_dashboard_bgrx(data, mode=active_mode,
width=self._layout[0], height=self._layout[1])
_fb_paint(self._mmap, raw, self._layout)
def close(self):
if self._closed and self._fb is None and self._lock_fh is None:
return
self._closed = True
try:
try:
_set_brightness(0)
except OSError:
pass
if self._mmap is not None:
try:
self._mmap[:] = b'\0' * self._layout[4]
except OSError:
pass
try:
self._mmap.close()
except OSError:
pass
self._mmap = None
if self._tty is not None:
try:
if self._prev_kd is not None:
fcntl.ioctl(self._tty, 0x4B3A, self._prev_kd)
except OSError:
pass
try:
os.close(self._tty)
except OSError:
pass
self._tty = None
if self._fb is not None:
try:
fcntl.ioctl(self._fb, FBIOBLANK, 4) # FB_BLANK_POWERDOWN
except OSError:
pass
try:
os.close(self._fb)
except OSError:
pass
self._fb = None
try:
if _read_text('/sys/class/graphics/fb0/blank') != '4':
fb2 = os.open('/dev/fb0', os.O_RDWR | os.O_CLOEXEC)
try:
fcntl.ioctl(fb2, FBIOBLANK, 4)
finally:
os.close(fb2)
except OSError:
pass
finally:
if self._lock_fh is not None:
try:
self._lock_fh.close()
except OSError:
pass
self._lock_fh = None
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--once', action='store_true', help='Display dashboard for --seconds then power off panel')
parser.add_argument('--mode', choices=('status', 'charger'), default='status')
parser.add_argument('--seconds', type=float, default=12.0)
parser.add_argument('--brightness', type=int, default=25)
parser.add_argument('--json', action='store_true', help='Print collected telemetry as JSON without touching display')
args = parser.parse_args()
if args.json:
print(json.dumps(collect_telemetry(), indent=2))
return 0
if not 0 < args.seconds <= 300:
parser.error('Choose --seconds between 0 and 300')
if not 1 <= args.brightness <= 100:
parser.error('Choose --brightness between 1 and 100')
signal.signal(signal.SIGTERM, lambda *_: sys.exit(143))
session = StatusDisplaySession(brightness=args.brightness, mode=args.mode)
session.open()
try:
deadline = time.monotonic() + args.seconds
while True:
remaining = deadline - time.monotonic()
if remaining <= 0:
break
time.sleep(min(2.0, remaining))
if time.monotonic() < deadline:
session.refresh()
finally:
session.close()
return 0
if __name__ == '__main__':
raise SystemExit(main())