feat(cellular, power): enable SDM660 IPA v2.6L 4G LTE, power-key status screen, and DVFS standby
Offline project checks / check (push) Canceled after 0s
Offline project checks / check (push) Canceled after 0s
This commit is contained in:
@@ -5,11 +5,18 @@
|
||||
set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
RELEASE_DIR="$SCRIPT_DIR/artifacts/release-v0.8.1-bulletproof"
|
||||
RELEASE_DIR="$SCRIPT_DIR/artifacts/release-v0.8.2-cellular"
|
||||
ARCHIVE="$SCRIPT_DIR/release/platina-linux-v0.8.2-cellular-release.tar.xz"
|
||||
|
||||
if [[ ! -d "$RELEASE_DIR" ]]; then
|
||||
echo "ERROR: Release directory '$RELEASE_DIR' not found!"
|
||||
exit 1
|
||||
if [[ ! -f "$RELEASE_DIR/flash.sh" ]]; then
|
||||
if [[ -f "$ARCHIVE" ]]; then
|
||||
echo "Extracting $ARCHIVE into $RELEASE_DIR ..."
|
||||
mkdir -p "$RELEASE_DIR"
|
||||
tar -xJf "$ARCHIVE" -C "$RELEASE_DIR"
|
||||
else
|
||||
echo "ERROR: Release directory '$RELEASE_DIR' and archive '$ARCHIVE' not found!"
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
exec "$RELEASE_DIR/flash.sh" "$@"
|
||||
|
||||
@@ -18,6 +18,7 @@ HELPERS = {
|
||||
'scripts/phone-splash.py': 'usr/local/sbin/platina-splash',
|
||||
'scripts/phone-display.py': 'usr/local/sbin/platina-display',
|
||||
'scripts/phone-display-session.py': 'usr/local/sbin/platina-display-session',
|
||||
'scripts/phone-status-screen.py': 'usr/local/sbin/platina-status-screen',
|
||||
'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',
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Generate a temporary AP DMA test overlay from this boot's live device tree.
|
||||
|
||||
No DT change, module loading or compilation is performed by this program.
|
||||
The generated phandles are valid only for the inspected tree/boot.
|
||||
"""
|
||||
|
||||
import argparse
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import sys
|
||||
|
||||
|
||||
def cells(path):
|
||||
data = path.read_bytes()
|
||||
if not data or len(data) % 4:
|
||||
raise ValueError(f"invalid cells: {path}")
|
||||
return struct.unpack(f">{len(data) // 4}I", data)
|
||||
|
||||
|
||||
def generate(root):
|
||||
if b"xiaomi,platina" not in (root / "compatible").read_bytes().split(b"\0"):
|
||||
raise ValueError("the device is not xiaomi,platina")
|
||||
soc = root / "soc@0"
|
||||
if cells(soc / "#address-cells") != (1,) or cells(soc / "#size-cells") != (1,):
|
||||
raise ValueError("unsupported SoC address/size cells")
|
||||
providers = {}
|
||||
for prop in root.rglob("phandle"):
|
||||
value, = cells(prop)
|
||||
if not value or value in providers:
|
||||
raise ValueError("invalid or duplicate phandle")
|
||||
providers[value] = prop.parent
|
||||
smmu = soc / "iommu@16c0000"
|
||||
if b"qcom,smmu-v2" not in (smmu / "compatible").read_bytes().split(b"\0"):
|
||||
raise ValueError("ANOC2 SMMU is not the expected controller")
|
||||
if cells(smmu / "#iommu-cells") != (1,):
|
||||
raise ValueError("unsupported ANOC2 IOMMU argument layout")
|
||||
smmu_id, = cells(smmu / "phandle")
|
||||
for prop in root.rglob("iommus"):
|
||||
values = cells(prop)
|
||||
offset = 0
|
||||
while offset < len(values):
|
||||
provider = providers.get(values[offset])
|
||||
if provider is None:
|
||||
raise ValueError(f"unresolved IOMMU provider: {prop}")
|
||||
nargs, = cells(provider / "#iommu-cells")
|
||||
if nargs < 1 or offset + nargs >= len(values):
|
||||
raise ValueError(f"invalid IOMMU arguments: {prop}")
|
||||
if provider == smmu and values[offset + 1] == 0x19C0:
|
||||
raise ValueError(f"AP stream 0x19c0 already declared: {prop.parent}")
|
||||
offset += nargs + 1
|
||||
ipa_nodes = [p.parent for p in soc.glob("*/compatible")
|
||||
if b"qcom,sdm660-ipa" in p.read_bytes().split(b"\0")]
|
||||
if len(ipa_nodes) != 1:
|
||||
raise ValueError("expected exactly one original IPA node")
|
||||
ipa = ipa_nodes[0]
|
||||
if (ipa / "clock-names").read_bytes() != b"core\0":
|
||||
raise ValueError("unsupported IPA clocks")
|
||||
clock = cells(ipa / "clocks")
|
||||
if len(clock) != 2 or clock[1] != 0x44:
|
||||
raise ValueError("expected RPM IPA core clock 0x44")
|
||||
if clock[0] not in providers or cells(providers[clock[0]] / "#clock-cells") != (1,):
|
||||
raise ValueError("invalid IPA clock provider")
|
||||
if (soc / "platina-ipa-dma-test@147c0000").exists():
|
||||
raise ValueError("the temporary test node already exists")
|
||||
return f'''/dts-v1/;
|
||||
/plugin/;
|
||||
|
||||
/* Generated from the inspected live DT. Do not reuse across different DTBs. */
|
||||
/ {{
|
||||
fragment@0 {{
|
||||
target-path = "/soc@0";
|
||||
__overlay__ {{
|
||||
platina-ipa-dma-test@147c0000 {{
|
||||
compatible = "xiaomi,platina-ipa-v2-dma-test";
|
||||
reg = <0x147c0000 0x1000>, <0x14784000 0x26934>;
|
||||
reg-names = "ipa", "bam";
|
||||
iommus = <0x{smmu_id:x} 0x19c0>;
|
||||
clocks = <0x{clock[0]:x} 0x44>;
|
||||
clock-names = "core";
|
||||
status = "okay";
|
||||
}};
|
||||
}};
|
||||
}};
|
||||
}};
|
||||
'''
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--dt-root", type=Path, default=Path("/sys/firmware/devicetree/base"))
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
sys.stdout.write(generate(args.dt_root))
|
||||
except (OSError, ValueError, struct.error) as error:
|
||||
parser.exit(1, f"overlay generation refused: {error}\n")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -27,6 +27,71 @@ import time
|
||||
import tty
|
||||
|
||||
|
||||
class PPPFrameStats:
|
||||
"""Count validated async PPP frames without retaining packet contents."""
|
||||
|
||||
def __init__(self):
|
||||
self.frame = None
|
||||
self.escaped = False
|
||||
self.protocols = {}
|
||||
self.invalid_fcs = 0
|
||||
self.oversized = 0
|
||||
self.ipv4_bytes = 0
|
||||
|
||||
@staticmethod
|
||||
def fcs(data):
|
||||
value = 0xffff
|
||||
for byte in data:
|
||||
value ^= byte
|
||||
for _ in range(8):
|
||||
value = (value >> 1) ^ (0x8408 if value & 1 else 0)
|
||||
return value
|
||||
|
||||
def feed(self, data):
|
||||
for byte in data:
|
||||
if byte == 0x7e:
|
||||
if self.frame and not self.escaped:
|
||||
self.record(bytes(self.frame))
|
||||
self.frame = bytearray()
|
||||
self.escaped = False
|
||||
elif self.frame is not None:
|
||||
if self.escaped:
|
||||
self.frame.append(byte ^ 0x20)
|
||||
self.escaped = False
|
||||
elif byte == 0x7d:
|
||||
self.escaped = True
|
||||
else:
|
||||
self.frame.append(byte)
|
||||
if len(self.frame) > 65536:
|
||||
self.oversized += 1
|
||||
self.frame = None
|
||||
self.escaped = False
|
||||
|
||||
def record(self, frame):
|
||||
if len(frame) < 3 or self.fcs(frame) != 0xf0b8:
|
||||
self.invalid_fcs += 1
|
||||
return
|
||||
payload = frame[:-2]
|
||||
if payload.startswith(b'\xff\x03'):
|
||||
payload = payload[2:]
|
||||
if not payload:
|
||||
return
|
||||
size = 1 if payload[0] & 1 else 2
|
||||
if len(payload) < size:
|
||||
return
|
||||
protocol = int.from_bytes(payload[:size], 'big')
|
||||
name = {0x21: 'ipv4', 0x57: 'ipv6', 0xc021: 'lcp',
|
||||
0x8021: 'ipcp', 0xc023: 'pap', 0xc223: 'chap'}.get(
|
||||
protocol, f'0x{protocol:04x}')
|
||||
self.protocols[name] = self.protocols.get(name, 0) + 1
|
||||
if protocol == 0x21:
|
||||
self.ipv4_bytes += len(payload) - size
|
||||
|
||||
def summary(self):
|
||||
return {'protocol_frames': dict(self.protocols), 'ipv4_bytes': self.ipv4_bytes,
|
||||
'invalid_fcs': self.invalid_fcs, 'oversized_frames': self.oversized}
|
||||
|
||||
|
||||
@contextmanager
|
||||
def exclusive_session(path='/run/lock/platina-cellular-rpmsg.lock'):
|
||||
fd = os.open(path, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600)
|
||||
@@ -142,6 +207,7 @@ def query(fd, timeout=5):
|
||||
results = []
|
||||
for command in ('AT', 'AT+CFUN?', 'AT+CPIN?', 'AT+CSQ', 'AT+COPS?',
|
||||
'AT+CEREG?', 'AT+CGREG?', 'AT+CGATT?', 'AT+CGDCONT?',
|
||||
'AT+CGACT?', 'AT+CGPADDR', 'AT+CGCONTRDP',
|
||||
'AT+CGDATA=?', 'AT+CEER'):
|
||||
result = at_command(fd, command, timeout)
|
||||
result.pop('trailing')
|
||||
@@ -170,6 +236,52 @@ def interface_ipv4(interface):
|
||||
return None
|
||||
|
||||
|
||||
def stop_ppp(proc, fd, master, timeout=5):
|
||||
"""Keep the transport alive while pppd sends its termination handshake."""
|
||||
if proc.poll() is not None:
|
||||
return
|
||||
proc.terminate()
|
||||
deadline = time.monotonic() + timeout
|
||||
pending = bytearray()
|
||||
try:
|
||||
while proc.poll() is None and time.monotonic() < deadline:
|
||||
readable, writable, _ = select.select(
|
||||
[fd, master], [master] if pending else [], [],
|
||||
min(0.1, max(0, deadline - time.monotonic())))
|
||||
if master in writable:
|
||||
try:
|
||||
count = os.write(master, pending)
|
||||
del pending[:count]
|
||||
except BlockingIOError:
|
||||
pass
|
||||
if fd in readable:
|
||||
try:
|
||||
data = os.read(fd, 65536)
|
||||
except BlockingIOError:
|
||||
data = None
|
||||
if data == b'':
|
||||
break
|
||||
if data:
|
||||
pending.extend(data)
|
||||
if len(pending) > 1024 * 1024:
|
||||
break
|
||||
if master in readable:
|
||||
try:
|
||||
data = os.read(master, 1024)
|
||||
except BlockingIOError:
|
||||
continue
|
||||
if data:
|
||||
send_message(fd, data)
|
||||
except (OSError, RuntimeError):
|
||||
# Remote modem teardown can remove the endpoint before pppd exits.
|
||||
# Process cleanup must still finish, and must not hide the main error.
|
||||
pass
|
||||
finally:
|
||||
if proc.poll() is None:
|
||||
proc.kill()
|
||||
proc.wait(timeout=5)
|
||||
|
||||
|
||||
def probe_dns(interface, target):
|
||||
"""Query a public resolver over a socket explicitly bound to the PPP device."""
|
||||
transaction = os.urandom(2)
|
||||
@@ -278,6 +390,8 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
|
||||
local_ip = None
|
||||
verification = None
|
||||
tx_bytes = rx_bytes = 0
|
||||
tx_frames, rx_frames = PPPFrameStats(), PPPFrameStats()
|
||||
rx_frames.feed(trailing)
|
||||
try:
|
||||
tty.setraw(slave)
|
||||
os.set_blocking(master, False)
|
||||
@@ -326,6 +440,7 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
|
||||
if data:
|
||||
to_pty.extend(data)
|
||||
rx_bytes += len(data)
|
||||
rx_frames.feed(data)
|
||||
if len(to_pty) > 1024 * 1024:
|
||||
raise RuntimeError('PPP receive queue exceeded 1 MiB')
|
||||
if master in readable:
|
||||
@@ -340,9 +455,11 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
|
||||
if data:
|
||||
send_message(fd, data)
|
||||
tx_bytes += len(data)
|
||||
tx_frames.feed(data)
|
||||
return {'interface': interface, 'local_ip': local_ip,
|
||||
'bridge_tx_bytes': tx_bytes,
|
||||
'bridge_rx_bytes': rx_bytes, 'pppd_exit': proc.poll(),
|
||||
'ppp_frames': {'tx': tx_frames.summary(), 'rx': rx_frames.summary()},
|
||||
'verification': verification,
|
||||
'ip_connectivity': bool(verification and verification['exit_code'] == 0)}
|
||||
finally:
|
||||
@@ -358,12 +475,7 @@ def connect(fd, apn, interface='ppp0', duration=120, timeout=30, dial_method='at
|
||||
if dns_pool is not None:
|
||||
dns_pool.shutdown(wait=True, cancel_futures=True)
|
||||
if proc is not None and proc.poll() is None:
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=5)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait()
|
||||
stop_ppp(proc, fd, master)
|
||||
os.close(master)
|
||||
os.close(slave)
|
||||
|
||||
|
||||
@@ -102,11 +102,10 @@ def parse_mmcli_modem_info(raw_text):
|
||||
|
||||
|
||||
def cellular_datapath_status(sys_path='/sys'):
|
||||
"""Inspect transport backing; a driver binding or interface name is insufficient.
|
||||
"""Inspect cellular hardware transport readiness under sysfs.
|
||||
|
||||
The current IPA v2.6 shim has no BAM TX/RX implementation. Reject it even
|
||||
when it exposes rmnet_ipa0. A future real backend must explicitly expose
|
||||
modem/datapath_ready=1 before this integration permits activation.
|
||||
Legacy IPA v2.6L hardware must expose modem/datapath_ready=1 before
|
||||
NetworkManager activation is permitted.
|
||||
"""
|
||||
root = Path(sys_path)
|
||||
rows = []
|
||||
@@ -133,8 +132,10 @@ def cellular_datapath_status(sys_path='/sys'):
|
||||
compatible = read(device / 'of_node/compatible').split('\0')
|
||||
legacy = (version.startswith('2.') or
|
||||
any(value in ('qcom,sdm660-ipa', 'qcom,ipa-v2.6') for value in compatible))
|
||||
if legacy and read(device / 'modem/datapath_ready') != '1':
|
||||
return False, 'IPA v2.6 shim: BAM TX/RX not implemented'
|
||||
if legacy:
|
||||
if read(device / 'modem/datapath_ready') != '1':
|
||||
return False, 'IPA v2.6 shim: BAM TX/RX not implemented'
|
||||
return True, 'bound hardware transport (datapath_ready=1)'
|
||||
return True, 'bound hardware transport (IP connectivity unverified)'
|
||||
|
||||
for iface in sorted((root / 'class/net').glob('*')):
|
||||
@@ -260,6 +261,7 @@ def build_nmcli_setup_commands(con_name=CONNECTION_NAME, apn='cmnet', ifname='*'
|
||||
'gsm.apn', apn,
|
||||
'gsm.auto-config', 'yes',
|
||||
'connection.autoconnect', 'no',
|
||||
'ipv4.route-metric', '700',
|
||||
'connection.interface-name', ifname if ifname != '*' else ''])
|
||||
else:
|
||||
cmd = ['nmcli', 'connection', 'add',
|
||||
@@ -268,7 +270,8 @@ def build_nmcli_setup_commands(con_name=CONNECTION_NAME, apn='cmnet', ifname='*'
|
||||
'ifname', ifname,
|
||||
'apn', apn,
|
||||
'gsm.auto-config', 'yes',
|
||||
'connection.autoconnect', 'no']
|
||||
'connection.autoconnect', 'no',
|
||||
'ipv4.route-metric', '700']
|
||||
commands.append(cmd)
|
||||
return commands
|
||||
|
||||
@@ -423,10 +426,6 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
|
||||
"""
|
||||
logger("Starting Platina cellular auto-connect...")
|
||||
|
||||
if not datapath_checker():
|
||||
logger("No hardware IPA or rmnet cellular data path detected in kernel; dialing skipped to maintain modem and Wi-Fi stability.")
|
||||
return False
|
||||
|
||||
attempts = 0
|
||||
last_operator = None
|
||||
last_state = None
|
||||
@@ -438,6 +437,15 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
|
||||
logger(f"Reached maximum attempts ({max_attempts}), stopping.")
|
||||
return False
|
||||
|
||||
if not datapath_checker():
|
||||
if last_state != 'no_datapath':
|
||||
logger("No hardware IPA or rmnet cellular data path detected in kernel; dialing skipped to maintain modem and Wi-Fi stability.")
|
||||
last_state = 'no_datapath'
|
||||
if not daemon:
|
||||
return False
|
||||
sleeper(poll_interval)
|
||||
continue
|
||||
|
||||
# Battery gate check: do not allow RF transmit if battery voltage/capacity is low
|
||||
bat_ok, bat_msg = battery_checker()
|
||||
if not bat_ok:
|
||||
@@ -492,6 +500,15 @@ def run_auto_connect(daemon=False, poll_interval=10, max_attempts=None,
|
||||
sleeper(poll_interval)
|
||||
continue
|
||||
|
||||
if state in ('searching', 'initializing', 'enabling') and not operator_code:
|
||||
if daemon or (max_attempts is None or attempts < max_attempts):
|
||||
wait_key = f'waiting_{state}'
|
||||
if last_state != wait_key:
|
||||
logger(f"Modem state is {state} without operator PLMN; waiting for registration...")
|
||||
last_state = wait_key
|
||||
sleeper(poll_interval)
|
||||
continue
|
||||
|
||||
# Determine APN for current operator
|
||||
apn = detect_apn_for_operator(
|
||||
operator_code,
|
||||
|
||||
+49
-12
@@ -6,25 +6,66 @@ depend() {
|
||||
before networkmanager
|
||||
}
|
||||
|
||||
ipa_bringup_mode() {
|
||||
case " $(cat "${1:-/proc/cmdline}" 2>/dev/null) " in
|
||||
*" platina.ipa_bringup=1 "*) return 0 ;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
start_remoteprocs() {
|
||||
local root="$1" hold_modem="$2" rproc
|
||||
for rproc in "$root"/remoteproc*; do
|
||||
if [ -d "$rproc" ] && [ -f "$rproc/state" ]; then
|
||||
if [ "$hold_modem" = 1 ] &&
|
||||
[ "$(cat "$rproc/name" 2>/dev/null)" = "4080000.remoteproc" ]; then
|
||||
continue
|
||||
fi
|
||||
if [ "$(cat "$rproc/state" 2>/dev/null)" = "offline" ]; then
|
||||
echo start > "$rproc/state" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
start() {
|
||||
local hold_modem=0
|
||||
if ipa_bringup_mode; then
|
||||
hold_modem=1
|
||||
fi
|
||||
ebegin "Initializing Platina DSP and WCN3990 Wi-Fi"
|
||||
# 1. Un-blacklist modem driver from initramfs disarm
|
||||
sed -i "/qcom_q6v5_mss/d" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null
|
||||
if ! grep -q "blacklist ipa" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null; then
|
||||
echo -e "install ipa /bin/true\nblacklist ipa" > /etc/modprobe.d/modem-blacklist.conf
|
||||
# 1. Manage initramfs modem/IPA blacklists for normal vs early bringup mode
|
||||
sed -i "/qcom_q6v5_mss/d" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null || true
|
||||
if [ "$hold_modem" = 1 ]; then
|
||||
if ! grep -q "blacklist ipa" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null; then
|
||||
printf "install ipa /bin/true\nblacklist ipa\n" > /etc/modprobe.d/modem-blacklist.conf
|
||||
fi
|
||||
else
|
||||
sed -i "/ipa/d" /etc/modprobe.d/modem-blacklist.conf 2>/dev/null || true
|
||||
if [ -f /etc/modprobe.d/modem-blacklist.conf ] &&
|
||||
[ ! -s /etc/modprobe.d/modem-blacklist.conf ]; then
|
||||
rm -f /etc/modprobe.d/modem-blacklist.conf
|
||||
fi
|
||||
fi
|
||||
|
||||
# 2. Ensure kernel modules are loaded
|
||||
modprobe qcom_rmtfs_mem 2>/dev/null || true
|
||||
modprobe qcom_q6v5_pas 2>/dev/null || true
|
||||
modprobe qcom_q6v5_mss 2>/dev/null || true
|
||||
if [ "$hold_modem" = 0 ]; then
|
||||
modprobe ipa 2>/dev/null || true
|
||||
fi
|
||||
|
||||
# 3. Ensure tqftpserv and rmtfs daemons are running
|
||||
if ! pidof tqftpserv >/dev/null 2>&1; then
|
||||
rc-service tqftpserv restart 2>/dev/null || /usr/bin/tqftpserv &
|
||||
fi
|
||||
if ! pidof rmtfs >/dev/null 2>&1; then
|
||||
rc-service rmtfs restart 2>/dev/null || /usr/bin/rmtfs -s -P -r -v &
|
||||
if [ "$hold_modem" = 1 ]; then
|
||||
rc-service rmtfs restart 2>/dev/null || /usr/bin/rmtfs -P -r -v &
|
||||
else
|
||||
rc-service rmtfs restart 2>/dev/null || /usr/bin/rmtfs -s -P -r -v &
|
||||
fi
|
||||
fi
|
||||
|
||||
# Wait up to 3s for remoteproc nodes to register
|
||||
@@ -36,13 +77,7 @@ start() {
|
||||
done
|
||||
|
||||
# 4. Start any offline remoteproc instance (modem/ADSP/CDSP)
|
||||
for rproc in /sys/class/remoteproc/remoteproc*; do
|
||||
if [ -d "$rproc" ] && [ -f "$rproc/state" ]; then
|
||||
if [ "$(cat "$rproc/state" 2>/dev/null)" = "offline" ]; then
|
||||
echo start > "$rproc/state" 2>/dev/null || true
|
||||
fi
|
||||
fi
|
||||
done
|
||||
start_remoteprocs /sys/class/remoteproc "$hold_modem"
|
||||
|
||||
# 5. Ensure pd-mapper is running
|
||||
if ! pidof pd-mapper >/dev/null 2>&1; then
|
||||
@@ -50,6 +85,7 @@ start() {
|
||||
fi
|
||||
|
||||
# Wait for modem remoteproc to be running before probing ath10k
|
||||
if [ "$hold_modem" = 0 ]; then
|
||||
for i in 1 2 3 4 5; do
|
||||
for rproc in /sys/class/remoteproc/remoteproc*; do
|
||||
if [ -f "$rproc/name" ] && grep -q "4080000" "$rproc/name" 2>/dev/null; then
|
||||
@@ -60,6 +96,7 @@ start() {
|
||||
done
|
||||
sleep 1
|
||||
done
|
||||
fi
|
||||
|
||||
# 6. Load ath10k_snoc Wi-Fi driver cleanly
|
||||
if ! lsmod | grep -q ath10k_snoc; then
|
||||
|
||||
@@ -1,8 +1,27 @@
|
||||
#!/bin/sh
|
||||
# Always start dark. Display the installed release briefly in the background.
|
||||
# Always start dark. Display charger UI in charger boot mode, or release logo briefly.
|
||||
for path in /sys/class/backlight/*/brightness; do
|
||||
[ -w "$path" ] && printf '0\n' > "$path"
|
||||
done
|
||||
CMDLINE=$(cat /proc/cmdline 2>/dev/null || true)
|
||||
CHARGER_MODE=0
|
||||
case " $CMDLINE " in
|
||||
*" androidboot.mode=charger "*|*" androidboot.bootreason=usb_chg "*)
|
||||
CHARGER_MODE=1
|
||||
;;
|
||||
esac
|
||||
if [ "$CHARGER_MODE" = 1 ]; then
|
||||
if [ -x /usr/local/sbin/platina-status-screen ]; then
|
||||
umask 027
|
||||
(
|
||||
timeout -s TERM -k 3 10 /usr/local/sbin/platina-status-screen --once --mode charger --seconds 5 || true
|
||||
if [ -x /usr/local/sbin/platina-display ]; then
|
||||
/usr/local/sbin/platina-display off || true
|
||||
fi
|
||||
) >> /var/log/platina-splash.log 2>&1 &
|
||||
fi
|
||||
exit 0
|
||||
fi
|
||||
if [ -x /usr/local/sbin/platina-splash ] && [ -r /usr/local/share/platina/current/release.json ]; then
|
||||
umask 027
|
||||
(
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
# Physical Power + Volume Up only. PMIC emergency reset remains unchanged.
|
||||
# Physical Power button / chord policy. PMIC emergency reset remains unchanged.
|
||||
hold_seconds=3
|
||||
# Start in observation mode until the physical gesture has been checked.
|
||||
dry_run=yes
|
||||
power_key_mode=yes
|
||||
screen_seconds=12
|
||||
idle_suspend_seconds=60
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
#!/sbin/openrc-run
|
||||
description="Platina Power + Volume Up: hold together, release both to shut down"
|
||||
description="Platina Power button, status screen, offline charger & standby daemon"
|
||||
command="/usr/local/sbin/platina-power-chord"
|
||||
command_user="root:root"
|
||||
command_args="--hold-seconds ${hold_seconds:-3}"
|
||||
command_args="--hold-seconds ${hold_seconds:-3} --screen-seconds ${screen_seconds:-12} --idle-suspend-seconds ${idle_suspend_seconds:-60}"
|
||||
supervisor="supervise-daemon"
|
||||
pidfile="/run/platina-power-chord.pid"
|
||||
respawn_delay=5
|
||||
@@ -18,6 +18,9 @@ depend() {
|
||||
|
||||
start_pre() {
|
||||
checkpath --file --mode 0640 --owner root:root "$output_log"
|
||||
if yesno "${power_key_mode:-yes}"; then
|
||||
command_args="$command_args --power-key-mode"
|
||||
fi
|
||||
if yesno "${dry_run:-yes}"; then
|
||||
command_args="$command_args --dry-run"
|
||||
fi
|
||||
|
||||
+402
-19
@@ -1,15 +1,18 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Power + Volume Up, held together and fully released, requests orderly shutdown."""
|
||||
"""Physical Power button, status screen toggle, offline charger & standby daemon."""
|
||||
import argparse
|
||||
import errno
|
||||
import fcntl
|
||||
import os
|
||||
from pathlib import Path
|
||||
import runpy
|
||||
import select
|
||||
import signal
|
||||
import stat
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
KEY_POWER, KEY_VOLUMEUP = 116, 115
|
||||
KEYS = {KEY_POWER, KEY_VOLUMEUP}
|
||||
@@ -59,6 +62,138 @@ class ChordPolicy:
|
||||
return None
|
||||
|
||||
|
||||
class PowerButtonPolicy:
|
||||
"""Single Power short tap toggles screen; >= hold_seconds triggers long_power immediately."""
|
||||
|
||||
def __init__(self, hold_seconds=3.0, min_tap_seconds=0.02, held=()):
|
||||
if not 1 <= hold_seconds <= 5:
|
||||
raise ValueError('Choose a hold of 1 to 5 seconds, below the PMIC emergency reset')
|
||||
self.hold_seconds = float(hold_seconds)
|
||||
self.min_tap_seconds = float(min_tap_seconds)
|
||||
self.last = None
|
||||
self.resync(held)
|
||||
|
||||
def resync(self, held):
|
||||
self.pressed = set(held) & KEYS
|
||||
self.blocked = bool(self.pressed)
|
||||
self.power_started = None
|
||||
self.saw_volumeup = KEY_VOLUMEUP in self.pressed
|
||||
self.long_fired = False
|
||||
|
||||
def check_timeout(self, now):
|
||||
if (KEY_POWER in self.pressed and not self.blocked and not self.long_fired
|
||||
and self.power_started is not None and now - self.power_started >= self.hold_seconds):
|
||||
self.long_fired = True
|
||||
self.power_started = None
|
||||
return 'long_power'
|
||||
return None
|
||||
|
||||
def event(self, key, value, timestamp):
|
||||
if key not in KEYS or value not in (0, 1):
|
||||
return None
|
||||
if self.last is not None and timestamp < self.last:
|
||||
self.resync(self.pressed | {key})
|
||||
return None
|
||||
self.last = timestamp
|
||||
if value == 1:
|
||||
if key in self.pressed:
|
||||
return None
|
||||
self.pressed.add(key)
|
||||
if key == KEY_VOLUMEUP:
|
||||
self.saw_volumeup = True
|
||||
elif key == KEY_POWER and not self.blocked and not self.long_fired:
|
||||
self.power_started = timestamp
|
||||
return None
|
||||
if key not in self.pressed:
|
||||
return None
|
||||
action = None
|
||||
if key == KEY_POWER and self.power_started is not None and not self.blocked and not self.long_fired:
|
||||
duration = timestamp - self.power_started
|
||||
if duration >= self.hold_seconds:
|
||||
action = 'long_power'
|
||||
self.long_fired = True
|
||||
elif not self.saw_volumeup and duration >= self.min_tap_seconds:
|
||||
action = 'toggle_screen'
|
||||
self.power_started = None
|
||||
self.pressed.remove(key)
|
||||
if not self.pressed:
|
||||
self.resync(())
|
||||
return action
|
||||
|
||||
|
||||
def _read_text(path):
|
||||
try:
|
||||
return Path(path).read_text().strip()
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
|
||||
def is_boot_charger_mode(cmdline_path=Path('/proc/cmdline')):
|
||||
raw = _read_text(cmdline_path)
|
||||
if not raw:
|
||||
return False
|
||||
tokens = raw.split()
|
||||
return 'androidboot.mode=charger' in tokens or 'androidboot.bootreason=usb_chg' in tokens
|
||||
|
||||
|
||||
def is_external_power_online(sys_supply=Path('/sys/class/power_supply')):
|
||||
for name in ('pm660-charger', 'qpnp-smbcharger', 'usb', 'charger'):
|
||||
online = _read_text(Path(sys_supply) / name / 'online')
|
||||
if online in ('1', 'true'):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def has_active_ssh_session(proc_net=Path('/proc/net')):
|
||||
for name in ('tcp', 'tcp6'):
|
||||
raw = _read_text(Path(proc_net) / name)
|
||||
if not raw:
|
||||
continue
|
||||
for line in raw.splitlines()[1:]:
|
||||
cols = line.split()
|
||||
if len(cols) >= 4 and cols[3].upper() == '01' and cols[1].upper().endswith(':0016'):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def is_usb_data_host_connected(sys_root=Path('/sys')):
|
||||
sys_root = Path(sys_root)
|
||||
if _read_text(sys_root / 'class/net/usb0/carrier') != '1':
|
||||
return False
|
||||
usb_type = _read_text(sys_root / 'class/power_supply/pm660-charger/usb_type') or ''
|
||||
if '[DCP]' in usb_type:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def can_auto_suspend(screen_on, sys_root=Path('/sys'), proc_net=Path('/proc/net'),
|
||||
inhibit_path=Path('/run/platina-inhibit-suspend')):
|
||||
if screen_on:
|
||||
return False, 'screen on'
|
||||
if Path(inhibit_path).exists():
|
||||
return False, 'inhibit file'
|
||||
if is_usb_data_host_connected(sys_root):
|
||||
return False, 'usb data host'
|
||||
if has_active_ssh_session(proc_net):
|
||||
return False, 'active ssh session'
|
||||
return True, 'idle'
|
||||
|
||||
|
||||
def read_pwrkey_wakeup_count(sys_wakeup=Path('/sys/class/wakeup')):
|
||||
root = Path(sys_wakeup)
|
||||
if not root.exists():
|
||||
return 0
|
||||
for entry in root.glob('wakeup*'):
|
||||
name = _read_text(entry / 'name') or ''
|
||||
if ':pwrkey' in name:
|
||||
cnt = _read_text(entry / 'event_count')
|
||||
try:
|
||||
return int(cnt)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
return 0
|
||||
|
||||
|
||||
def find_devices(sys_input=Path('/sys/class/input'), dev_input=Path('/dev/input')):
|
||||
result = {}
|
||||
for key, name in DEVICES.items():
|
||||
@@ -96,12 +231,82 @@ def dispatch(dry_run):
|
||||
raise RuntimeError('Shutdown helper failed; exit ' + str(code))
|
||||
|
||||
|
||||
def monitor(seconds, dry_run):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError('Run on the phone as root')
|
||||
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
|
||||
raise ValueError('This service requires Platina')
|
||||
descriptors, dropped = {}, set()
|
||||
def _load_status_session_cls():
|
||||
helper = Path('/usr/local/sbin/platina-status-screen')
|
||||
if not helper.exists():
|
||||
return None
|
||||
mod = runpy.run_path(str(helper), run_name='status_screen')
|
||||
return mod.get('StatusDisplaySession')
|
||||
|
||||
|
||||
def set_cpu_standby(mode, cpufreq_root=Path('/sys/devices/system/cpu/cpufreq')):
|
||||
"""Clamp or restore per-cluster scaling_max_freq without using kernel s2idle."""
|
||||
if mode not in ('active', 'standby', 'charger'):
|
||||
raise ValueError('Unsupported CPU standby mode: ' + str(mode))
|
||||
root = Path(cpufreq_root)
|
||||
applied = {}
|
||||
if not root.exists():
|
||||
return applied
|
||||
for policy in sorted(root.glob('policy*')):
|
||||
max_txt = _read_text(policy / 'cpuinfo_max_freq')
|
||||
min_txt = _read_text(policy / 'scaling_min_freq')
|
||||
if not max_txt or not min_txt:
|
||||
continue
|
||||
try:
|
||||
cpu_max = int(max_txt)
|
||||
cpu_min = int(min_txt)
|
||||
except ValueError:
|
||||
continue
|
||||
if mode == 'active':
|
||||
target = cpu_max
|
||||
elif mode == 'charger':
|
||||
target = cpu_min
|
||||
else:
|
||||
if cpu_max >= 2_000_000:
|
||||
target = cpu_min
|
||||
else:
|
||||
avail_raw = _read_text(policy / 'scaling_available_frequencies')
|
||||
freqs = []
|
||||
if avail_raw:
|
||||
for tok in avail_raw.split():
|
||||
try:
|
||||
freqs.append(int(tok))
|
||||
except ValueError:
|
||||
pass
|
||||
under_cap = [f for f in freqs if f <= 633600]
|
||||
if under_cap:
|
||||
target = max(under_cap)
|
||||
elif freqs:
|
||||
target = min(freqs)
|
||||
else:
|
||||
target = min(cpu_max, max(cpu_min, 633600))
|
||||
try:
|
||||
(policy / 'scaling_max_freq').write_text(str(target) + '\n')
|
||||
applied[policy.name] = target
|
||||
except OSError:
|
||||
continue
|
||||
return applied
|
||||
|
||||
|
||||
def _select_timeout(now, policy, screen_on, screen_opened_at, last_refresh,
|
||||
screen_dur, charger_mode, idle_suspend_seconds,
|
||||
last_activity, standby_active):
|
||||
wait = 30.0
|
||||
if (KEY_POWER in policy.pressed and not policy.blocked and not policy.long_fired
|
||||
and policy.power_started is not None):
|
||||
wait = min(wait, max(0.02, policy.power_started + policy.hold_seconds - now))
|
||||
if screen_on:
|
||||
wait = min(wait, max(0.05, min(last_refresh + 2.0, screen_opened_at + screen_dur) - now))
|
||||
if charger_mode:
|
||||
wait = min(wait, 1.0)
|
||||
elif not screen_on and not standby_active and idle_suspend_seconds > 0:
|
||||
target = last_activity + idle_suspend_seconds
|
||||
wait = min(wait, max(0.2, min(10.0, target - now)))
|
||||
return max(0.02, wait)
|
||||
|
||||
|
||||
def _open_inputs():
|
||||
descriptors = {}
|
||||
try:
|
||||
for key, device in find_devices().items():
|
||||
fd = os.open(device, os.O_RDONLY | os.O_NONBLOCK | os.O_CLOEXEC)
|
||||
@@ -114,36 +319,207 @@ def monitor(seconds, dry_run):
|
||||
raise ValueError('Input identity changed')
|
||||
fcntl.ioctl(fd, 0x400445A0, struct.pack('i', 1)) # Monotonic timestamps.
|
||||
fcntl.ioctl(fd, 0x40044590, 1) # EVIOCGRAB; no console actions.
|
||||
def held():
|
||||
return {key for fd, key in descriptors.items() if key_held(fd, key)}
|
||||
policy = ChordPolicy(seconds, held())
|
||||
log(('TEST ONLY' if dry_run else 'ACTIVE') + f'; hold both >= {seconds:g}s; release BOTH to power off')
|
||||
except BaseException:
|
||||
for fd in descriptors:
|
||||
os.close(fd)
|
||||
raise
|
||||
return descriptors
|
||||
|
||||
|
||||
def monitor(seconds, dry_run, power_key_mode=False, screen_seconds=12.0, idle_suspend_seconds=60.0):
|
||||
if os.geteuid() != 0:
|
||||
raise ValueError('Run on the phone as root')
|
||||
if b'xiaomi,platina\0' not in Path('/proc/device-tree/compatible').read_bytes():
|
||||
raise ValueError('This service requires Platina')
|
||||
|
||||
descriptors = _open_inputs()
|
||||
dropped = set()
|
||||
session_cls = _load_status_session_cls() if power_key_mode else None
|
||||
display_session = None
|
||||
screen_on = False
|
||||
screen_opened_at = 0.0
|
||||
last_refresh = 0.0
|
||||
charger_mode = is_boot_charger_mode() if power_key_mode else False
|
||||
standby_active = False
|
||||
if charger_mode and not dry_run:
|
||||
set_cpu_standby('charger')
|
||||
standby_active = True
|
||||
prev_online = is_external_power_online()
|
||||
last_activity = time.monotonic()
|
||||
|
||||
def held():
|
||||
return {key for fd, key in descriptors.items() if key_held(fd, key)}
|
||||
|
||||
def close_screen(reason=None):
|
||||
nonlocal display_session, screen_on, last_activity
|
||||
if display_session is not None:
|
||||
try:
|
||||
display_session.close()
|
||||
except OSError as exc:
|
||||
log(f'display close error: {exc}')
|
||||
display_session = None
|
||||
if screen_on and reason:
|
||||
log(reason)
|
||||
screen_on = False
|
||||
last_activity = time.monotonic()
|
||||
|
||||
def open_screen(mode):
|
||||
nonlocal display_session, screen_on, screen_opened_at, last_refresh, last_activity, standby_active
|
||||
if session_cls is None:
|
||||
log('status screen helper missing; cannot illuminate display')
|
||||
return False
|
||||
if not charger_mode and standby_active:
|
||||
set_cpu_standby('active')
|
||||
standby_active = False
|
||||
if display_session is not None:
|
||||
return True
|
||||
try:
|
||||
sess = session_cls(brightness=25, mode=mode)
|
||||
sess.open()
|
||||
display_session = sess
|
||||
screen_on = True
|
||||
now_t = time.monotonic()
|
||||
screen_opened_at = now_t
|
||||
last_refresh = now_t
|
||||
last_activity = now_t
|
||||
return True
|
||||
except OSError as exc:
|
||||
log(f'display open skipped ({exc})')
|
||||
return False
|
||||
|
||||
def handle_action(action):
|
||||
nonlocal charger_mode, prev_online, standby_active
|
||||
if action == 'poweroff':
|
||||
log('complete chord accepted')
|
||||
dispatch(dry_run)
|
||||
elif action == 'toggle_screen':
|
||||
if screen_on:
|
||||
close_screen('toggle_screen -> OFF')
|
||||
else:
|
||||
mode = 'charger' if charger_mode else 'status'
|
||||
if open_screen(mode):
|
||||
log(f'toggle_screen -> ON ({mode})')
|
||||
elif action == 'long_power':
|
||||
close_screen()
|
||||
if charger_mode:
|
||||
log('long Power in charger mode -> booting normal cellular/server')
|
||||
charger_mode = False
|
||||
if not dry_run:
|
||||
set_cpu_standby('active')
|
||||
standby_active = False
|
||||
if Path('/usr/local/sbin/platina-cellular').exists():
|
||||
subprocess.Popen(['/usr/local/sbin/platina-cellular', '--auto'], start_new_session=True)
|
||||
open_screen('status')
|
||||
elif is_external_power_online():
|
||||
log('long Power with external power -> entering offline charger mode')
|
||||
charger_mode = True
|
||||
prev_online = True
|
||||
if not dry_run:
|
||||
set_cpu_standby('charger')
|
||||
standby_active = True
|
||||
if Path('/usr/local/sbin/platina-cellular').exists():
|
||||
subprocess.Popen(['/usr/local/sbin/platina-cellular', '--down'], start_new_session=True)
|
||||
open_screen('charger')
|
||||
else:
|
||||
log('long Power on battery -> shutting down')
|
||||
if dry_run:
|
||||
log('TEST ONLY: long Power accepted; would show Power off and shut down')
|
||||
else:
|
||||
set_cpu_standby('active')
|
||||
standby_active = False
|
||||
child = subprocess.Popen(['/usr/local/sbin/platina-poweroff', '--force'],
|
||||
start_new_session=True)
|
||||
code = child.wait()
|
||||
if code:
|
||||
raise RuntimeError('Shutdown helper failed; exit ' + str(code))
|
||||
|
||||
try:
|
||||
policy = (PowerButtonPolicy(seconds, held=held())
|
||||
if power_key_mode else ChordPolicy(seconds, held()))
|
||||
log(('TEST ONLY' if dry_run else 'ACTIVE')
|
||||
+ f'; power_key_mode={power_key_mode}; hold>={seconds:g}s; charger_mode={charger_mode}')
|
||||
while True:
|
||||
ready, _, _ = select.select(list(descriptors), [], [])
|
||||
screen_dur = 5.0 if charger_mode else float(screen_seconds)
|
||||
timeout = (_select_timeout(time.monotonic(), policy, screen_on, screen_opened_at,
|
||||
last_refresh, screen_dur, charger_mode,
|
||||
idle_suspend_seconds, last_activity, standby_active)
|
||||
if power_key_mode else None)
|
||||
try:
|
||||
ready, _, _ = select.select(list(descriptors), [], [], timeout)
|
||||
except InterruptedError:
|
||||
continue
|
||||
|
||||
events = []
|
||||
for fd in ready:
|
||||
data = os.read(fd, EVENT.size * 64)
|
||||
try:
|
||||
data = os.read(fd, EVENT.size * 64)
|
||||
except BlockingIOError:
|
||||
continue
|
||||
if not data or len(data) % EVENT.size:
|
||||
raise ValueError('Disconnected or truncated input')
|
||||
for offset in range(0, len(data), EVENT.size):
|
||||
sec, usec, typ, code, value = EVENT.unpack_from(data, offset)
|
||||
events.append((sec + usec / 1e6, fd, typ, code, value))
|
||||
|
||||
for timestamp, fd, typ, code, value in sorted(events):
|
||||
if typ == 0 and code == 3: # SYN_DROPPED: cancel both keys.
|
||||
if typ == 0 and code == 3: # SYN_DROPPED: cancel pending keys.
|
||||
dropped.add(fd)
|
||||
policy.resync(KEYS)
|
||||
log('lost input events; pending chord cancelled')
|
||||
log('lost input events; pending gesture cancelled')
|
||||
elif typ == 0 and code == 0 and fd in dropped:
|
||||
dropped.remove(fd)
|
||||
policy.resync(held())
|
||||
elif typ == 1 and code == descriptors[fd] and not dropped:
|
||||
action = policy.event(code, value, timestamp)
|
||||
if value in (0, 1):
|
||||
last_activity = time.monotonic()
|
||||
log(DEVICES[code] + (' pressed' if value else ' released'))
|
||||
action = policy.event(code, value, timestamp)
|
||||
if action:
|
||||
log('complete chord accepted')
|
||||
dispatch(dry_run)
|
||||
handle_action(action)
|
||||
|
||||
if not power_key_mode:
|
||||
continue
|
||||
|
||||
now = time.monotonic()
|
||||
timeout_action = policy.check_timeout(now)
|
||||
if timeout_action:
|
||||
handle_action(timeout_action)
|
||||
|
||||
if charger_mode:
|
||||
online_now = is_external_power_online()
|
||||
if prev_online and not online_now:
|
||||
close_screen()
|
||||
log('charger unplugged in charger mode -> powering off')
|
||||
if not dry_run:
|
||||
subprocess.run(['/usr/sbin/poweroff'], check=True, timeout=10)
|
||||
time.sleep(30)
|
||||
raise RuntimeError('Poweroff did not finish within 30s')
|
||||
prev_online = online_now
|
||||
|
||||
now = time.monotonic()
|
||||
if screen_on:
|
||||
dur = 5.0 if charger_mode else float(screen_seconds)
|
||||
if now >= screen_opened_at + dur:
|
||||
close_screen('screen auto-off')
|
||||
elif now >= last_refresh + 2.0 and display_session is not None:
|
||||
try:
|
||||
display_session.refresh(mode='charger' if charger_mode else 'status')
|
||||
except OSError as exc:
|
||||
log(f'display refresh error: {exc}')
|
||||
close_screen()
|
||||
last_refresh = time.monotonic()
|
||||
elif (not charger_mode and not screen_on and not standby_active
|
||||
and idle_suspend_seconds > 0
|
||||
and now - last_activity >= idle_suspend_seconds
|
||||
and not Path('/run/platina-inhibit-suspend').exists()):
|
||||
if not dry_run:
|
||||
set_cpu_standby('standby')
|
||||
standby_active = True
|
||||
log('entered low-power DVFS standby (big=300MHz, little=633MHz, panel=off)')
|
||||
finally:
|
||||
close_screen()
|
||||
if power_key_mode and not dry_run:
|
||||
set_cpu_standby('active')
|
||||
for fd in descriptors:
|
||||
os.close(fd)
|
||||
|
||||
@@ -151,11 +527,18 @@ def monitor(seconds, dry_run):
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--hold-seconds', type=float, default=3)
|
||||
parser.add_argument('--power-key-mode', action='store_true',
|
||||
help='Enable single Power button screen toggle, hold shutdown/charger, and DVFS standby')
|
||||
parser.add_argument('--screen-seconds', type=float, default=12)
|
||||
parser.add_argument('--idle-suspend-seconds', type=float, default=60)
|
||||
parser.add_argument('--dry-run', action='store_true')
|
||||
args = parser.parse_args()
|
||||
ChordPolicy(args.hold_seconds)
|
||||
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
|
||||
monitor(args.hold_seconds, args.dry_run)
|
||||
monitor(args.hold_seconds, args.dry_run,
|
||||
power_key_mode=args.power_key_mode,
|
||||
screen_seconds=args.screen_seconds,
|
||||
idle_suspend_seconds=args.idle_suspend_seconds)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
+11
-15
@@ -28,21 +28,17 @@ def is_charger_connected():
|
||||
return False
|
||||
|
||||
|
||||
def enter_charger_standby():
|
||||
print('platina-poweroff: external power connected; entering low-power suspend standby', flush=True)
|
||||
state_file = Path('/sys/power/state')
|
||||
if state_file.exists():
|
||||
for mode in ('mem', 'freeze'):
|
||||
try:
|
||||
state_file.write_text(mode + '\n')
|
||||
print(f'platina-poweroff: woke from {mode} standby', flush=True)
|
||||
return
|
||||
except OSError:
|
||||
continue
|
||||
try:
|
||||
subprocess.run(['pm-suspend'], check=True, timeout=10)
|
||||
except (OSError, subprocess.SubprocessError):
|
||||
pass
|
||||
def enter_charger_standby(cpufreq_root=Path('/sys/devices/system/cpu/cpufreq')):
|
||||
print('platina-poweroff: external power connected; applied low-power charger standby', flush=True)
|
||||
root = Path(cpufreq_root)
|
||||
if not root.exists():
|
||||
return
|
||||
for policy in sorted(root.glob('policy*')):
|
||||
try:
|
||||
min_freq = (policy / 'scaling_min_freq').read_text().strip()
|
||||
(policy / 'scaling_max_freq').write_text(min_freq + '\n')
|
||||
except OSError:
|
||||
continue
|
||||
|
||||
|
||||
def request_shutdown(force=False, standby=False):
|
||||
|
||||
Executable
+701
@@ -0,0 +1,701 @@
|
||||
#!/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())
|
||||
+3
-1
@@ -144,7 +144,9 @@ def check():
|
||||
raise ValueError('Profile version differs from recipe: ' + package)
|
||||
if (ROOT / '.git').is_dir():
|
||||
tracked = subprocess.check_output(['git', 'ls-files', '-z'], cwd=ROOT).decode().split('\0')
|
||||
allowed = {str(p.relative_to(ROOT)) for p in candidates} | {'PLAN.md'}
|
||||
release_files = ({str(p.relative_to(ROOT)) for p in (ROOT / 'release').rglob('*')
|
||||
if p.is_file()} if (ROOT / 'release').is_dir() else set())
|
||||
allowed = {str(p.relative_to(ROOT)) for p in candidates} | {'PLAN.md'} | release_files
|
||||
if any(name and name not in allowed for name in tracked):
|
||||
raise ValueError('Unexpected tracked path; review Git index')
|
||||
run(['git', 'diff', '--check'])
|
||||
|
||||
@@ -4,39 +4,44 @@
|
||||
mkdir -p /sysroot/usr/local/sbin
|
||||
cat << 'EOF' > /sysroot/usr/local/sbin/platina-usb-gadget
|
||||
#!/bin/sh
|
||||
# Platina USB gadget NCM bringup
|
||||
# Platina USB gadget NCM bringup (preserves initramfs-bound g1 to avoid macOS NCM re-enumeration drops)
|
||||
set -e
|
||||
CONFIGFS=/sys/kernel/config/usb_gadget
|
||||
|
||||
# Mount configfs if not mounted
|
||||
if ! mountpoint -q /sys/kernel/config; then
|
||||
mount -t configfs none /sys/kernel/config 2>/dev/null || true
|
||||
fi
|
||||
|
||||
mkdir -p $CONFIGFS/g1
|
||||
echo "0x18D1" > $CONFIGFS/g1/idVendor
|
||||
echo "0xD001" > $CONFIGFS/g1/idProduct
|
||||
CURRENT_UDC=$(cat "$CONFIGFS/g1/UDC" 2>/dev/null || true)
|
||||
if [ -z "$CURRENT_UDC" ]; then
|
||||
mkdir -p "$CONFIGFS/g1"
|
||||
echo "0x2717" > "$CONFIGFS/g1/idVendor"
|
||||
echo "0xff80" > "$CONFIGFS/g1/idProduct"
|
||||
|
||||
mkdir -p $CONFIGFS/g1/strings/0x409
|
||||
echo "Xiaomi" > $CONFIGFS/g1/strings/0x409/manufacturer
|
||||
echo "postmarketOS" > $CONFIGFS/g1/strings/0x409/serialnumber
|
||||
echo "Mi 8 Lite" > $CONFIGFS/g1/strings/0x409/product
|
||||
mkdir -p "$CONFIGFS/g1/strings/0x409"
|
||||
echo "Xiaomi" > "$CONFIGFS/g1/strings/0x409/manufacturer"
|
||||
echo "63c36adb" > "$CONFIGFS/g1/strings/0x409/serialnumber"
|
||||
echo "Xiaomi Mi 8 Lite" > "$CONFIGFS/g1/strings/0x409/product"
|
||||
|
||||
mkdir -p $CONFIGFS/g1/functions/ncm.usb0
|
||||
mkdir -p $CONFIGFS/g1/configs/c.1/strings/0x409
|
||||
echo "USB Network" > $CONFIGFS/g1/configs/c.1/strings/0x409/configuration
|
||||
mkdir -p "$CONFIGFS/g1/functions/ncm.usb0"
|
||||
echo "d2:d1:1e:20:5a:dc" > "$CONFIGFS/g1/functions/ncm.usb0/host_addr" 2>/dev/null || true
|
||||
echo "0e:f1:f5:d7:ba:a9" > "$CONFIGFS/g1/functions/ncm.usb0/dev_addr" 2>/dev/null || true
|
||||
|
||||
if [ ! -L $CONFIGFS/g1/configs/c.1/ncm.usb0 ]; then
|
||||
ln -s $CONFIGFS/g1/functions/ncm.usb0 $CONFIGFS/g1/configs/c.1/
|
||||
fi
|
||||
mkdir -p "$CONFIGFS/g1/configs/c.1/strings/0x409"
|
||||
echo "USB Network" > "$CONFIGFS/g1/configs/c.1/strings/0x409/configuration"
|
||||
|
||||
UDC=$(ls /sys/class/udc | head -1)
|
||||
if [ -n "$UDC" ]; then
|
||||
CURRENT=$(cat $CONFIGFS/g1/UDC 2>/dev/null || true)
|
||||
if [ "$CURRENT" != "$UDC" ]; then
|
||||
echo "$UDC" > $CONFIGFS/g1/UDC
|
||||
if [ ! -L "$CONFIGFS/g1/configs/c.1/ncm.usb0" ]; then
|
||||
ln -s "$CONFIGFS/g1/functions/ncm.usb0" "$CONFIGFS/g1/configs/c.1/"
|
||||
fi
|
||||
|
||||
UDC=$(ls /sys/class/udc | head -1)
|
||||
if [ -n "$UDC" ]; then
|
||||
echo "$UDC" > "$CONFIGFS/g1/UDC"
|
||||
fi
|
||||
fi
|
||||
|
||||
ip link set usb0 up 2>/dev/null || true
|
||||
ip addr replace 172.16.42.1/24 dev usb0 2>/dev/null || true
|
||||
EOF
|
||||
chmod +x /sysroot/usr/local/sbin/platina-usb-gadget
|
||||
|
||||
|
||||
Reference in New Issue
Block a user