Files
mu300-linux/tests/test_device_scripts.py
T
Abdurrahman Kaan DikeçandClaude Opus 5.5 77ccbe442a mobile-data: the radio comes up after the modem's first word and the RIL handshake, without an early power cycle
K57: radio_on waits (30 s at most) for nr0's first URC, sends AT+SMMSWAP=0 to the nr1 daemon once per boot
(/run/mu300-ril-handshake), sends no AT+SFUN when AT+CFUN? is unanswered, and after AT+SFUN=4 waits for
"+CFUN: 1" (30 real seconds) before the SFUN=2/SFUN=4 power cycle. A lock (/run/mu300-radio-on.lock) keeps two
radio state machines apart; the second caller waits for the first (120 s) instead of the fork's 8 s, since a
dial that gives up costs netifd's 20 s pause.
K58: AT+CAVIMS=1 after the radio is on, in up and in radio-on.
K65: the unisoc-modem plugin's early lock replay ($PLUGIN_LOCK, MU300_PLUGIN_LOCK in tests) runs between the
radio-off answer and AT+SFUN=4; the pending marker is cleared on success only.
K66: `mobile-data radio-on`. K20: mu300-atd's radio-warmup instance runs it once nr1's daemon reads commands.
Ported from kanoqwq/clean-tf-7.2 cd4fb28 and 6404c10 (tests/test_early_replay_hook.py, paths adjusted).

R30: the CGACT=1 comment says only a timeout ends the bring-up; the address waits state their real worst case
and fetch_addr no longer sleeps past its budget; at() writes its own pid (not the parent's $$) into the AT lock,
so operator_log's background query owns the lock it holds. A modem reset during the registration wait is left to
the next attempt, which starts with radio_on (as in the fork).

Gate K57/K58 (cold boots, SMS) is deferred to the device phase.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DqKKtBQZCfxYnHuBCuDqqn
2026-10-05 08:03:55 +03:00

1394 lines
73 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""Small device scripts, against a fake / (MU300_SYSROOT) and stub commands: mu300-device, mu300-lan-ip, mu300-led,
mu300-ttl. They run on Ubuntu (dash, bash) and OpenWrt (busybox ash)."""
import os
import pty
import re
import select
import shutil
import subprocess
import threading
import time
import unittest
from pathlib import Path
from helpers import BIN, TOP, ShellTest
class Device(ShellTest):
def root(self, device=None, dt_u30=False):
r = self.tmp / 'root'
(r / 'run' / 'mu300').mkdir(parents=True, exist_ok=True)
if device is not None:
(r / 'run' / 'mu300' / 'device').write_text(device + '\n')
if dt_u30:
(r / 'proc' / 'device-tree' / 'charger_policy_service').mkdir(parents=True, exist_ok=True)
return r
def test_mu300_device(self):
cases = [(None, False, 'f50'), (None, True, 'u30air'), ('u30air', False, 'u30air'),
('f50', True, 'f50')] # what init wrote wins over the device tree
for device, dt, want in cases:
r = self.root(device, dt)
for shell in self.each_shell():
out = self.script(shell, BIN / 'mu300-device', MU300_SYSROOT=r).stdout.strip()
self.assertEqual(out, want, (device, dt))
(r / 'run' / 'mu300' / 'device').unlink(missing_ok=True)
def test_lan_ip(self):
for device, want in (('f50', '192.168.77.1'), ('u30air', '192.168.78.1'), ('', '192.168.77.1')):
r = self.root(device)
for shell in self.each_shell():
out = self.script(shell, BIN / 'mu300-lan-ip', MU300_SYSROOT=r, MU300_BIN=BIN).stdout.strip()
self.assertEqual(out, want, device)
class At(ShellTest):
"""mu300-at against a fake daemon directory: a FIFO `cmd` and a thread that answers through the answer file."""
def setUp(self):
super().setUp()
self.dir = self.tmp / 'at'
self.dir.mkdir()
os.mkfifo(self.dir / 'cmd')
(self.tmp / 'bb').mkdir()
self.sleeper = self.tmp / 'bb' / 'busybox'
self.sleeper.write_text('#!/usr/bin/env python3\nimport sys, time\n'
'assert sys.argv[1] == "sleep"\ntime.sleep(float(sys.argv[2]))\n')
self.sleeper.chmod(0o755)
def daemon(self, reply, count=1, open_delay=0, answer_delay=0):
"""Answer COUNT commands with REPLY the way mu300-atd does: open the FIFO afresh for each command (after
OPEN_DELAY: the daemon is busy draining), read `T answer-file command`, write the answer file after
ANSWER_DELAY. A command whose writer has gone before the open is lost, as with the real daemon."""
def run():
for _ in range(count):
time.sleep(open_delay)
line = ''
while not line: # like the daemon: an empty read (no writer yet) just reopens
with open(self.dir / 'cmd') as f:
line = f.readline().rstrip('\n')
_t, answer, _cmd = line.split(' ', 2)
time.sleep(answer_delay)
with open(answer, 'w', newline='') as a:
a.write(reply)
th = threading.Thread(target=run, daemon=True)
th.start()
return th
def at(self, shell, *args):
return self.script(shell, BIN / 'mu300-at', *args, MU300_AT_DIR=self.dir, MU300_BUSYBOX=self.sleeper)
def test_answer_needs_a_final_result_code(self):
for shell in self.each_shell():
self.daemon('\r\n')
r = self.at(shell, 'AT')
self.assertEqual(r.returncode, 1)
self.assertIn('modem returned no final response', r.stderr)
self.daemon('+CSQ: 20,99\r\nOK\r\n')
r = self.at(shell, 'AT+CSQ')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(r.stdout.replace('\r', ''), '+CSQ: 20,99\nOK\n') # text mode folds CRLF
def test_no_daemon_does_not_hang(self):
for shell in self.each_shell():
t0 = time.monotonic()
r = self.at(shell, '-t', 1, 'AT')
self.assertLess(time.monotonic() - t0, 3 + 0.5)
self.assertEqual(r.returncode, 1)
self.assertIn('no answer from the daemon', r.stderr)
self.assertFalse((self.dir / 'lock').exists())
def test_command_survives_a_busy_daemon(self):
# the daemon opens the FIFO only 0.5 s after the client wrote: the command must still be there
for shell in self.each_shell():
self.daemon('OK\r\n', open_delay=0.5)
r = self.at(shell, '-t', 2, 'AT')
self.assertEqual(r.returncode, 0, r.stderr)
def test_live_daemon_gets_a_long_budget(self):
# a live mu300-atd (owner/pid) may drain before it collects: an answer after T + 2 s is still taken
owner = subprocess.Popen(['sh', '-c', 'sleep 60; :', 'mu300-atd'])
try:
(self.dir / 'owner').mkdir()
(self.dir / 'owner' / 'pid').write_text(f'{owner.pid}\n')
if not Path(f'/proc/{owner.pid}/cmdline').exists():
self.skipTest('no /proc')
for shell in self.each_shell():
self.daemon('OK\r\n', answer_delay=3.5)
r = self.at(shell, '-t', 1, 'AT')
self.assertEqual(r.returncode, 0, r.stderr)
finally:
owner.kill()
owner.wait()
def test_signal_stops_the_client_and_frees_the_lock(self):
for shell in self.each_shell():
p = subprocess.Popen(shell + [str(BIN / 'mu300-at'), '-t', '20', 'AT'], stderr=subprocess.PIPE,
env=self.env(MU300_AT_DIR=self.dir, MU300_BUSYBOX=self.sleeper))
for _ in range(200):
if (self.dir / 'lock').exists():
break
time.sleep(0.02)
time.sleep(0.3)
p.terminate()
self.assertEqual(p.wait(timeout=10), 143)
p.stderr.close()
self.assertFalse((self.dir / 'lock').exists())
self.assertEqual(list(self.dir.glob('answer.*')), [])
def test_vanished_fifo_is_not_replaced_by_a_file(self):
for shell in self.each_shell():
(self.dir / 'cmd').unlink()
r = self.at(shell, 'AT') # no FIFO: the direct path, which has no tty here
self.assertNotEqual(r.returncode, 0)
self.assertFalse((self.dir / 'cmd').exists())
os.mkfifo(self.dir / 'cmd')
def test_fast_round_trip(self):
for shell in self.each_shell():
self.daemon('OK\r\n', 20)
t0 = time.monotonic()
for _ in range(20):
self.assertEqual(self.at(shell, 'AT').returncode, 0)
self.assertLess(time.monotonic() - t0, 3)
class Atd(ShellTest):
"""mu300-atd on a pseudo terminal pair: the test is the modem (the pty master), the daemon runs for real."""
FAST = 0.95 # a round trip without the one second drain wait: read -t 1 alone cannot be faster than this
def setUp(self):
super().setUp()
self.dir = self.tmp / 'at'
self.procs = []
self.masters = []
self.slave_fds = []
def tearDown(self):
for p in self.procs:
p.terminate() # the daemon's INT/TERM trap stops its drainers
try:
p.wait(timeout=5)
except subprocess.TimeoutExpired:
p.kill()
p.wait()
for fd in self.masters + self.slave_fds:
os.close(fd)
super().tearDown()
def pty(self, name):
"""A character device RUN/NAME (a symlink to a pty slave) and the master fd behind it."""
master, slave = pty.openpty()
self.masters.append(master)
self.slave_fds.append(slave) # keep the slave open: no hangup
link = self.run_dir / name
link.symlink_to(os.ttyname(slave))
return link, master
def start(self, shell, nr0=True, **env):
"""Start the daemon on tty_nr1 (and a tty_nr0 if NR0); wait until it owns the channel and every drainer it
started has made its log. Returns the URC logs and the nr1 master."""
self.run_dir = self.tmp / f'run{len(self.procs)}' # one per daemon: each_shell starts several
self.run_dir.mkdir()
self.dir = self.run_dir / 'at'
dev, master = self.pty('tty_nr1')
if nr0:
self.pty('tty_nr0')
e = self.env(MU300_AT_DEV=dev, MU300_AT_DIR=self.dir, **env)
if 'MU300_AT_URC_CHANNELS' not in env:
e.pop('MU300_AT_URC_CHANNELS', None)
self.err = self.run_dir / 'atd.err'
with self.err.open('w') as err:
self.procs.append(subprocess.Popen(shell + [str(BIN / 'mu300-atd')], stderr=err, env=e))
# "... is ours, draining N other channel(s)" comes once every drainer has been started
n = None
for _ in range(500):
m = re.search(r'is ours, draining\s+(\d+) other', self.err.read_text())
if m:
n = int(m.group(1))
break
time.sleep(0.02)
self.assertIsNotNone(n, 'the daemon did not come up: ' + self.err.read_text())
urc = self.dir / 'urc'
for _ in range(500): # a drainer makes its log in the background
logs = sorted(p.name for p in urc.iterdir())
if len(logs) >= n:
break
time.sleep(0.02)
return logs, master
def send(self, master, cmd, reply, t=1):
"""Hand the daemon CMD (as a client does), answer on the pty when it arrives; seconds until the answer file.
The answer itself is left in self.answer."""
answer = self.tmp / 'answer'
answer.unlink(missing_ok=True)
t0 = time.monotonic()
with open(self.dir / 'cmd', 'w') as f:
f.write(f'{t} {answer} {cmd}\n')
buf = b''
while cmd.encode() + b'\r' not in buf:
if not select.select([master], [], [], 10)[0]:
break
buf += os.read(master, 256)
if reply is not None:
os.write(master, reply)
while not answer.exists() and time.monotonic() - t0 < 40:
time.sleep(0.02)
elapsed = time.monotonic() - t0
self.answer = answer.read_text() if answer.exists() else None
return elapsed
def whole_seconds(self):
"""The daemon's shell reads in whole seconds only (bash 3.2): every drain then waits the full second."""
return 'takes whole seconds' in self.err.read_text()
def test_log_lines_after_open_reach_stderr(self):
for shell in self.each_shell():
self.start(shell)
self.assertIn('is ours, draining', self.err.read_text())
def test_unset_urc_channels_open_nr0(self):
for shell in self.each_shell():
logs, _m = self.start(shell)
self.assertEqual(logs, ['tty_nr0.log'])
def test_empty_urc_channels_open_none(self):
for shell in self.each_shell():
logs, _m = self.start(shell, MU300_AT_URC_CHANNELS='')
self.assertRegex(self.err.read_text(), r'draining\s+0 other')
self.assertEqual(logs, [])
def test_no_drain_wait_after_a_clean_reply(self):
for shell in self.each_shell():
_l, m = self.start(shell, nr0=False)
self.send(m, 'AT', b'\r\nOK\r\n') # the first command drains slowly: nothing known yet
if self.whole_seconds():
continue
for reply in (b'\r\nOK\r\n', b'\r\nERROR\r\n', b'\r\nOK\r\n'): # the last one times the drain after ERROR
self.assertLess(self.send(m, 'AT', reply), self.FAST)
def test_slow_drain_after_a_timeout(self):
for shell in self.each_shell():
_l, m = self.start(shell, nr0=False)
self.send(m, 'AT', b'\r\nOK\r\n')
self.send(m, 'AT+X', None, t=1) # no answer: the timeout path
self.assertGreater(self.send(m, 'AT', b'\r\nOK\r\n'), 0.9)
if not self.whole_seconds():
self.assertLess(self.send(m, 'AT', b'\r\nOK\r\n'), self.FAST) # and a clean one makes it fast again
def test_stray_lines_while_idle_do_not_shift_the_answers(self):
# A line that arrives after a clean reply and before the next command - a late final code, a URC, an
# unsolicited NO CARRIER - is drained into the nr1 log, never taken as the next command's answer.
for shell in self.each_shell():
_l, m = self.start(shell, nr0=False)
self.send(m, 'AT', b'\r\nOK\r\n')
# (a) a late trailing final code, the moment the reply that ended in OK has been handed over
self.send(m, 'AT+A', b'\r\n+A: 1\r\nOK\r\n')
self.assertEqual(self.answer, '+A: 1\nOK\n')
os.write(m, b'\r\nOK\r\n')
self.send(m, 'AT+B', b'\r\n+B: 2\r\nOK\r\n')
self.assertEqual(self.answer, '+B: 2\nOK\n')
# (b) URCs and an unsolicited final code while the channel is idle, before the next command
os.write(m, b'\r\n+CMTI: "SM",3\r\n\r\nNO CARRIER\r\n')
time.sleep(0.2)
self.send(m, 'AT+C', b'\r\n+C: 3\r\nOK\r\n')
self.assertEqual(self.answer, '+C: 3\nOK\n')
self.send(m, 'AT+D', b'\r\nERROR\r\n')
self.assertEqual(self.answer, 'ERROR\n')
self.assertEqual((self.dir / 'urc' / 'tty_nr1.log').read_text().split('\n'),
['OK', '+CMTI: "SM",3', 'NO CARRIER', ''])
class MobileData(ShellTest):
"""mobile-data's at(): which daemon directory the command goes to (K17). The function is cut out of the script and
its absolute paths pointed at the scratch directory, so nothing else of mobile-data runs."""
def run_at(self, shell, nr2, nr1=True):
run = self.tmp / 'run'
shutil.rmtree(run, ignore_errors=True)
for flag, name in ((nr1, 'mu300-at'), (nr2, 'mu300-at2')):
d = run / name
d.mkdir(parents=True, exist_ok=True)
if flag:
os.mkfifo(d / 'cmd')
self.stub('mu300-at', 'echo "dir=$MU300_AT_DIR args=$*" >> "$STUBLOG/calls"')
text = (BIN / 'mobile-data').read_text()
body = text[text.index('\nat() {'):text.index('\n}\n', text.index('\nat() {')) + 3]
body = body.replace('/run/', f'{run}/').replace('/opt/mu300/bin/mu300-at', 'mu300-at')
(self.tmp / 'calls').unlink(missing_ok=True)
r = self.sh(shell, body + '\nat "AT+CSQ" 4', MU300_AT_DIR='')
self.assertEqual(r.returncode, 0, r.stderr)
return (self.tmp / 'calls').read_text().strip()
def test_at_prefers_the_nr2_daemon(self):
for shell in self.each_shell():
out = self.run_at(shell, nr2=True)
self.assertRegex(out, r'^dir=\S*/run/mu300-at2 args=-t 4 AT\+CSQ$', shell)
# the nr1 daemon takes over while nr2's is not there (yet): mu300-at's own default directory
out = self.run_at(shell, nr2=False)
self.assertEqual(out, 'dir= args=-t 4 AT+CSQ', shell)
# mobile-data's functions with MU300_LIB=1 (K56, K59-K62). mobile-data is a bash script (#!/bin/bash, on OpenWrt
# too), so these run under bash only; under alpine they still use busybox's tail, wc, sleep and awk.
# `at` is replaced by the modem below, which answers from a table and writes each command it was sent to
# $STUBLOG/at as "<seconds since the start> <command>".
MODEM = r'''
at() {
echo "$SECONDS $1" >> "$STUBLOG/at"
case $1 in
'AT+CEREG?') printf '%s\nOK\n' "${CEREG:-+CEREG: 2,2}" ;;
'AT+CFUN?') printf '+CFUN: 1\nOK\n' ;;
AT+CGCONTRDP=*)
# the address arrives once CGACT=1 has been sent $ADDR_AFTER times
if [ "$(grep -c 'AT+CGACT=1' "$STUBLOG/at")" -ge "${ADDR_AFTER:-1}" ]; then
printf '%s\nOK\n' "${RDP:-+CGCONTRDP: 1,5,\"apn\",\"10.1.2.3.255.255.255.0\",\"10.1.2.1\",\"8.8.8.8\",\"1.1.1.1\"}"
else
printf '+CGCONTRDP: 1,5,"apn","0.0.0.0.0.0.0.0","0.0.0.0","0.0.0.0","0.0.0.0"\nOK\n'
fi ;;
AT+CGDATA=*) printf 'CONNECT\n' ;;
AT+CGPADDR=*) printf '+CGPADDR: 1,"10.1.2.3"\nOK\n' ;;
'AT+COPS?') printf '+COPS: 0,0,"Test Net",7\nOK\n' ;;
*) printf 'OK\n' ;;
esac
}
'''
def lib(self, code, modem=None, **env):
"""Run CODE with bash after sourcing mobile-data (MU300_LIB=1) and replacing `at` by MODEM (or MODEM).
/run is the scratch directory's run/; mu300-led and mu300-at are stubs on PATH. The mu300-at stub is the nr1
daemon's client that radio_on's RIL handshake calls directly: it logs "nr1 <command>" to $STUBLOG/at and
answers $SMMSWAP (OK by default; "none" is a timeout)."""
if not shutil.which('bash'):
self.skipTest('no bash')
text = (BIN / 'mobile-data').read_text()
text = text.replace('/run/', f'{self.tmp}/run/').replace('/opt/mu300/bin/mu300-led', 'mu300-led')
text = text.replace('/opt/mu300/bin/mu300-at ', 'mu300-at ')
lib = self.tmp / 'mobile-data.lib'
lib.write_text(text)
(self.tmp / 'run').mkdir(exist_ok=True)
for f in ('at', 'led', 'rf', 'nr1env'):
(self.tmp / f).unlink(missing_ok=True)
self.stub('mu300-led', 'echo "$*" >> "$STUBLOG/led"')
self.stub('mu300-at', '[ "$1" = -t ] && shift 2\necho "nr1 $1" >> "$STUBLOG/at"\n'
'echo "dir=$MU300_AT_DIR wait=$MU300_AT_LOCK_WAIT" > "$STUBLOG/nr1env"\n'
'case ${SMMSWAP:-OK} in none) echo "mu300-at: no answer from the daemon" >&2; exit 1 ;; esac\n'
'echo "${SMMSWAP:-OK}"')
r = self.sh(['bash'], f'MU300_LIB=1; . "{lib}"\n{modem or self.MODEM}\nSECONDS=0\n{code}', **env)
sent = (self.tmp / 'at').read_text().splitlines() if (self.tmp / 'at').exists() else []
return r, sent
def test_registered_from_urc(self):
"""nr0 announces the registration: wait_registered sees it in the URC log and asks nothing in the first 5 s."""
log = self.tmp / 'stty_nr0.log'
# the modem's last word before the call was "searching"; the registration is appended a second later
log.write_text('+CEREG: 2\n')
r, sent = self.lib('(sleep 1; printf \'+CEREG: 1,"1A2B","0123ABCD",7\\n\' >> "$MU300_URC_LOG") &\n'
'rc=0; wait_registered || rc=$?; echo "rc=$rc t=$SECONDS"',
MU300_URC_LOG=log, MU300_REGISTER_WAIT=20, CEREG='+CEREG: 2,2')
self.assertRegex(r.stdout, r'rc=0 t=[0-4]\b', r.stderr)
self.assertFalse([s for s in sent if 'AT+CEREG?' in s], sent)
# mu300-atd starts the log over at its size cap: a registration written after the cut still counts
log.write_text('+CEREG: 2\n' * 50)
r, sent = self.lib('(sleep 1; : > "$MU300_URC_LOG"; printf \'+CEREG: 5\\n\' >> "$MU300_URC_LOG") &\n'
'rc=0; wait_registered || rc=$?; echo "rc=$rc t=$SECONDS"',
MU300_URC_LOG=log, MU300_REGISTER_WAIT=20, CEREG='+CEREG: 2,2')
self.assertRegex(r.stdout, r'rc=0 t=[0-4]\b', r.stderr)
self.assertFalse([s for s in sent if 'AT+CEREG?' in s], sent)
def test_old_urc_does_not_count(self):
"""A registration announced before the call proves nothing now: the query decides, and is sent at once."""
log = self.tmp / 'stty_nr0.log'
log.write_text('+CEREG: 2\n+CEREG: 1,"1A2B","0123ABCD",7\n')
r, sent = self.lib('rc=0; wait_registered || rc=$?; echo "rc=$rc t=$SECONDS"',
MU300_URC_LOG=log, MU300_REGISTER_WAIT=20, CEREG='+CEREG: 2,1,"1A2B","0123ABCD",7')
self.assertRegex(r.stdout, r'rc=0 t=[01]\b', r.stderr)
self.assertTrue([s for s in sent if 'AT+CEREG?' in s], sent)
# nothing new arrives and the query says "searching": not registered when the budget is spent. "+CEREG: 1,2"
# is the query form with <n>=1 and <stat>=2, not a registration.
r, sent = self.lib('rc=0; wait_registered || rc=$?; echo "rc=$rc t=$SECONDS"',
MU300_URC_LOG=log, MU300_REGISTER_WAIT=6, CEREG='+CEREG: 1,2')
self.assertRegex(r.stdout, r'rc=1 t=[6-8]\b', r.stderr)
# the fallback asks every 5 s, not every 2
self.assertEqual(len([s for s in sent if 'AT+CEREG?' in s]), 2, sent)
def test_fetch_addr_bounded(self):
"""+CGCONTRDP keeps answering 0.0.0.0: fetch_addr gives up within its budget (in seconds, not rounds), and
does not sleep past it (queries at 0 and 2 s; a third would start after the budget, so none is waited for)."""
r, _ = self.lib('rc=0; fetch_addr 3 || rc=$?; echo "rc=$rc t=$SECONDS rdp=$rdp"', ADDR_AFTER=99)
self.assertRegex(r.stdout, r'rc=1 t=[23] rdp=$', r.stderr)
r, _ = self.lib('rc=0; fetch_addr 3 || rc=$?; echo "rc=$rc rdp=$rdp"', ADDR_AFTER=0)
self.assertIn('rc=0 rdp=+CGCONTRDP: 1,5,"apn","10.1.2.3.255.255.255.0"', r.stdout, r.stderr)
def test_address_after_one_cgact_reassert(self):
"""up (netifd mode): no AT+CGACT? first, one idempotent CGACT=1 reassert when the address is late, never
CGACT=0, and the decision is in radio.log (K60, K62)."""
r, sent = self.lib('up_locked', MU300_NETIFD=1, MU300_AT_DEV='/dev/null', MU300_URC_LOG=self.tmp / 'none',
CEREG='+CEREG: 2,1,"1A2B","0123ABCD",7', ADDR_AFTER=2, MU300_CFUN_WAIT=0,
MU300_ADDR_WAIT_FIRST=2, MU300_ADDR_WAIT_RETRY=6)
self.assertEqual(r.returncode, 0, r.stderr)
self.assertIn('IP=10.1.2.3\nPREFIX=24\nDNS1=8.8.8.8\nDNS2=1.1.1.1\n', r.stdout)
cmds = [s.split(' ', 1)[1] for s in sent]
# K58: the IMS bearer SMS needs, once the radio is on and before the registration wait
self.assertLess(cmds.index('AT+CFUN?'), cmds.index('AT+CAVIMS=1'), cmds)
self.assertLess(cmds.index('AT+CAVIMS=1'), cmds.index('AT+CEREG?'), cmds)
self.assertEqual(cmds.count('AT+CGACT=1,1'), 2, cmds)
self.assertNotIn('AT+CGACT?', cmds)
self.assertFalse([c for c in cmds if c.startswith('AT+CGACT=0')], cmds)
radio = (self.tmp / 'run' / 'mu300' / 'radio.log').read_text()
self.assertRegex(radio, r'(?m)^t=\S* +registered\b')
self.assertIn('reasserting', radio)
def test_led_from_cereg(self):
"""4G or 5G from the AcT field of AT+CEREG? (K56), not from AT+COPS?."""
for act, want in (('13', 'data 5g'), ('7', 'data on'), ('11', 'data 5g')):
r, sent = self.lib('led_up', CEREG=f'+CEREG: 2,1,"1A2B","0123ABCD",{act}')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual((self.tmp / 'led').read_text().strip(), want, act)
self.assertEqual([s.split(' ', 1)[1] for s in sent], ['AT+CEREG?'], act)
def test_systemd_path_keeps_v6_up(self):
"""K63 is rejected: on the systemd path (Ubuntu) an IPv6 address from the network still runs v6_up, and none
switches IPv6 off."""
text = (BIN / 'mobile-data').read_text()
start = text.index('\nup_locked() {')
body = text[start:text.index('\ndown() {', start)] # the nft here-documents have their own '}' lines
netifd = body.index('if [ "${MU300_NETIFD:-0}" = 1 ]; then')
self.assertIn('[ -n "$iid" ] || v6_off', body[:netifd])
self.assertIn('[ -n "$iid" ] && v6_up "$iid"', body[netifd:])
self.assertNotIn('MU300_PDP_TYPE:-IP}" != IP', body) # the fork's replacement for v6_up
# radio_on (K57, K65, K66). The radio's state: "+CFUN: $CFUN" (0 by default, "none" = no answer) until AT+SFUN=4
# has been answered, then $RF_LAG more "+CFUN: 0" and "+CFUN: 1" from then on. AT+SFUN=4 takes $SFUN_DELAY s.
RADIO = r'''
at() {
echo "$SECONDS $1" >> "$STUBLOG/at"
case $1 in
'AT+CFUN?')
[ "${CFUN:-}" = none ] && { echo "mu300-at: modem returned no final response" >&2; return 1; }
if [ -e "$STUBLOG/rf" ]; then
k=$(cat "$STUBLOG/rf")
if [ "$k" -gt 0 ]; then echo $((k - 1)) > "$STUBLOG/rf"; printf '+CFUN: 0\nOK\n'
else printf '+CFUN: 1\nOK\n'; fi
else
printf '+CFUN: %s\nOK\n' "${CFUN:-0}"
fi ;;
'AT+SFUN=4') sleep "${SFUN_DELAY:-0}"; echo "${RF_LAG:-0}" > "$STUBLOG/rf"; printf 'OK\n' ;;
*) printf 'OK\n' ;;
esac
}
'''
def radio(self, code, urc='+CEREG: 2\n', **env):
"""CODE against RADIO, with nr0's URC log already written (URC=None: no log) and no plugin unless the test
names one (MU300_PLUGIN_LOCK)."""
log = self.tmp / 'stty_nr0.log'
log.unlink(missing_ok=True)
if urc is not None:
log.write_text(urc)
env.setdefault('MU300_PLUGIN_LOCK', self.tmp / 'no-plugin')
r, sent = self.lib(code, modem=self.RADIO, MU300_URC_LOG=log, **env)
return r, sent, [s.split(' ', 1)[1] for s in sent]
def radio_log(self):
p = self.tmp / 'run' / 'mu300' / 'radio.log'
return p.read_text() if p.exists() else ''
def test_ril_handshake_once_per_boot(self):
"""AT+SMMSWAP=0 is nr1's first command, sent through the nr1 daemon once per boot (K57)."""
marker = self.tmp / 'run' / 'mu300-ril-handshake'
r, sent, cmds = self.radio('radio_on; radio_on; echo ok', RF_LAG=0)
self.assertIn('ok', r.stdout, r.stderr)
self.assertEqual(cmds.count('AT+SMMSWAP=0'), 1, cmds)
self.assertEqual(cmds[0], 'AT+SMMSWAP=0', cmds)
self.assertTrue(sent[0].startswith('nr1 '), sent) # mu300-at to nr1, not at() (nr2)
self.assertEqual((self.tmp / 'nr1env').read_text().strip(), f'dir={self.tmp}/run/mu300-at wait=1')
self.assertTrue(marker.exists())
self.assertEqual(cmds.count('AT+SFUN=4'), 1, cmds) # the second call found the radio on
# no answer to the handshake: the round ends there, nothing else is sent and the next round tries again
marker.unlink()
r, sent, cmds = self.radio('rc=0; radio_on || rc=$?; echo "rc=$rc"', SMMSWAP='none')
self.assertIn('rc=1', r.stdout, r.stderr)
self.assertEqual(cmds, ['AT+SMMSWAP=0'])
self.assertFalse(marker.exists())
self.assertIn('RIL handshake', self.radio_log())
def test_waits_for_nr0_first(self):
"""Nothing is sent before nr0 has said something (the CP is still starting); the wait is bounded."""
r, sent, cmds = self.radio(f'(sleep 1; echo "+CEREG: 2" > "{self.tmp}/stty_nr0.log") &\nradio_on; echo ok',
urc=None, MU300_CFUN_WAIT=10)
self.assertIn('ok', r.stdout, r.stderr)
first = [s for s in sent if s[0].isdigit()][0]
self.assertGreaterEqual(int(first.split()[0]), 1, sent)
# nr0 never speaks: go ahead after MU300_CFUN_WAIT s anyway
r, sent, cmds = self.radio('radio_on; echo "ok t=$SECONDS"', urc=None, MU300_CFUN_WAIT=1)
self.assertRegex(r.stdout, r'ok t=[12]\b', r.stderr)
self.assertIn('AT+SFUN=4', cmds)
def test_no_sfun_when_cfun_is_unanswered(self):
"""A channel that does not answer AT+CFUN? gets no AT+SFUN either (K57)."""
r, sent, cmds = self.radio('rc=0; radio_on || rc=$?; echo "rc=$rc"', CFUN='none')
self.assertIn('rc=1', r.stdout, r.stderr)
self.assertFalse([c for c in cmds if c.startswith('AT+SFUN')], cmds)
self.assertIn('no answer to AT+CFUN?', self.radio_log())
def test_radio_comes_up_late_without_a_power_cycle(self):
"""After AT+SFUN=4 the radio says 0 twice and then 1: wait for it, no SFUN=2 off/on cycle (K57)."""
r, sent, cmds = self.radio('rc=0; radio_on || rc=$?; echo "rc=$rc t=$SECONDS"', RF_LAG=2)
self.assertRegex(r.stdout, r'rc=0 t=[4-6]\b', r.stderr)
self.assertEqual(cmds.count('AT+SFUN=4'), 1, cmds)
self.assertNotIn('AT+SFUN=2', cmds)
self.assertEqual(cmds.count('AT+CFUN?'), 4, cmds) # before, then 0, 0, 1
self.assertRegex(self.radio_log(), r'radio on [4-6] s after AT\+SFUN=4')
# already on (and the handshake done this boot): one question, nothing switched
r, sent, cmds = self.radio('radio_on; echo ok', CFUN=1)
self.assertEqual(cmds, ['AT+CFUN?'])
def test_two_radio_on_one_state_machine(self):
"""The warm-up and the dial meet: the second radio_on waits for the first instead of running its own CFUN/SFUN
sequence beside it, and then finds the radio on (K57)."""
r, sent, cmds = self.radio('radio_on & a=$!; radio_on & b=$!\n'
'ra=0; wait $a || ra=$?; rb=0; wait $b || rb=$?; echo "ra=$ra rb=$rb"',
SFUN_DELAY=1)
self.assertIn('ra=0 rb=0', r.stdout, r.stderr)
self.assertEqual(cmds.count('AT+SMMSWAP=0'), 1, cmds)
self.assertEqual(cmds.count('AT+SFUN=4'), 1, cmds)
self.assertEqual(cmds.count('AT+CFUN?'), 3, cmds) # the first: 0, then 1; the second: 1
self.assertFalse((self.tmp / 'run' / 'mu300-radio-on.lock').exists())
def test_early_lock_replay_hook(self):
"""K65: the plugin's lock replay runs after the handshake and the radio-off answer, before AT+SFUN=4; only
when the plugin is installed and has not replayed yet; a failed replay never stops the radio."""
hook = self.tmp / 'lock'
hook.write_text('#!/bin/sh\necho "- hook $*" >> "$STUBLOG/at"\nexit "${HOOK_RC:-0}"\n')
hook.chmod(0o755)
pending = self.tmp / 'run' / 'unisoc-modem-early-hook-pending'
pending.parent.mkdir(exist_ok=True)
pending.touch()
r, sent, cmds = self.radio('radio_on; echo ok', MU300_PLUGIN_LOCK=hook)
self.assertIn('ok', r.stdout, r.stderr)
self.assertEqual(cmds[:4], ['AT+SMMSWAP=0', 'AT+CFUN?', 'hook replay early', 'AT+SFUN=4'], cmds)
self.assertFalse(pending.exists()) # the plugin's generic worker may use nr1 now
# no plugin: no hook
r, sent, cmds = self.radio('radio_on; echo ok')
self.assertNotIn('hook replay early', cmds)
self.assertIn('AT+SFUN=4', cmds)
# the plugin already replayed its locks this boot
(self.tmp / 'run' / 'unisoc-modem-lock-replay-done').touch()
r, sent, cmds = self.radio('radio_on; echo ok', MU300_PLUGIN_LOCK=hook)
self.assertNotIn('hook replay early', cmds)
(self.tmp / 'run' / 'unisoc-modem-lock-replay-done').unlink()
# a failed replay: said in radio.log, the radio comes on all the same
r, sent, cmds = self.radio('radio_on; echo ok', MU300_PLUGIN_LOCK=hook, HOOK_RC=1)
self.assertIn('ok', r.stdout, r.stderr)
self.assertIn('AT+SFUN=4', cmds)
self.assertIn('early lock replay unverified; late fallback remains armed', self.radio_log())
# a failed radio_on keeps the marker: the worker stays away from nr1 until a round succeeds
pending.touch()
r, sent, cmds = self.radio('radio_on || echo failed', CFUN='none', MU300_PLUGIN_LOCK=hook)
self.assertIn('failed', r.stdout, r.stderr)
self.assertNotIn('hook replay early', cmds)
self.assertTrue(pending.exists())
def test_radio_on_subcommand(self):
"""K66: `mobile-data radio-on` switches the radio on and asks for the IMS bearer (K58), nothing more."""
text = (BIN / 'mobile-data').read_text()
case = text[text.index('\ncase "${1:-status}" in'):]
self.assertRegex(case, r'\n radio-on\)')
r, sent, cmds = self.radio('main() { set -- radio-on' + case + '\n}\nmain; echo ok',
MU300_AT_DEV='/dev/null')
self.assertIn('ok', r.stdout, r.stderr)
self.assertEqual(cmds, ['AT+SMMSWAP=0', 'AT+CFUN?', 'AT+SFUN=4', 'AT+CFUN?', 'AT+CAVIMS=1'])
def test_background_at_owns_the_lock_itself(self):
"""R30: at() on the direct path (no daemon) in a background subshell writes its own pid into the AT lock, not
the parent's: the lock owner has to be the process that is reading the channel."""
r, _ = self.lib('unset -f at; . "$STUBLOG/mobile-data.lib"\n'
'( at AT 2 >/dev/null ) & bg=$!\n'
f'sleep 0.5; echo "owner=$(cat "{self.tmp}/run/mu300-at/owner/pid") bg=$bg parent=$$"; wait',
MU300_AT_DEV='/dev/null')
m = re.search(r'owner=(\d+) bg=(\d+) parent=(\d+)', r.stdout)
self.assertTrue(m, r.stdout + r.stderr)
self.assertEqual(m.group(1), m.group(2))
self.assertNotEqual(m.group(1), m.group(3))
class Bootmark(ShellTest):
"""bootmark (K42): one "t=<uptime> words" line per call on tmpfs, -r empties, never fails."""
def test_two_calls_two_lines_and_reset_empties(self):
up = self.tmp / 'uptime'
up.write_text('12.34 56.78\n')
os.environ['MU300_UPTIME'] = str(up)
self.addCleanup(os.environ.pop, 'MU300_UPTIME', None)
for shell in self.each_shell():
f = self.tmp / 'run' / 'boot-timeline' # its directory does not exist yet: bootmark creates it
shutil.rmtree(f.parent, ignore_errors=True)
for words in ('first mark', 'second'):
r = self.script(shell, BIN / 'bootmark', *words.split(), MU300_TIMELINE=str(f))
self.assertEqual(r.returncode, 0, shell)
lines = f.read_text().splitlines()
self.assertEqual(len(lines), 2, shell)
self.assertRegex(lines[0], r'^t=12\.34 +first mark$', shell)
self.assertRegex(lines[1], r'^t=12\.34 +second$', shell)
self.script(shell, BIN / 'bootmark', '-r', 'fresh', MU300_TIMELINE=str(f))
self.assertEqual(len(f.read_text().splitlines()), 1, shell)
self.assertIn(' fresh', f.read_text(), shell)
self.script(shell, BIN / 'bootmark', '-r', MU300_TIMELINE=str(f))
self.assertEqual(f.read_text().strip(), '', shell)
def test_unwritable_path_is_exit_zero(self):
for shell in self.each_shell():
for path in ('/proc/nonexistent/x/boot-timeline', str(self.tmp)): # no such directory; a directory
r = self.script(shell, BIN / 'bootmark', 'x', MU300_TIMELINE=path)
self.assertEqual(r.returncode, 0, (shell, path))
r = self.script(shell, BIN / 'bootmark', '-r', 'x', MU300_TIMELINE=path)
self.assertEqual(r.returncode, 0, (shell, path))
def test_the_default_is_on_tmpfs_and_the_callers_guard_it(self):
self.assertIn('${MU300_TIMELINE:-/run/mu300/boot-timeline}', (BIN / 'bootmark').read_text())
self.assertTrue(os.access(BIN / 'bootmark', os.X_OK))
for f in (BIN / 'android-vendor-start', BIN / 'mobile-data',
TOP / 'openwrt' / 'overlay' / 'etc' / 'init.d' / 'mu300-atd'):
text = f.read_text()
self.assertRegex(text, r'\[ -x /opt/mu300/bin/bootmark \] && /opt/mu300/bin/bootmark .*\|\| true', f.name)
# no bare call: every bootmark call sits behind the guard or inside mark()
self.assertNotRegex(text, r'(?m)^\s*/opt/mu300/bin/bootmark', f.name)
self.assertIn('bootmark S19-atd-init', (TOP / 'openwrt' / 'overlay' / 'etc' / 'init.d' / 'mu300-atd').read_text())
class VendorStart(ShellTest):
"""android-vendor-start (K40, K41): the partition links without forks, and no sleep after logdw."""
def test_link_partitions_from_a_fake_sysfs(self):
text = (BIN / 'android-vendor-start').read_text()
body = text[text.index('\nlink_partitions() {'):text.index('\n}\n', text.index('\nlink_partitions() {')) + 3]
sysdir, dev = self.tmp / 'sys', self.tmp / 'dev'
(dev / 'block' / 'by-name').mkdir(parents=True)
for name, uevent in (('mmcblk0p1', 'MAJOR=179\nMINOR=1\nPARTNAME=boot_a\nDEVTYPE=partition\n'),
('mmcblk0p2', 'MAJOR=179\nMINOR=2\nPARTNAME=system a=b\n'),
('mmcblk0p3', 'MAJOR=179\nMINOR=3\n')): # no PARTNAME: only the block link
(sysdir / name).mkdir(parents=True)
(sysdir / name / 'uevent').write_text(uevent)
(sysdir / 'mmcblk0boot0').mkdir() # not a partition: not matched by mmcblk0p*
for shell in self.each_shell():
r = self.sh(shell, body + f'\nlink_partitions {sysdir} {dev}')
self.assertEqual(r.returncode, 0, (shell, r.stderr))
links = {p.relative_to(dev).as_posix(): os.readlink(p) for p in dev.rglob('*') if p.is_symlink()}
self.assertEqual(links, {
'block/mmcblk0p1': f'{dev}/mmcblk0p1', 'block/mmcblk0p2': f'{dev}/mmcblk0p2',
'block/mmcblk0p3': f'{dev}/mmcblk0p3',
'block/by-name/boot_a': f'{dev}/mmcblk0p1', 'block/by-name/system a=b': f'{dev}/mmcblk0p2'}, shell)
# a second run over existing links is fine, and an absent sysfs is not an error
self.assertEqual(self.sh(shell, body + f'\nlink_partitions {sysdir} {dev}').returncode, 0, shell)
self.assertEqual(self.sh(shell, body + f'\nlink_partitions {self.tmp}/none {dev}').returncode, 0, shell)
shutil.rmtree(dev / 'block'); (dev / 'block' / 'by-name').mkdir(parents=True)
def test_no_forks_in_the_loop_and_no_sleep_after_logdw(self):
text = (BIN / 'android-vendor-start').read_text()
body = text[text.index('\nlink_partitions() {'):text.index('\n}\n', text.index('\nlink_partitions() {'))]
for cmd in ('basename', 'dirname', 'sed', '$(', '`'):
self.assertNotIn(cmd, body)
self.assertNotRegex(text, r'logdw[^\n]*sleep 1')
self.assertNotRegex(text, r'(?m)^\s*\[ -S /dev/socket/logdw \] \|\|')
class Os(ShellTest):
"""mu300-os against a fake disk area: three systems, and a kept copy is never offered."""
def setUp(self):
super().setUp()
self.disk = self.tmp / 'disk'
for name in ('ubuntu', 'openwrt', 'openwrt-luci', 'openwrt-luci.old'):
init = self.disk / name / 'sbin' / 'init'
init.parent.mkdir(parents=True)
init.write_text('#!/bin/sh\n'); init.chmod(0o755)
(self.disk / name / 'etc').mkdir()
self.root = self.tmp / 'root'
(self.root / 'etc' / 'mu300').mkdir(parents=True)
(self.root / 'etc' / 'mu300' / 'default-boot').write_text('linux\n')
self.stub('mountpoint', 'exit 0')
def os(self, shell, *args):
return self.script(shell, BIN / 'mu300-os', *args, MU300_DISK=self.disk, MU300_SYSROOT=self.root)
def test_lists_the_third_system(self):
for shell in self.each_shell():
out = self.os(shell).stdout
self.assertIn('openwrt-luci: installed', out)
self.assertNotIn('.old', out)
def test_choosing_it(self):
for shell in self.each_shell():
(self.disk / 'openwrt-luci' / 'etc' / 'mu300' / 'default-boot').unlink(missing_ok=True)
r = self.os(shell, 'openwrt-luci')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual((self.disk / '.mu300' / 'boot-os').read_text().strip(), 'openwrt-luci')
self.assertEqual((self.disk / 'openwrt-luci' / 'etc' / 'mu300' / 'default-boot').read_text().strip(), 'linux')
def test_a_kept_copy_cannot_be_chosen(self):
for shell in self.each_shell():
r = self.os(shell, 'openwrt-luci.old')
self.assertEqual(r.returncode, 1)
self.assertFalse((self.disk / '.mu300' / 'boot-os').exists())
class Led(ShellTest):
# the U30 Air's: power is the battery LED's white (the PMIC's green channel), the network LED blue on 4G
# (net_blue), white on 5G (zte-ldo0), red without service (keyboard-backlight); the Wi-Fi LED's colours are LDOs too
LEDS = ['sc27xx:blue', 'sc27xx:red', 'sc27xx:green', 'net_blue', 'keyboard-backlight', 'zte-ldo0', 'zte-ldo1', 'zte-ldo2']
def setUp(self):
super().setUp()
self.root = self.tmp / 'root'
self.setUp_leds()
(self.root / 'run' / 'mu300').mkdir(parents=True)
(self.root / 'proc').mkdir()
self.conf = self.tmp / 'led.conf'
self.uptime(100)
self.stub('iw', 'cat "$STUBLOG/iw.out" 2>/dev/null')
def setUp_leds(self):
for n in self.LEDS:
d = self.root / 'sys' / 'class' / 'leds' / n
d.mkdir(parents=True, exist_ok=True)
(d / 'brightness').write_text('0\n')
(d / 'max_brightness').write_text('255\n')
(d / 'trigger').write_text('[none] timer\n')
def uptime(self, s):
(self.root / 'proc' / 'uptime').write_text(f'{s}.42 1234.00\n')
def reset(self):
for n in self.LEDS:
(self.root / 'sys/class/leds' / n / 'brightness').write_text('0\n')
for f in (self.root / 'run/mu300').glob('led/*'):
f.unlink()
for f in (self.root / 'run/mu300').glob('led/.awake-until'):
f.unlink()
self.conf.unlink(missing_ok=True)
def state(self):
return {n: (self.root / 'sys/class/leds' / n / 'brightness').read_text().strip() for n in self.LEDS}
def led(self, shell, device, *args):
(self.root / 'run/mu300/device').write_text(device + '\n')
return self.script(shell, BIN / 'mu300-led', *args, MU300_SYSROOT=self.root, MU300_BIN=BIN,
MU300_LED_CONF=self.conf)
def test_u30air(self):
for shell in self.each_shell():
self.reset()
self.assertEqual(self.led(shell, 'u30air', 'power', 'on').returncode, 0)
self.assertEqual(self.led(shell, 'u30air', 'data', 'error').returncode, 0)
s = self.state()
self.assertEqual((s['sc27xx:green'], s['keyboard-backlight'], s['net_blue']), ('255', '255', '0'))
self.led(shell, 'u30air', 'data', 'on')
s = self.state()
self.assertEqual((s['keyboard-backlight'], s['net_blue']), ('0', '255'))
self.led(shell, 'u30air', 'data', '5g')
s = self.state()
self.assertEqual((s['keyboard-backlight'], s['net_blue'], s['zte-ldo0']), ('0', '0', '255'))
self.led(shell, 'u30air', 'data', 'on') # back to 4G
s = self.state()
self.assertEqual((s['net_blue'], s['zte-ldo0']), ('255', '0'))
self.led(shell, 'u30air', 'data', '5g')
self.led(shell, 'u30air', 'data', 'error')
s = self.state()
self.assertEqual((s['keyboard-backlight'], s['net_blue'], s['zte-ldo0']), ('255', '0', '0'))
self.led(shell, 'u30air', 'data', 'off')
self.assertEqual(self.state()['net_blue'], '0')
self.assertEqual(self.state()['sc27xx:blue'], '0') # the F50's LED is not touched
def test_wifi_colour_follows_the_band(self):
for shell in self.each_shell():
self.reset()
self.led(shell, 'u30air', 'power', 'on')
for iw, lit, dark in (('channel 36 (5180 MHz), width: 80 MHz', 'zte-ldo2', 'zte-ldo1'),
('channel 6 (2437 MHz), width: 20 MHz', 'zte-ldo1', 'zte-ldo2')):
(self.tmp / 'iw.out').write_text(f'Interface wlan0\n\ttype AP\n\t{iw}\n')
self.led(shell, 'u30air', 'wifi', 'on')
s = self.state()
self.assertEqual((s[lit], s[dark]), ('255', '0'), iw)
self.led(shell, 'u30air', 'wifi', 'off')
self.assertEqual((self.state()['zte-ldo2'], self.state()['zte-ldo1']), ('0', '0'))
# the hotspot just started and has no channel yet: its setting decides
(self.tmp / 'iw.out').write_text('Interface wlan0\n\ttype AP\n')
conf = self.tmp / 'hotspot.conf'
for band, lit in (('2.4', 'zte-ldo1'), ('5', 'zte-ldo2')):
conf.write_text(f'SSID=x\nPSK=12345678\nBAND={band}\n')
(self.root / 'run/mu300/device').write_text('u30air\n')
self.script(shell, BIN / 'mu300-led', 'wifi', 'on', MU300_SYSROOT=self.root, MU300_BIN=BIN,
MU300_LED_CONF=self.conf, MU300_HOTSPOT_CONF=conf)
self.assertEqual(self.state()[lit], '255', band)
def test_timeout(self):
for shell in self.each_shell():
self.reset()
self.uptime(100)
self.led(shell, 'u30air', 'power', 'on') # boot: lit for 60 s
self.led(shell, 'u30air', 'data', 'on')
self.uptime(150)
self.led(shell, 'u30air', 'sleep', '--if-due') # not yet
self.assertEqual(self.state()['net_blue'], '255')
self.uptime(161)
self.led(shell, 'u30air', 'sleep', '--if-due')
self.assertEqual({v for v in self.state().values()}, {'0'})
# a change while dark is kept, and shown on the next wake
self.led(shell, 'u30air', 'data', 'error')
self.assertEqual(self.state()['keyboard-backlight'], '0')
self.led(shell, 'u30air', 'wake')
s = self.state()
self.assertEqual((s['sc27xx:green'], s['keyboard-backlight'], s['net_blue']), ('255', '255', '0'))
# and the timeout counts from the wake
self.uptime(161 + 59)
self.led(shell, 'u30air', 'sleep', '--if-due')
self.assertEqual(self.state()['sc27xx:green'], '255')
self.uptime(161 + 61)
self.led(shell, 'u30air', 'sleep', '--if-due')
self.assertEqual(self.state()['sc27xx:green'], '0')
def test_no_timeout(self):
for shell in self.each_shell():
for device, conf in (('u30air', 'LED_TIMEOUT=0\n'), ('f50', '')):
self.reset()
if conf:
self.conf.write_text(conf)
self.uptime(100)
self.led(shell, device, 'power', 'on')
self.led(shell, device, 'data', 'on')
self.uptime(100000)
self.led(shell, device, 'sleep', '--if-due')
lit = 'net_blue' if device == 'u30air' else 'sc27xx:blue'
self.assertEqual(self.state()[lit], '255', device)
def test_f50(self):
for shell in self.each_shell():
self.reset()
for args in (('power', 'on'), ('wifi', 'on'), ('data', 'error'), ('wake',), ('sleep',)):
# nothing to show on an F50: no error, and no LED of the U30 Air switched
self.assertEqual(self.led(shell, 'f50', *args).returncode, 0, args)
self.led(shell, 'f50', 'data', 'on')
s = self.state()
self.assertEqual(s['sc27xx:blue'], '255')
self.assertEqual({v for k, v in s.items() if k != 'sc27xx:blue'}, {'0'})
self.led(shell, 'f50', 'data', '5g') # one LED: blue on 5G too
self.assertEqual(self.state()['sc27xx:blue'], '255')
def test_stale_siren_stops(self):
# a siren the pid file does not name (left behind by a restart) stops by itself: two of them flashed
# together, white lit throughout
for shell in self.each_shell():
self.reset()
pid = self.root / 'run/mu300/led-siren.pid'
self.led(shell, 'u30air', 'alarm', 'on')
p = int(pid.read_text())
pid.write_text('1\n') # someone else's now
deadline = time.time() + 3
while time.time() < deadline:
try:
os.kill(p, 0)
except ProcessLookupError:
break
time.sleep(0.1)
else:
os.kill(p, 15)
self.fail('the stale siren kept running')
pid.unlink()
def test_vendor_ldo_switches_on_5_4(self):
# the 5.4 kernel has no zte-ldoN LEDs: ZTE's zte_ldo_leds switches the same LDOs through vddcamaN_status
for shell in self.each_shell():
self.reset()
for n in ('zte-ldo0', 'zte-ldo1', 'zte-ldo2'):
shutil.rmtree(self.root / 'sys/class/leds' / n)
vendor = self.root / 'sys/devices/platform/zte_ldo_leds'
vendor.mkdir(parents=True, exist_ok=True)
for i in range(3):
(vendor / f'vddcama{i}_status').write_text('0\n')
self.led(shell, 'u30air', 'power', 'on')
self.led(shell, 'u30air', 'data', '5g')
(self.tmp / 'iw.out').write_text('Interface wlan0\n\ttype AP\n\tchannel 36 (5180 MHz)\n')
self.led(shell, 'u30air', 'wifi', 'on')
self.assertEqual([(vendor / f'vddcama{i}_status').read_text().strip() for i in range(3)], ['1', '0', '1'])
self.led(shell, 'u30air', 'sleep')
self.assertEqual([(vendor / f'vddcama{i}_status').read_text().strip() for i in range(3)], ['0', '0', '0'])
shutil.rmtree(self.root / 'sys/devices')
self.setUp_leds()
def test_alarm_siren(self):
# too hot: red and blue take turns on the PMIC's LED until the alarm is off, then the LEDs are as before
for shell in self.each_shell():
for device in ('u30air', 'f50'):
self.reset()
self.conf.write_text('LED_TIMEOUT=0\n')
self.led(shell, device, 'power', 'on')
self.led(shell, device, 'data', 'on')
pid = self.root / 'run/mu300/led-siren.pid'
try:
self.assertEqual(self.led(shell, device, 'alarm', 'on').returncode, 0)
self.assertTrue(pid.exists())
self.led(shell, device, 'alarm', 'on') # a second one starts no second siren
# one colour at a time: white (the U30 Air's green channel) never mixed in
want = ({('255', '0', '0'), ('0', '255', '0'), ('0', '0', '255')} if device == 'u30air'
else {('255', '0', '0'), ('0', '0', '255')})
seen = set()
deadline = time.time() + 4
while time.time() < deadline and not want <= seen:
s = self.state()
seen.add((s['sc27xx:red'], s['sc27xx:green'], s['sc27xx:blue']))
time.sleep(0.03)
self.assertLessEqual(want, seen, device)
if device == 'f50':
self.assertEqual({g for _, g, _ in seen}, {'0'}) # the F50's green is green
finally:
self.led(shell, device, 'alarm', 'off')
self.assertFalse(pid.exists())
time.sleep(0.4) # a killed siren writes no more
s = self.state()
self.assertEqual(s['sc27xx:red'], '0')
# the F50's blue is its data LED: back on; the U30 Air's white is its power LED
self.assertEqual(s['sc27xx:blue'], '255' if device == 'f50' else '0', device)
self.assertEqual(s['sc27xx:green'], '255' if device == 'u30air' else '0', device)
self.assertEqual(self.led(shell, device, 'alarm', 'off').returncode, 0) # off twice
def test_missing_leds_and_bad_usage(self):
for shell in self.each_shell():
empty = self.tmp / 'empty'
(empty / 'run/mu300').mkdir(parents=True, exist_ok=True)
(empty / 'run/mu300/device').write_text('u30air\n')
r = self.script(shell, BIN / 'mu300-led', 'data', 'on', MU300_SYSROOT=empty, MU300_BIN=BIN)
self.assertEqual(r.returncode, 0) # an LED the device has not is skipped
self.assertEqual(self.led(shell, 'u30air', 'blink').returncode, 2)
class WifiBand(ShellTest):
def setUp(self):
super().setUp()
self.conf = self.tmp / 'hotspot.conf'
def band(self, shell, *args):
return self.script(shell, BIN / 'mu300-wifi-band', *args, MU300_HOTSPOT_CONF=self.conf)
def test_toggle(self):
for shell in self.each_shell():
self.conf.write_text("SSID=U30 AIR\nPSK=pa$$ 'w\"d\nBAND=5\nCHANNEL=40\nCOUNTRY=TR\n")
self.conf.chmod(0o600)
self.assertEqual(self.band(shell).stdout.strip(), 'hotspot: 5 GHz')
r = self.band(shell, 'toggle')
self.assertEqual((r.returncode, r.stdout.strip()), (0, 'hotspot: 2.4 GHz'), r.stderr)
self.assertEqual(self.conf.read_text(),
"SSID=U30 AIR\nPSK=pa$$ 'w\"d\nBAND=2.4\nCHANNEL=auto\nCOUNTRY=TR\n")
self.assertEqual(self.conf.stat().st_mode & 0o777, 0o600)
self.band(shell, 'toggle')
self.assertIn('BAND=5\n', self.conf.read_text())
self.band(shell, '2.4')
self.band(shell, '2.4')
self.assertEqual(self.conf.read_text().count('BAND='), 1)
def test_missing_keys_and_file(self):
for shell in self.each_shell():
self.conf.write_text('SSID=x\nPSK=12345678\n') # an old file without BAND/CHANNEL: 5 GHz
self.assertEqual(self.band(shell).stdout.strip(), 'hotspot: 5 GHz')
self.band(shell, 'toggle')
self.assertEqual(self.conf.read_text(), 'SSID=x\nPSK=12345678\nBAND=2.4\nCHANNEL=auto\n')
self.conf.unlink()
self.assertEqual(self.band(shell, '5').returncode, 1)
self.assertEqual(self.band(shell, '6').returncode, 2)
class Buttons(ShellTest):
def test_actions(self):
self.stub('mu300-keys', 'cat "$STUBLOG/keys.in"')
for name in ('mu300-led', 'mu300-wifi-band', 'systemctl', 'logger', 'poweroff'):
self.stub(name, f'echo "{name} $*" >> "$STUBLOG/calls"; [ "{name} $*" != "systemctl is-active --quiet mu300-hotspot" ]')
cases = [('116 short', ['mu300-led wake']),
('138 short', ['mu300-led wake', 'mu300-wifi-band toggle']),
('138 long', ['mu300-led wake', 'systemctl is-active --quiet mu300-hotspot', 'systemctl start mu300-hotspot']),
('0 tick', ['mu300-led sleep --if-due']),
('116 long', ['mu300-led wake', 'systemctl poweroff']),
('115 short', [])]
for shell in self.each_shell():
for event, want in cases:
(self.tmp / 'keys.in').write_text(event + '\n')
(self.tmp / 'calls').unlink(missing_ok=True)
r = self.script(shell, BIN / 'mu300-buttons')
self.assertEqual(r.returncode, 0, r.stderr)
calls = (self.tmp / 'calls').read_text().splitlines() if (self.tmp / 'calls').exists() else []
self.assertEqual([c for c in calls if not c.startswith('logger')], want, event)
class ThermalGuard(ShellTest):
"""thermal-guard's LED alarm (one round against a fake /: MU300_SYSROOT)."""
def setUp(self):
super().setUp()
self.root = self.tmp / 'root'
self.bin = self.tmp / 'bin'
self.bin.mkdir()
led = self.bin / 'mu300-led'
led.write_text('#!/bin/sh\necho "mu300-led $*" >> "$STUBLOG/calls"\n')
led.chmod(0o755)
shutil.copy(BIN / 'mu300-device', self.bin / 'mu300-device')
self.device('u30air')
self.stub('logger', ':')
self.stub('poweroff', 'echo poweroff >> "$STUBLOG/calls"')
def device(self, name):
(self.root / 'run/mu300').mkdir(parents=True, exist_ok=True)
(self.root / 'run/mu300/device').write_text(name + '\n')
def round(self, shell, soc, battery=None, trips=False):
z = self.root / 'sys/class/thermal/thermal_zone0'
z.mkdir(parents=True, exist_ok=True)
(z / 'temp').write_text(f'{soc}\n')
if trips:
(z / 'trip_point_0_temp').write_text('95000\n')
if battery is not None:
b = self.root / 'sys/class/power_supply/battery'
b.mkdir(parents=True, exist_ok=True)
(b / 'type').write_text('Battery\n')
(b / 'temp').write_text(f'{battery}\n')
(self.tmp / 'calls').unlink(missing_ok=True)
r = self.script(shell, BIN / 'thermal-guard', MU300_SYSROOT=self.root, MU300_BIN=self.bin)
self.assertEqual(r.returncode, 0, r.stderr)
return (self.tmp / 'calls').read_text().splitlines() if (self.tmp / 'calls').exists() else []
def test_alarm_on_and_off(self):
for shell in self.each_shell():
shutil.rmtree(self.root, ignore_errors=True)
self.device('u30air')
self.assertEqual(self.round(shell, 60000, 300), [])
self.assertEqual(self.round(shell, 86000, 300), ['mu300-led alarm on'])
self.assertEqual(self.round(shell, 90000, 300), []) # on already
self.assertEqual(self.round(shell, 80000, 300), []) # not cool enough yet
self.assertEqual(self.round(shell, 74000, 300), ['mu300-led alarm off'])
self.assertEqual(self.round(shell, 60000, 510), ['mu300-led alarm on']) # the battery alone
self.assertEqual(self.round(shell, 60000, 460), [])
self.assertEqual(self.round(shell, 60000, 440), ['mu300-led alarm off'])
def test_f50_battery_is_ignored(self):
# the F50 has no battery, but mainline's fuel gauge reports one at 75.0 C from an open NTC input: the
# alarm went on at every boot and never off (v2026.10.06)
for shell in self.each_shell():
shutil.rmtree(self.root, ignore_errors=True)
self.device('f50')
self.assertEqual(self.round(shell, 46000, 750), [])
self.assertEqual(self.round(shell, 86000, 750), ['mu300-led alarm on']) # the SoC still counts
self.assertEqual(self.round(shell, 74000, 750), ['mu300-led alarm off'])
def test_vendor_kernel_only_watches(self):
# 5.4 has its own trip points: no throttling or power-off here, but the alarm still works
for shell in self.each_shell():
shutil.rmtree(self.root, ignore_errors=True)
self.device('u30air')
self.assertEqual(self.round(shell, 110000, trips=True), ['mu300-led alarm on'])
shutil.rmtree(self.root, ignore_errors=True)
self.device('u30air')
self.assertEqual(self.round(shell, 110000), ['poweroff', 'mu300-led alarm on']) # mainline: critical
class Nfc(ShellTest):
"""mu300-nfc against a fake FM11NT08: 1 KiB behind a stub i2ctransfer, which answers only while a stub gpioset
holds line 190 low, as the tag does."""
EEPROM = r'''
import os, sys
mem = os.path.join(os.environ['STUBLOG'], 'tag.bin')
data = bytearray(open(mem, 'rb').read())
args = [a for a in sys.argv[1:] if a != '-y']
bus, op = args[0], args[1]
if not os.path.exists(os.path.join(os.environ['STUBLOG'], 'held')) or bus != '2' or not op.endswith('@0x57'):
sys.exit('Error: Sending messages failed: Remote I/O error')
n = int(op[1:op.index('@')])
addr = int(args[2], 16) << 8 | int(args[3], 16)
if op.startswith('w') and len(args) > 4 and args[4].startswith('r'):
print(' '.join('0x%02x' % b for b in data[addr:addr + int(args[4][1:])]))
elif op.startswith('w'):
body = [int(x, 16) for x in args[4:]]
# NDEF pages of 16 bytes; the configuration byte on its own
assert len(body) == n - 2 and (len(body) <= 16 and addr % 16 == 0 and addr >= 16 or (addr, len(body)) == (0x3bf, 1)), args
data[addr:addr + len(body)] = bytes(body)
open(mem, 'wb').write(bytes(data))
open(os.path.join(os.environ['STUBLOG'], 'writes'), 'a').write('%x\\n' % addr)
'''
# what ZTE's firmware leaves there: UID, capability container (NDEF, 872 bytes), a Wi-Fi record
ZTE = bytes.fromhex('1df4bcdd99030012 88b20000e1106d00'.replace(' ', ''))
def setUp(self):
super().setUp()
self.root = self.tmp / 'root'
(self.root / 'run/mu300').mkdir(parents=True)
chip = self.tmp / 'devices/platform/soc/64170000.gpio/gpiochip4'
chip.mkdir(parents=True)
(self.root / 'sys/bus/gpio/devices').mkdir(parents=True)
(self.root / 'sys/bus/gpio/devices/gpiochip4').symlink_to(chip)
(self.tmp / 'eeprom.py').write_text(self.EEPROM)
self.stub('i2ctransfer', 'exec python3 "$STUBLOG/eeprom.py" "$@"')
# libgpiod 2: holds the line until killed
self.stub('gpioset', '[ "$1" = --help ] && { echo " -c, --chip"; exit 0; }; '
'[ "$*" = "-c gpiochip4 190=0" ] || exit 1; touch "$STUBLOG/held"; '
'trap \'rm -f "$STUBLOG/held"; exit 0\' TERM; while :; do sleep 0.05; done')
self.conf = self.tmp / 'hotspot.conf'
self.conf.write_text('SSID=U30 AIR\nPSK=secret pass!\nBAND=5\n')
def blank(self, ndef=b'\x03\x00\xfe'):
(self.tmp / 'tag.bin').write_bytes(self.ZTE + ndef + bytes(1024 - 16 - len(ndef)))
(self.tmp / 'writes').unlink(missing_ok=True)
def nfc(self, shell, *args, device='u30air'):
(self.root / 'run/mu300/device').write_text(device + '\n')
return self.script(shell, BIN / 'mu300-nfc', *args, MU300_SYSROOT=self.root, MU300_BIN=BIN,
MU300_HOTSPOT_CONF=self.conf)
def writes(self):
w = self.tmp / 'writes'
return w.read_text().split() if w.exists() else []
def test_wifi_record_is_zte_s(self):
# byte for byte what the stock firmware writes (WSC credential, WPA2-PSK, AES)
for shell in self.each_shell():
self.blank()
r = self.nfc(shell, 'wifi')
self.assertEqual((r.returncode, r.stdout.strip()), (0, 'wifi: U30 AIR (with its password)'), r.stderr)
self.assertNotIn('secret', r.stdout + r.stderr)
ssid, key = b'U30 AIR', b'secret pass!'
cred = (b'\x10\x45\x00' + bytes([len(ssid)]) + ssid + b'\x10\x03\x00\x02\x00\x20\x10\x0f\x00\x02\x00\x08'
+ b'\x10\x27\x00' + bytes([len(key)]) + key + b'\x10\x20\x00\x06' + bytes(6)
+ b'\x10\x49\x00\x06\x00\x37\x2a\x00\x01\x20')
payload = b'\x10\x0e\x00' + bytes([len(cred)]) + cred
rec = b'\xd2\x17' + bytes([len(payload)]) + b'application/vnd.wfa.wsc' + payload
want = b'\x03' + bytes([len(rec)]) + rec + b'\xfe'
data = (self.tmp / 'tag.bin').read_bytes()
self.assertEqual(data[16:16 + len(want)], want)
self.assertEqual(data[:16], self.ZTE) # UID and capability container untouched
self.assertFalse((self.tmp / 'held').exists()) # the line is let go
# again: nothing changed, nothing written
(self.tmp / 'writes').unlink()
self.assertEqual(self.nfc(shell, 'wifi').returncode, 0)
self.assertEqual(self.writes(), [])
def test_url_text_clear(self):
for shell in self.each_shell():
self.blank()
for args, shown in ((('url', 'https://github.com/dikeckaan/mu300-linux'),
'url: https://github.com/dikeckaan/mu300-linux'),
(('url', 'tel:+905551112233'), 'url: tel:+905551112233'),
(('url', 'geo:41.0,29.0'), 'url: geo:41.0,29.0'),
(('text', 'Merhaba, şifre kutunun altında'), 'text: Merhaba, şifre kutunun altında'),
(('clear',), 'empty')):
r = self.nfc(shell, *args)
self.assertEqual((r.returncode, r.stdout.strip()), (0, shown), r.stderr)
self.assertEqual(self.nfc(shell).stdout.strip(), shown)
data = (self.tmp / 'tag.bin').read_bytes()
self.assertEqual(data[16:19], b'\x03\x00\xfe')
def test_long_url(self):
# over 255 bytes: a long record and a three-byte TLV length
for shell in self.each_shell():
self.blank()
url = 'https://example.com/' + 'x' * 400
r = self.nfc(shell, 'url', url)
self.assertEqual(r.stdout.strip(), 'url: ' + url, r.stderr)
data = (self.tmp / 'tag.bin').read_bytes()
self.assertEqual((data[16], data[17]), (0x03, 0xff))
r = self.nfc(shell, 'url', 'https://example.com/' + 'x' * 900)
self.assertNotEqual(r.returncode, 0)
self.assertIn('too long', r.stderr)
def test_sync_keeps_what_the_user_wrote(self):
for shell in self.each_shell():
self.blank()
self.conf.write_text('SSID=U30 AIR\nPSK=secret pass!\nBAND=5\n')
self.assertEqual(self.nfc(shell, 'sync').stdout.strip(), 'wifi: U30 AIR (with its password)')
self.conf.write_text('SSID=Ev\nPSK=another one\n')
self.assertEqual(self.nfc(shell, 'sync').stdout.strip(), 'wifi: Ev (with its password)')
self.nfc(shell, 'url', 'https://example.com/')
(self.tmp / 'writes').unlink()
r = self.nfc(shell, 'sync')
self.assertIn('left as it is', r.stdout)
self.assertEqual(self.writes(), [])
self.assertEqual(self.nfc(shell).stdout.strip(), 'url: https://example.com/')
def test_on_off(self):
# ZTE's NFC switch: bit 5 of the configuration byte 0x3bf (set: phones get nothing); nothing else changes
for shell in self.each_shell():
self.blank()
data = bytearray((self.tmp / 'tag.bin').read_bytes())
data[0x3b0:0x3c0] = bytes.fromhex('0578f057806002 1e0000009e44000420'.replace(' ', ''))
(self.tmp / 'tag.bin').write_bytes(bytes(data))
r = self.nfc(shell)
self.assertIn('NFC is off', r.stdout)
r = self.nfc(shell, 'on')
self.assertEqual((r.returncode, r.stdout.strip()), (0, 'NFC on'), r.stderr)
after = (self.tmp / 'tag.bin').read_bytes()
self.assertEqual(after[0x3b0:0x3c0], bytes.fromhex('0578f0578060021e0000009e44000400'))
self.assertEqual(after[:0x3bf], bytes(data[:0x3bf]))
self.assertNotIn('NFC is off', self.nfc(shell).stdout)
self.assertEqual(self.nfc(shell, 'off').stdout.strip(), 'NFC off')
self.assertEqual((self.tmp / 'tag.bin').read_bytes()[0x3bf], 0x20)
def test_refusals(self):
for shell in self.each_shell():
self.blank()
r = self.nfc(shell, 'wifi', device='f50')
self.assertEqual(r.returncode, 1)
self.assertIn('only the U30 Air', r.stderr)
self.assertEqual(self.nfc(shell, 'blink').returncode, 2)
self.assertEqual(self.nfc(shell, 'url').returncode, 1)
# no capability container: not written
(self.tmp / 'tag.bin').write_bytes(bytes(1024))
r = self.nfc(shell, 'url', 'https://example.com/')
self.assertEqual(r.returncode, 1)
self.assertIn('capability container', r.stderr)
self.assertEqual(self.writes(), [])
class Ttl(ShellTest):
def setUp(self):
super().setUp()
self.conf = self.tmp / 'etc' / 'ttl.conf'
self.stub('id', 'echo 0')
# nft records its arguments, and the ruleset it is given on stdin
self.stub('nft', 'echo "$*" >> "$STUBLOG/nft.args"; [ "$1" = -f ] && cat >> "$STUBLOG/nft.in"; '
'[ "$1" = list ] && exit 1; exit 0')
def ttl(self, shell, *args):
return self.script(shell, BIN / 'mu300-ttl', *args, MU300_TTL_CONF=self.conf)
def reset(self):
for f in ('nft.args', 'nft.in'):
(self.tmp / f).unlink(missing_ok=True)
self.conf.unlink(missing_ok=True)
def test_set(self):
for shell in self.each_shell():
self.reset()
r = self.ttl(shell, 'set', '64')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(self.conf.read_text(), 'TTL=64\n')
rules = (self.tmp / 'nft.in').read_text()
self.assertIn('table inet mu300_ttl', rules)
self.assertIn('oifname "sipa_eth*" ip ttl set 64', rules)
self.assertIn('oifname "sipa_eth*" ip6 hoplimit set 64', rules)
self.assertIn('fixed at 64', r.stdout)
def test_invalid_values_change_nothing(self):
for shell in self.each_shell():
for v in ('0', '256', 'abc', '-1', '6 4', ''):
self.reset()
r = self.ttl(shell, 'set', v)
self.assertEqual(r.returncode, 2, v)
self.assertFalse(self.conf.exists(), v)
self.assertFalse((self.tmp / 'nft.in').exists(), v)
def test_off_and_apply(self):
for shell in self.each_shell():
self.reset()
self.ttl(shell, 'set', '128')
(self.tmp / 'nft.in').unlink()
r = self.ttl(shell, 'off')
self.assertEqual(r.returncode, 0)
self.assertFalse(self.conf.exists())
self.assertIn('delete table inet mu300_ttl', (self.tmp / 'nft.args').read_text())
self.assertFalse((self.tmp / 'nft.in').exists()) # no rule without a setting
self.assertIn('not changed', r.stdout)
# a hand-edited file with junk sets nothing
self.conf.parent.mkdir(parents=True, exist_ok=True)
self.conf.write_text('TTL=999\n')
self.ttl(shell, 'apply')
self.assertFalse((self.tmp / 'nft.in').exists())
def test_not_root(self):
self.stub('id', 'echo 1000')
for shell in self.each_shell():
self.reset()
r = self.ttl(shell, 'set', '64')
self.assertEqual(r.returncode, 1)
self.assertFalse(self.conf.exists())
self.assertEqual(self.ttl(shell).returncode, 0) # status works without root
class Usb(ShellTest):
"""mu300-usb against a fake charger (busybox i2cget/i2cset on files) and a fake role switch."""
def setUp(self):
super().setUp()
r = self.root = self.tmp / 'root'
(r / 'run/mu300').mkdir(parents=True)
(r / 'run/mu300/device').write_text('u30air\n')
node = r / 'sys/firmware/devicetree/base/soc/i2c@22a0000'
node.mkdir(parents=True)
i2c = r / 'sys/bus/i2c/devices/i2c-6'
i2c.mkdir(parents=True)
(i2c / 'of_node').symlink_to(node)
role = r / 'sys/class/usb_role/25100000.dwc3-role-switch'
role.mkdir(parents=True)
(role / 'role').write_text('device\n')
self.stub('id', 'echo 0')
self.stub('sleep', ':')
# i2c-tools (which mu300-usb prefers to busybox's): i2cget -y BUS ADDR REG / i2cset -y BUS ADDR REG VALUE,
# one file per register. (Not a stub called busybox: that would also replace the "busybox sh" under test.)
self.stub('i2cget', '[ "$1" = -y ] && shift; cat "$STUBLOG/reg-$3" 2>/dev/null || echo 0x00')
self.stub('i2cset', '[ "$1" = -y ] && shift; printf "0x%02x\\n" $(( $4 )) > "$STUBLOG/reg-$3"; '
'echo "$3=$(( $4 ))" >> "$STUBLOG/writes"')
def regs(self, **values):
for k, v in values.items():
(self.tmp / f'reg-0x{k[1:]}').write_text(v + '\n')
def reg(self, r):
return int((self.tmp / f'reg-{r}').read_text(), 16)
def usb(self, shell, *args):
return self.script(shell, BIN / 'mu300-usb', *args, MU300_SYSROOT=self.root,
PATH=f'{self.stubs}:{BIN}:/usr/bin:/bin')
def role(self):
return (self.root / 'sys/class/usb_role/25100000.dwc3-role-switch/role').read_text().strip()
def test_host_and_back(self):
for shell in self.each_shell():
self.regs(r01='0x1a', r05='0x9f', r08='0x00') # no outside supply
r = self.usb(shell, 'host')
self.assertEqual(r.returncode, 0, r.stdout + r.stderr)
self.assertEqual(self.role(), 'host')
self.assertEqual(self.reg('0x01'), 0x1a | 0x20) # OTG_CONFIG on, the rest untouched
self.assertEqual(self.reg('0x05'), 0x9f & ~0x30) # watchdog off
r = self.usb(shell, 'device')
self.assertEqual(r.returncode, 0, r.stderr)
self.assertEqual(self.role(), 'device')
self.assertEqual(self.reg('0x01'), 0x1a)
self.assertEqual(self.reg('0x05'), (0x9f & ~0x30) | 0x10)
def test_refuses_while_powered(self):
for shell in self.each_shell():
self.regs(r01='0x1a', r05='0x9f', r08='0x24') # power good, a USB host drives VBUS
(self.tmp / 'writes').unlink(missing_ok=True)
r = self.usb(shell, 'host')
self.assertEqual(r.returncode, 1)
self.assertIn('unplug it first', r.stderr)
self.assertFalse((self.tmp / 'writes').exists()) # not a single register written
self.assertEqual(self.role(), 'device')
def test_boot_switches_a_leftover_boost_off(self):
for shell in self.each_shell():
self.regs(r01='0x3a', r05='0x8f')
r = self.usb(shell, 'boot')
self.assertEqual(r.returncode, 0)
self.assertEqual(self.reg('0x01'), 0x1a)
self.assertIn('switched off', r.stdout)
# nothing to do, nothing written
(self.tmp / 'writes').unlink(missing_ok=True)
self.assertEqual(self.usb(shell, 'boot').stdout, '')
self.assertFalse((self.tmp / 'writes').exists())
def test_f50(self):
for shell in self.each_shell():
(self.root / 'run/mu300/device').write_text('f50\n')
r = self.usb(shell, 'host')
self.assertEqual(r.returncode, 1)
self.assertIn('only the U30 Air', r.stderr)
self.assertEqual(self.usb(shell, 'boot').returncode, 0) # boot is quiet on every device
if __name__ == '__main__':
unittest.main()