Implement 0010 RPM/L2/WCD/UART deep-standby, Adreno 304 ICC/SMMU fixes, and C11 autostart daemons
- patches/kernel/0010-msm8909-rpm-lpm-bimc-wcd-ldo-uart.patch and device DTS/DTB files (nokia-{argon,beatles,beatles-cover,coconut,sparkler,leo}): vMPM APSS RPM sleep, L2 SAW2 collapse, WCD-digital runtime PM, PM8909 LDO seeding, ttyMSM0 disable, dynamic msm_gpu gfx-mem BIMC interconnect scaling (mas_oxili), and qcom_iommu context restore + atomic TLB flush on resume.
- Replace Python/shell autostart loops with compiled C11 ARM ELF daemons (bananarchy-dsds, bananarchy-modemmonitor, bananarchy-soundmonitor, bananarchy-notifmonitor, bananarchy-run-aligned, bananarchy-session-loop) plus scripts/test-dsds-daemon.py.
- Update scripts/check-rebuild.sh, CHANGELOG.md, BATTERY-OPTIMIZATION-ANALYSIS.md, MANUAL.md, README.md, and AGENTS.md with verified a1114 (carbonara) image/archive pins and guards.
This commit is contained in:
1 parent
96c66bf0c6
commit
2ae4ef34a2
86 files changed
+99754
-94563
No files matched your search
@@ -979,7 +979,7 @@ PY
|
||||
fi
|
||||
SIM_WAIT_TIME=2
|
||||
provision_slot "$target" 4
|
||||
pkill -f "dsds-daemon" 2>/dev/null || true
|
||||
killall -q bananarchy-dsds 2>/dev/null || true
|
||||
if [ "${3:-}" = "--swap-gw" ]; then
|
||||
spawn_enable_and_register "$target" 2
|
||||
else
|
||||
@@ -2409,902 +2409,7 @@ PY
|
||||
;;
|
||||
|
||||
dsds-daemon)
|
||||
exec python3 - dsds-daemon << 'PY'
|
||||
import datetime, fcntl, os, select, socket, struct, subprocess, sys, time
|
||||
|
||||
lock_fd = open("/tmp/dsds_daemon.lock", "w")
|
||||
try:
|
||||
fcntl.flock(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
except Exception:
|
||||
sys.exit(0)
|
||||
try:
|
||||
os.chmod("/tmp/dsds_daemon.lock", 0o666)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
try:
|
||||
while os.waitpid(-1, os.WNOHANG)[0] > 0:
|
||||
pass
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
AF_QIPCRTR = 42
|
||||
QRTR_PORT_CTRL = 0xfffffffe
|
||||
QRTR_TYPE_NEW_SERVER = 4
|
||||
QRTR_TYPE_NEW_LOOKUP = 10
|
||||
QMI_SERVICE_UIM = 11
|
||||
QMI_SERVICE_WMS = 5
|
||||
QMI_SERVICE_VOICE = 9
|
||||
|
||||
CALLS_DIR = "/run/user/10000/sxmo_calls"
|
||||
LOG_DIR = "/home/user/.local/share/sxmo/modem"
|
||||
MODEMLOG = os.path.join(LOG_DIR, "modemlog.tsv")
|
||||
|
||||
# This daemon runs as root (via doas), but everything it creates under the
|
||||
# user's runtime and data directories must stay owned by "user": the sxmo
|
||||
# scripts that run as the user append to modemlog.tsv and create call state
|
||||
# files under `set -e`, so a root-owned directory or log file makes them
|
||||
# abort (no call log entries, and rejected calls never get hung up).
|
||||
try:
|
||||
import pwd
|
||||
_pw = pwd.getpwnam("user")
|
||||
USER_UID, USER_GID = _pw.pw_uid, _pw.pw_gid
|
||||
except Exception:
|
||||
USER_UID, USER_GID = 10000, 10000
|
||||
|
||||
def chown_user(path):
|
||||
try:
|
||||
os.chown(path, USER_UID, USER_GID)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def ensure_user_dir(path, stop_at):
|
||||
# Create `path` (and missing parents below `stop_at`) owned by the user,
|
||||
# and repair ownership of directories a previous root-run instance created.
|
||||
parts = []
|
||||
cur = path
|
||||
while cur and cur != stop_at and cur != "/":
|
||||
parts.append(cur)
|
||||
cur = os.path.dirname(cur)
|
||||
for d in reversed(parts):
|
||||
try:
|
||||
os.mkdir(d, 0o755)
|
||||
except FileExistsError:
|
||||
pass
|
||||
except Exception:
|
||||
return
|
||||
try:
|
||||
if os.stat(d).st_uid == 0:
|
||||
chown_user(d)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def append_modemlog(line):
|
||||
ensure_user_dir(LOG_DIR, "/home/user")
|
||||
try:
|
||||
with open(MODEMLOG, "a", encoding="utf-8") as f:
|
||||
f.write(line)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
except Exception:
|
||||
return
|
||||
chown_user(MODEMLOG)
|
||||
|
||||
# Only create the call state directory inside an existing user runtime dir;
|
||||
# never create /run/user/10000 itself as root.
|
||||
if os.path.isdir("/run/user/10000"):
|
||||
ensure_user_dir(CALLS_DIR, "/run/user/10000")
|
||||
ensure_user_dir(LOG_DIR, "/home/user")
|
||||
# Repair logs and directories left root-owned by earlier daemon versions.
|
||||
try:
|
||||
for root_dir, dirs, files in os.walk(LOG_DIR):
|
||||
for name in dirs + files:
|
||||
p = os.path.join(root_dir, name)
|
||||
if os.lstat(p).st_uid == 0:
|
||||
chown_user(p)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def lookup_srv(sid):
|
||||
try:
|
||||
ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
|
||||
node, _ = ls.getsockname()
|
||||
ls.sendto(struct.pack("<IIIII", QRTR_TYPE_NEW_LOOKUP, sid, 0, 0, 0), (node, QRTR_PORT_CTRL))
|
||||
addr = None
|
||||
while True:
|
||||
r, _, _ = select.select([ls], [], [], 0.2)
|
||||
if not r:
|
||||
break
|
||||
data, _ = ls.recvfrom(256)
|
||||
if len(data) >= 20:
|
||||
cmd, srv, inst, srv_node, srv_port = struct.unpack("<IIIII", data[:20])
|
||||
if cmd == QRTR_TYPE_NEW_SERVER:
|
||||
if srv == sid and srv_port != 0:
|
||||
addr = (srv_node, srv_port)
|
||||
if srv == 0 and srv_node == 0 and srv_port == 0:
|
||||
break
|
||||
ls.close()
|
||||
return addr
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def parse_tlvs(resp):
|
||||
res = {}
|
||||
pos = 7
|
||||
while pos + 3 <= len(resp):
|
||||
tt, tl = struct.unpack("<BH", resp[pos:pos+3])
|
||||
pos += 3
|
||||
res[tt] = resp[pos:pos+tl]
|
||||
pos += tl
|
||||
return res
|
||||
|
||||
pending_inds = []
|
||||
|
||||
def qmi_req(s, addr, txn, msg_id, tlvs=b"", timeout=1.0):
|
||||
s.sendto(struct.pack("<BHHH", 0x00, txn, msg_id, len(tlvs)) + tlvs, addr)
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
r, _, _ = select.select([s], [], [], max(0.05, deadline - time.time()))
|
||||
if not r:
|
||||
return {}
|
||||
resp, _ = s.recvfrom(4096)
|
||||
if len(resp) >= 7 and resp[0] == 0x04:
|
||||
pending_inds.append((s, resp))
|
||||
continue
|
||||
if len(resp) >= 7 and resp[0] == 0x02:
|
||||
r_txn, r_msg, _ = struct.unpack("<HHH", resp[1:7])
|
||||
if r_txn == txn and r_msg == msg_id:
|
||||
return parse_tlvs(resp)
|
||||
return {}
|
||||
|
||||
def run_user_cmd(cmd_str, extra_env=None):
|
||||
env = os.environ.copy()
|
||||
env["DISPLAY"] = ":0"
|
||||
env["XDG_RUNTIME_DIR"] = "/run/user/10000"
|
||||
env["HOME"] = "/home/user"
|
||||
env["PATH"] = "/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin"
|
||||
if extra_env:
|
||||
env.update(extra_env)
|
||||
try:
|
||||
p = subprocess.Popen(
|
||||
["su", "-m", "user", "-c", f"export DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/10000 HOME=/home/user PATH=/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin; ({cmd_str}) >/dev/null 2>&1 &"],
|
||||
env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL
|
||||
)
|
||||
p.wait(timeout=2.0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def send_fifo(fifo_path, line):
|
||||
try:
|
||||
if os.path.exists(fifo_path):
|
||||
fd = os.open(fifo_path, os.O_WRONLY | os.O_NONBLOCK)
|
||||
os.write(fd, (line + "\n").encode("utf-8"))
|
||||
os.close(fd)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
GSM7_BASIC = (
|
||||
"@\u00a3$\u00a5\u00e8\u00e9\u00f9\u00ec\u00f2\u00c7\n\u00d8\u00f8\r\u00c5\u00e5"
|
||||
"\u0394_\u03a6\u0393\u039b\u03a9\u03a0\u03a8\u03a3\u0398\u039e\x1b\u00c6\u00e6\u00df\u00c9"
|
||||
" !\"#\u00a4%&'()*+,-./0123456789:;<=>?"
|
||||
"\u00a1ABCDEFGHIJKLMNOPQRSTUVWXYZ\u00c4\u00d6\u00d1\u00dc\u00a7"
|
||||
"\u00bfabcdefghijklmnopqrstuvwxyz\u00e4\u00f6\u00f1\u00fc\u00e0"
|
||||
)
|
||||
GSM7_EXT = {
|
||||
0x0A: "\f", 0x14: "^", 0x28: "{", 0x29: "}", 0x2F: "\\",
|
||||
0x3C: "[", 0x3D: "~", 0x3E: "]", 0x40: "|", 0x65: "\u20ac"
|
||||
}
|
||||
|
||||
def decode_bcd_addr(data, num_digits, ton_npi):
|
||||
ton = (ton_npi >> 4) & 0x07
|
||||
if ton == 5:
|
||||
# Alphanumeric 7-bit GSM address
|
||||
total_septets = (num_digits * 4) // 7
|
||||
septets = []
|
||||
esc = False
|
||||
for i in range(total_septets):
|
||||
bit_off = i * 7
|
||||
byte_idx = bit_off // 8
|
||||
shift = bit_off % 8
|
||||
if byte_idx >= len(data):
|
||||
break
|
||||
val = (data[byte_idx] >> shift) & 0x7F
|
||||
if shift > 1 and (byte_idx + 1) < len(data):
|
||||
val |= (data[byte_idx + 1] << (8 - shift)) & 0x7F
|
||||
if esc:
|
||||
septets.append(GSM7_EXT.get(val, ""))
|
||||
esc = False
|
||||
elif val == 0x1B:
|
||||
esc = True
|
||||
else:
|
||||
septets.append(GSM7_BASIC[val] if val < len(GSM7_BASIC) else "")
|
||||
return "".join(septets).strip("@ ")
|
||||
prefix = "+" if ton == 1 else ""
|
||||
digits = []
|
||||
for b in data:
|
||||
lo = b & 0x0F
|
||||
hi = (b >> 4) & 0x0F
|
||||
if lo < 10:
|
||||
digits.append(str(lo))
|
||||
if hi < 10 and len(digits) < num_digits:
|
||||
digits.append(str(hi))
|
||||
return prefix + "".join(digits[:num_digits])
|
||||
|
||||
def _parse_deliver_tpdu(pdu, pos):
|
||||
try:
|
||||
if pos < 0 or pos + 12 > len(pdu):
|
||||
return None
|
||||
first_octet = pdu[pos]
|
||||
mti = first_octet & 0x03
|
||||
if mti != 0:
|
||||
return None
|
||||
udhi = (first_octet & 0x40) != 0
|
||||
pos += 1
|
||||
oa_digits = pdu[pos]
|
||||
oa_ton_npi = pdu[pos + 1]
|
||||
if oa_digits > 24 or (oa_ton_npi & 0x80) == 0:
|
||||
return None
|
||||
oa_byte_len = (oa_digits + 1) // 2
|
||||
if pos + 2 + oa_byte_len + 10 > len(pdu):
|
||||
return None
|
||||
oa_bytes = pdu[pos + 2 : pos + 2 + oa_byte_len]
|
||||
sender = decode_bcd_addr(oa_bytes, oa_digits, oa_ton_npi)
|
||||
pos += 2 + oa_byte_len
|
||||
pid = pdu[pos]
|
||||
dcs = pdu[pos + 1]
|
||||
scts = pdu[pos + 2 : pos + 9]
|
||||
udl = pdu[pos + 9]
|
||||
ud = pdu[pos + 10 :]
|
||||
|
||||
# Validate and decode SCTS (YY MM DD HH MM SS TZ)
|
||||
def unbcd(b):
|
||||
lo = b & 0x0F
|
||||
hi = (b >> 4) & 0x0F
|
||||
if lo > 9 or hi > 9:
|
||||
raise ValueError("invalid BCD")
|
||||
return (lo * 10) + hi
|
||||
|
||||
yr = 2000 + unbcd(scts[0])
|
||||
mo = unbcd(scts[1])
|
||||
dy = unbcd(scts[2])
|
||||
hr = unbcd(scts[3])
|
||||
mi = unbcd(scts[4])
|
||||
sc = unbcd(scts[5])
|
||||
if not (1 <= mo <= 12 and 1 <= dy <= 31 and 0 <= hr <= 23 and 0 <= mi <= 59 and 0 <= sc <= 59):
|
||||
return None
|
||||
iso_ts = f"{yr:04d}-{mo:02d}-{dy:02d}T{hr:02d}:{mi:02d}:{sc:02d}"
|
||||
|
||||
csms_ref = None
|
||||
csms_total = 1
|
||||
csms_seq = 1
|
||||
udh_bytes = 0
|
||||
if udhi and len(ud) >= 1:
|
||||
udh_len = ud[0]
|
||||
udh_bytes = 1 + udh_len
|
||||
if udh_bytes > len(ud):
|
||||
return None
|
||||
upos = 1
|
||||
while upos + 2 <= udh_bytes and upos + 2 <= len(ud):
|
||||
iei = ud[upos]
|
||||
ielen = ud[upos + 1]
|
||||
iedata = ud[upos + 2 : upos + 2 + ielen]
|
||||
upos += 2 + ielen
|
||||
if iei == 0x00 and len(iedata) >= 3:
|
||||
csms_ref, csms_total, csms_seq = iedata[0], iedata[1], iedata[2]
|
||||
elif iei == 0x08 and len(iedata) >= 4:
|
||||
csms_ref = (iedata[0] << 8) | iedata[1]
|
||||
csms_total, csms_seq = iedata[2], iedata[3]
|
||||
if csms_ref is not None and (csms_total < 1 or csms_seq < 1 or csms_seq > csms_total):
|
||||
csms_ref = None
|
||||
csms_total = 1
|
||||
csms_seq = 1
|
||||
|
||||
# Determine alphabet from 3GPP TS 23.038 DCS
|
||||
if (dcs & 0xC0) in (0x00, 0x40):
|
||||
alphabet = (dcs >> 2) & 0x03
|
||||
if alphabet == 3:
|
||||
alphabet = 0
|
||||
elif (dcs & 0xF0) == 0xE0:
|
||||
alphabet = 2
|
||||
elif (dcs & 0xF0) in (0xC0, 0xD0):
|
||||
alphabet = 0
|
||||
elif (dcs & 0xF0) == 0xF0:
|
||||
alphabet = 1 if (dcs & 0x04) else 0
|
||||
else:
|
||||
alphabet = 0
|
||||
|
||||
if alphabet == 2:
|
||||
end_byte = min(udl, len(ud))
|
||||
payload = ud[udh_bytes : end_byte]
|
||||
if len(payload) % 2 == 1:
|
||||
payload = payload[:-1]
|
||||
text = payload.decode("utf-16-be", errors="surrogatepass")
|
||||
elif alphabet == 1:
|
||||
end_byte = min(udl, len(ud))
|
||||
payload = ud[udh_bytes : end_byte]
|
||||
text = payload.decode("utf-8", errors="replace")
|
||||
else:
|
||||
fill_bits = (7 - ((udh_bytes * 8) % 7)) % 7 if udh_bytes > 0 else 0
|
||||
start_septet = ((udh_bytes * 8) + fill_bits) // 7
|
||||
chars = []
|
||||
esc = False
|
||||
for i in range(start_septet, udl):
|
||||
bit_off = i * 7
|
||||
byte_idx = bit_off // 8
|
||||
shift = bit_off % 8
|
||||
if byte_idx >= len(ud):
|
||||
break
|
||||
val = (ud[byte_idx] >> shift) & 0x7F
|
||||
if shift > 1 and (byte_idx + 1) < len(ud):
|
||||
val |= (ud[byte_idx + 1] << (8 - shift)) & 0x7F
|
||||
if esc:
|
||||
chars.append(GSM7_EXT.get(val, " "))
|
||||
esc = False
|
||||
elif val == 0x1B:
|
||||
esc = True
|
||||
else:
|
||||
chars.append(GSM7_BASIC[val] if val < len(GSM7_BASIC) else "?")
|
||||
text = "".join(chars)
|
||||
|
||||
clean_sender = "".join(
|
||||
c for c in (sender or "Unknown")
|
||||
if c not in "/\x00\r\n\t" and ord(c) >= 32
|
||||
).strip() or "Unknown"
|
||||
|
||||
return {
|
||||
"sender": clean_sender,
|
||||
"time": iso_ts,
|
||||
"text": text,
|
||||
"ref": csms_ref,
|
||||
"total": csms_total,
|
||||
"seq": csms_seq,
|
||||
}
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
def decode_sms_deliver(pdu, only_tpdu=False):
|
||||
if not pdu or len(pdu) < 12:
|
||||
return None
|
||||
if only_tpdu:
|
||||
res = _parse_deliver_tpdu(pdu, 0)
|
||||
if res is not None:
|
||||
return res
|
||||
smsc_len = pdu[0]
|
||||
if 0 <= smsc_len <= 12 and (smsc_len == 0 or (pdu[1] & 0x80) != 0):
|
||||
return _parse_deliver_tpdu(pdu, 1 + smsc_len)
|
||||
return None
|
||||
smsc_len = pdu[0]
|
||||
if 0 <= smsc_len <= 12 and (smsc_len == 0 or (len(pdu) > 1 and (pdu[1] & 0x80) != 0)):
|
||||
res = _parse_deliver_tpdu(pdu, 1 + smsc_len)
|
||||
if res is not None:
|
||||
return res
|
||||
return _parse_deliver_tpdu(pdu, 0)
|
||||
|
||||
multipart_buf = {}
|
||||
recent_sms_dedup = {}
|
||||
|
||||
def _normalize_sms_text(s):
|
||||
try:
|
||||
return s.encode("utf-16", "surrogatepass").decode("utf-16", "replace")
|
||||
except Exception:
|
||||
return s
|
||||
|
||||
BLOCK_FILE = "/home/user/.config/sxmo/block.tsv"
|
||||
BLOCK_DIR = "/home/user/.local/share/sxmo/block"
|
||||
|
||||
def is_sender_blocked(sender):
|
||||
try:
|
||||
if not os.path.isfile(BLOCK_FILE):
|
||||
return False
|
||||
norm = "".join(c for c in sender if c.isdigit() or c == "+")
|
||||
if not norm:
|
||||
norm = sender.strip()
|
||||
sfx = norm[-7:] if len(norm) >= 7 else ""
|
||||
with open(BLOCK_FILE, "r", encoding="utf-8", errors="ignore") as bf:
|
||||
for line in bf:
|
||||
raw = line.split("\t", 1)[0].strip()
|
||||
if not raw:
|
||||
continue
|
||||
r_norm = "".join(c for c in raw if c.isdigit() or c in "+*")
|
||||
if not r_norm:
|
||||
continue
|
||||
if r_norm.endswith("*") and len(r_norm) > 1:
|
||||
if norm.startswith(r_norm[:-1]):
|
||||
return True
|
||||
elif r_norm == norm or (sfx and len(r_norm) >= 7 and r_norm[-7:] == sfx):
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
def deliver_sms_to_sxmo(sender, iso_ts, text, sim_slot):
|
||||
now_str = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
tsv_text = text.replace("\t", " ").replace("\r", " ").replace("\n", " ")
|
||||
if is_sender_blocked(sender):
|
||||
num_dir = os.path.join(BLOCK_DIR, sender)
|
||||
ensure_user_dir(num_dir, "/home/user")
|
||||
sms_file = os.path.join(num_dir, "sms.txt")
|
||||
header = f"Received from {sender} [SIM {sim_slot}] at {now_str}:\n{text}\n\n"
|
||||
with open(sms_file, "a", encoding="utf-8") as f:
|
||||
f.write(header)
|
||||
chown_user(sms_file)
|
||||
blk_log = os.path.join(BLOCK_DIR, "modemlog.tsv")
|
||||
try:
|
||||
with open(blk_log, "a", encoding="utf-8") as f:
|
||||
f.write(f"{now_str}\trecv_txt\t{sender}\t[SIM {sim_slot}] {tsv_text}\n")
|
||||
chown_user(blk_log)
|
||||
except Exception:
|
||||
pass
|
||||
send_fifo("/tmp/dwm_plugin_sms.fifo", "REFRESH")
|
||||
return
|
||||
|
||||
num_dir = os.path.join(LOG_DIR, sender)
|
||||
ensure_user_dir(num_dir, "/home/user")
|
||||
sms_file = os.path.join(num_dir, "sms.txt")
|
||||
header = f"Received from {sender} [SIM {sim_slot}] at {now_str}:\n{text}\n\n"
|
||||
with open(sms_file, "a", encoding="utf-8") as f:
|
||||
f.write(header)
|
||||
f.flush()
|
||||
os.fsync(f.fileno())
|
||||
append_modemlog(f"{now_str}\trecv_txt\t{sender}\t[SIM {sim_slot}] {tsv_text}\n")
|
||||
chown_user(sms_file)
|
||||
send_fifo("/tmp/dwm_plugin_sms.fifo", "REFRESH")
|
||||
run_user_cmd(
|
||||
'CONTACTNAME="$(sxmo_contacts.sh --name-or-number "$SXMO_SMS_SENDER" 2>/dev/null || printf "%s" "$SXMO_SMS_SENDER")"; '
|
||||
'sxmo_notifs.sh new -g "incoming-message-$SXMO_SMS_SENDER" "xsms tailtextlog \'$SXMO_SMS_SENDER\'" "$CONTACTNAME: $SXMO_SMS_TEXT" >/dev/null 2>&1 || true; '
|
||||
'sxmo_hook_sms.sh "$CONTACTNAME" "$SXMO_SMS_TEXT"',
|
||||
extra_env={"SXMO_SMS_SENDER": sender, "SXMO_SMS_TEXT": text}
|
||||
)
|
||||
|
||||
def handle_decoded_sms(info, sim_slot):
|
||||
if not info:
|
||||
return
|
||||
now = time.time()
|
||||
for k, ts in list(recent_sms_dedup.items()):
|
||||
if now - ts > 120.0:
|
||||
del recent_sms_dedup[k]
|
||||
seg_key = ("seg", info["sender"], info["time"], info["ref"], info["total"], info["seq"], info["text"])
|
||||
if seg_key in recent_sms_dedup and now - recent_sms_dedup[seg_key] < 15.0:
|
||||
return
|
||||
recent_sms_dedup[seg_key] = now
|
||||
if info["ref"] is not None and info["total"] > 1:
|
||||
done_key = ("csms_done", info["sender"], info["ref"], info["total"])
|
||||
if done_key in recent_sms_dedup:
|
||||
return
|
||||
key = (info["sender"], info["ref"], info["total"])
|
||||
parts = multipart_buf.setdefault(key, {"ts": now, "time": info["time"], "slot": sim_slot, "segs": {}})
|
||||
parts["ts"] = now
|
||||
parts["slot"] = sim_slot
|
||||
parts["segs"][info["seq"]] = info["text"]
|
||||
if len(parts["segs"]) >= info["total"]:
|
||||
full_text = _normalize_sms_text("".join(parts["segs"].get(i, "") for i in range(1, info["total"] + 1)))
|
||||
msg_time = parts.get("time") or info["time"]
|
||||
del multipart_buf[key]
|
||||
recent_sms_dedup[done_key] = now
|
||||
deliver_sms_to_sxmo(info["sender"], msg_time, full_text, sim_slot)
|
||||
else:
|
||||
deliver_sms_to_sxmo(info["sender"], info["time"], _normalize_sms_text(info["text"]), sim_slot)
|
||||
|
||||
def flush_stale_multipart(wms_sock=None, wms_addr=None, txn=1, sim_slot=2):
|
||||
now = time.time()
|
||||
has_expired = any(now - parts["ts"] >= 45.0 for parts in multipart_buf.values())
|
||||
if has_expired and wms_sock is not None and wms_addr is not None:
|
||||
txn = poll_stored_sms(wms_sock, wms_addr, txn, sim_slot)
|
||||
now = time.time()
|
||||
for key, parts in list(multipart_buf.items()):
|
||||
if now - parts["ts"] >= 45.0:
|
||||
sender, ref, total = key
|
||||
full_text = _normalize_sms_text("".join(parts["segs"].get(i, "") for i in range(1, total + 1)))
|
||||
del multipart_buf[key]
|
||||
recent_sms_dedup[("csms_done", sender, ref, total)] = now
|
||||
if full_text:
|
||||
deliver_sms_to_sxmo(sender, parts.get("time", ""), full_text, parts.get("slot", sim_slot))
|
||||
return txn
|
||||
|
||||
def poll_stored_sms(wms_sock, wms_addr, txn, sim_slot):
|
||||
for _pass in range(3):
|
||||
found_any = False
|
||||
decoded_batch = []
|
||||
for stype in (0, 1):
|
||||
# WMSListMessages (0x0031): TLV 0x01 = storage_type, TLV 0x11 = message_mode (1 = GW)
|
||||
tlvs = qmi_req(wms_sock, wms_addr, txn, 0x0031, struct.pack("<BHB", 0x01, 1, stype) + struct.pack("<BHB", 0x11, 1, 1))
|
||||
txn = (txn % 60000) + 1
|
||||
raw_list = tlvs.get(0x01, b"")
|
||||
if len(raw_list) < 4:
|
||||
continue
|
||||
cnt = struct.unpack("<I", raw_list[:4])[0]
|
||||
off = 4
|
||||
for _ in range(cnt):
|
||||
if off + 5 > len(raw_list):
|
||||
break
|
||||
idx, tag = struct.unpack("<IB", raw_list[off:off+5])
|
||||
off += 5
|
||||
# tag 0 = MT read, 1 = MT not read
|
||||
if tag in (0, 1):
|
||||
found_any = True
|
||||
r_tlvs = qmi_req(wms_sock, wms_addr, txn, 0x0022, struct.pack("<BHBI", 0x01, 5, stype, idx) + struct.pack("<BHB", 0x10, 1, 1))
|
||||
txn = (txn % 60000) + 1
|
||||
qmi_req(wms_sock, wms_addr, txn, 0x0024, struct.pack("<BHB", 0x01, 1, stype) + struct.pack("<BHI", 0x10, 4, idx) + struct.pack("<BHB", 0x12, 1, 1))
|
||||
txn = (txn % 60000) + 1
|
||||
raw_msg = r_tlvs.get(0x01, b"")
|
||||
if len(raw_msg) >= 4:
|
||||
dlen = struct.unpack("<H", raw_msg[2:4])[0]
|
||||
pdu = raw_msg[4:4+dlen]
|
||||
info = decode_sms_deliver(pdu, only_tpdu=False)
|
||||
if info:
|
||||
decoded_batch.append(info)
|
||||
for info in decoded_batch:
|
||||
handle_decoded_sms(info, sim_slot)
|
||||
if not found_any:
|
||||
break
|
||||
return txn
|
||||
|
||||
def parse_call_info(tlvs):
|
||||
calls = {}
|
||||
raw_ci = tlvs[0x01] if 0x01 in tlvs else tlvs.get(0x10, b"")
|
||||
if len(raw_ci) >= 1:
|
||||
cnt = raw_ci[0]
|
||||
off = 1
|
||||
for _ in range(cnt):
|
||||
if off + 7 > len(raw_ci):
|
||||
break
|
||||
cid, cstate, ctype, cdir, cmode, _, _ = struct.unpack("<BBBBBbB", raw_ci[off:off+7])
|
||||
off += 7
|
||||
calls[cid] = {"id": cid, "state": cstate, "dir": cdir, "num": ""}
|
||||
raw_num = tlvs.get(0x10, b"") if 0x01 in tlvs else tlvs.get(0x11, b"")
|
||||
if len(raw_num) >= 1:
|
||||
cnt = raw_num[0]
|
||||
off = 1
|
||||
for _ in range(cnt):
|
||||
if off + 3 > len(raw_num):
|
||||
break
|
||||
cid, _, nlen = struct.unpack("<BBB", raw_num[off:off+3])
|
||||
off += 3
|
||||
num = raw_num[off:off+nlen].decode("ascii", errors="ignore").strip("\x00 ")
|
||||
off += nlen
|
||||
if cid in calls:
|
||||
calls[cid]["num"] = num
|
||||
return calls
|
||||
|
||||
STATE_MAP = {
|
||||
1: "dialing",
|
||||
2: "ringing-in",
|
||||
3: "active",
|
||||
4: "dialing",
|
||||
5: "ringing-out",
|
||||
6: "held",
|
||||
7: "waiting",
|
||||
8: "terminated",
|
||||
9: "terminated",
|
||||
10: "setup",
|
||||
}
|
||||
|
||||
active_calls = {}
|
||||
audio_opened = False
|
||||
|
||||
def stop_ringing_user():
|
||||
run_user_cmd(
|
||||
"rm -f /tmp/sxmo_call_ringing; "
|
||||
"sxmo_jobs.sh stop ringing >/dev/null 2>&1; "
|
||||
"pkill -TERM -f sxmo_hook_ring.sh 2>/dev/null; "
|
||||
"pkill -TERM -f 'pw-play.*ring' 2>/dev/null; "
|
||||
"pkill -TERM -f 'mpv.*ring' 2>/dev/null; "
|
||||
"pkill -TERM -x sxmo_vibrate 2>/dev/null || true"
|
||||
)
|
||||
|
||||
def set_q6voiced_audio(enable):
|
||||
global audio_opened
|
||||
if enable and not audio_opened:
|
||||
audio_opened = True
|
||||
subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallAdded"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
run_user_cmd("sxmo_modemaudio.sh setup_audio")
|
||||
elif not enable and audio_opened:
|
||||
audio_opened = False
|
||||
subprocess.run(["dbus-send", "--system", "--type=signal", "/", "org.ofono.VoiceCallManager.CallRemoved"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
run_user_cmd("sxmo_modemaudio.sh reset_audio")
|
||||
|
||||
def has_sub1_call_files():
|
||||
try:
|
||||
return any(fn.startswith("sub1_") for fn in os.listdir(CALLS_DIR))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def has_mm_call_files():
|
||||
try:
|
||||
for fn in os.listdir(CALLS_DIR):
|
||||
if fn and fn[0].isdigit():
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
def is_hangup_requested():
|
||||
try:
|
||||
return (time.time() - os.path.getmtime("/tmp/sxmo_hangup_requested")) < 3.5
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def query_sec_slot(uim_addr, fallback=2):
|
||||
if not uim_addr:
|
||||
return fallback
|
||||
try:
|
||||
us = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
|
||||
ut = qmi_req(us, uim_addr, 1, 0x002F, timeout=0.08)
|
||||
us.close()
|
||||
st_val = ut.get(0x10, b"")
|
||||
if len(st_val) >= 8:
|
||||
_, _, sec_gw_idx, _ = struct.unpack("<HHHH", st_val[:8])
|
||||
if sec_gw_idx != 0xFFFF:
|
||||
return ((sec_gw_idx >> 8) & 0xFF) + 1
|
||||
except Exception:
|
||||
pass
|
||||
return fallback
|
||||
|
||||
def sync_sub1_calls(calls, sim_slot, vs=None, voice_addr=None):
|
||||
global active_calls
|
||||
now_str = datetime.datetime.now().astimezone().isoformat(timespec="seconds")
|
||||
hangup_req = is_hangup_requested()
|
||||
sent_ended = False
|
||||
|
||||
if hangup_req:
|
||||
for cid, c in list(calls.items()):
|
||||
if c["state"] not in (8, 9):
|
||||
if vs is not None and voice_addr is not None:
|
||||
try:
|
||||
qmi_req(vs, voice_addr, 55000 + (cid % 100), 0x0021, struct.pack("<BHB", 0x01, 1, cid), timeout=0.2)
|
||||
except Exception:
|
||||
pass
|
||||
c["state"] = 9
|
||||
|
||||
for old_cid, old_info in list(active_calls.items()):
|
||||
if old_cid not in calls:
|
||||
if old_info.get("state") == "terminated":
|
||||
del active_calls[old_cid]
|
||||
else:
|
||||
calls[old_cid] = {
|
||||
"id": old_cid,
|
||||
"state": 9,
|
||||
"dir": old_info.get("dir", 1),
|
||||
"num": old_info.get("num", ""),
|
||||
}
|
||||
|
||||
for cid, c in list(calls.items()):
|
||||
st = STATE_MAP.get(c["state"], "unknown")
|
||||
if st == "setup":
|
||||
if c["dir"] == 1 and has_sub1_call_files() and not hangup_req:
|
||||
st = "dialing"
|
||||
else:
|
||||
continue
|
||||
|
||||
# Skip calls that are already managed by ModemManager / sxmo_modem.sh on Primary GW
|
||||
if cid not in active_calls:
|
||||
if st == "terminated" or hangup_req:
|
||||
continue
|
||||
if c["dir"] == 1 and not has_sub1_call_files():
|
||||
continue
|
||||
if c["dir"] == 2:
|
||||
time.sleep(0.35)
|
||||
if has_mm_call_files():
|
||||
continue
|
||||
|
||||
num = c["num"] or active_calls.get(cid, {}).get("num") or "Unknown"
|
||||
if num and num != "Unknown" and not num.startswith("+") and len(num) >= 10:
|
||||
num = "+" + num
|
||||
c["num"] = num
|
||||
prev = active_calls.get(cid, {}).get("state")
|
||||
call_key = f"sub1_{cid}"
|
||||
|
||||
# Update /run/user/10000/sxmo_calls/sub1_<id>.<state>
|
||||
for fn in os.listdir(CALLS_DIR):
|
||||
if fn == "sub1_dialing.initiatedcall" or (fn.startswith(f"{call_key}.") and not fn.endswith(".initiatedcall") and not fn.endswith(".pickedupcall") and not fn.endswith(".mutedring")):
|
||||
try:
|
||||
os.remove(os.path.join(CALLS_DIR, fn))
|
||||
except Exception:
|
||||
pass
|
||||
if st != "terminated" and not hangup_req:
|
||||
try:
|
||||
open(os.path.join(CALLS_DIR, f"{call_key}.{st}"), "w").close()
|
||||
chown_user(os.path.join(CALLS_DIR, f"{call_key}.{st}"))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
for fn in os.listdir(CALLS_DIR):
|
||||
if fn.startswith(f"{call_key}."):
|
||||
try:
|
||||
os.remove(os.path.join(CALLS_DIR, fn))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if st == prev:
|
||||
continue
|
||||
active_calls[cid] = {"state": st, "num": num, "dir": c["dir"]}
|
||||
|
||||
if st == "ringing-in":
|
||||
if has_mm_call_files():
|
||||
del active_calls[cid]
|
||||
continue
|
||||
append_modemlog(f"{now_str}\tcall_ring\t{num}\t[SIM {sim_slot}]\n")
|
||||
send_fifo("/tmp/dwm_plugin_callscreen.fifo", f"INCOMING {call_key} {num} SIM{sim_slot}")
|
||||
run_user_cmd(f"sxmo_jobs.sh start --group ringing sxmo_hook_ring.sh '{num}'")
|
||||
elif st in ("dialing", "ringing-out"):
|
||||
set_q6voiced_audio(True)
|
||||
if prev not in ("dialing", "ringing-out"):
|
||||
append_modemlog(f"{now_str}\tcall_dial\t{num}\t[SIM {sim_slot}]\n")
|
||||
send_fifo("/tmp/dwm_plugin_callscreen.fifo", f"OUTGOING {call_key} {num} SIM{sim_slot}")
|
||||
elif st == "active":
|
||||
stop_ringing_user()
|
||||
set_q6voiced_audio(True)
|
||||
append_modemlog(f"{now_str}\tcall_start\t{num}\t[SIM {sim_slot}]\n")
|
||||
send_fifo("/tmp/dwm_plugin_callscreen.fifo", f"ACTIVE {call_key} {num} SIM{sim_slot}")
|
||||
elif st == "terminated":
|
||||
stop_ringing_user()
|
||||
evt = "call_missed" if prev == "ringing-in" else "call_hangup"
|
||||
append_modemlog(f"{now_str}\t{evt}\t{num}\t[SIM {sim_slot}]\n")
|
||||
if not hangup_req:
|
||||
send_fifo("/tmp/dwm_plugin_callscreen.fifo", "ENDED CALL ENDED")
|
||||
sent_ended = True
|
||||
|
||||
has_live = any(v["state"] in ("dialing", "ringing-out", "active", "held", "ringing-in", "waiting") for v in active_calls.values())
|
||||
if not has_live:
|
||||
removed_stale = False
|
||||
for fn in os.listdir(CALLS_DIR):
|
||||
if fn.startswith("sub1_"):
|
||||
try:
|
||||
os.remove(os.path.join(CALLS_DIR, fn))
|
||||
removed_stale = True
|
||||
except Exception:
|
||||
pass
|
||||
if removed_stale:
|
||||
stop_ringing_user()
|
||||
if not sent_ended and not hangup_req:
|
||||
send_fifo("/tmp/dwm_plugin_callscreen.fifo", "ENDED CALL ENDED")
|
||||
if audio_opened:
|
||||
set_q6voiced_audio(False)
|
||||
|
||||
while True:
|
||||
wms_addr = lookup_srv(QMI_SERVICE_WMS)
|
||||
voice_addr = lookup_srv(QMI_SERVICE_VOICE)
|
||||
uim_addr = lookup_srv(QMI_SERVICE_UIM)
|
||||
if not (wms_addr and voice_addr):
|
||||
time.sleep(3)
|
||||
continue
|
||||
|
||||
sec_slot = query_sec_slot(uim_addr, 2)
|
||||
|
||||
ws = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
|
||||
vs = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM)
|
||||
w_txn = 1
|
||||
v_txn = 1
|
||||
|
||||
# Bind both sockets to Secondary GW (sub = 1)
|
||||
qmi_req(ws, wms_addr, w_txn, 0x004C, struct.pack("<BHB", 0x01, 1, 1))
|
||||
w_txn += 1
|
||||
qmi_req(ws, wms_addr, w_txn, 0x0001, struct.pack("<BHB", 0x10, 1, 1))
|
||||
w_txn += 1
|
||||
# Configure WMS routes on Secondary GW (sub = 1) to match ModemManager:
|
||||
# Class 0 -> UIM + TRANSFER_AND_ACK (0x03), Class 1/2/3/None -> UIM + STORE_AND_NOTIFY (0x01)
|
||||
# so the baseband sends 3GPP RP-ACK in hardware for every multipart segment immediately.
|
||||
route_list = bytes.fromhex("060000000003000100010002000100030001000400010005ff02")
|
||||
route_tlvs = struct.pack("<BH", 0x01, len(route_list)) + route_list + struct.pack("<BHB", 0x10, 1, 0)
|
||||
qmi_req(ws, wms_addr, w_txn, 0x0032, route_tlvs)
|
||||
w_txn += 1
|
||||
|
||||
qmi_req(vs, voice_addr, v_txn, 0x0044, struct.pack("<BHB", 0x01, 1, 1))
|
||||
v_txn += 1
|
||||
# Register for Voice Call Notification Events (TLV 0x13 = 1)
|
||||
qmi_req(vs, voice_addr, v_txn, 0x0003, struct.pack("<BHB", 0x13, 1, 1))
|
||||
v_txn += 1
|
||||
|
||||
w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
|
||||
last_poll = time.time()
|
||||
|
||||
def screen_is_idle():
|
||||
if os.path.exists("/tmp/bananarchy_screen_locked") or \
|
||||
os.path.exists("/run/bananarchy/cover-backlight"):
|
||||
return True
|
||||
try:
|
||||
with open("/sys/class/backlight/backlight/bl_power", "r") as f:
|
||||
if f.read().strip() != "0":
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
with open("/sys/class/backlight/backlight/brightness", "r") as f:
|
||||
if int(f.read().strip()) <= 0:
|
||||
return True
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
try:
|
||||
while True:
|
||||
if pending_inds:
|
||||
poll_timeout = 0.0
|
||||
elif active_calls or has_sub1_call_files():
|
||||
poll_timeout = 1.0
|
||||
elif multipart_buf:
|
||||
poll_timeout = 2.0
|
||||
elif screen_is_idle():
|
||||
poll_timeout = None
|
||||
else:
|
||||
poll_timeout = 1800.0
|
||||
r, _, _ = select.select([ws, vs], [], [], poll_timeout)
|
||||
got_voice_ind = False
|
||||
events = []
|
||||
while pending_inds:
|
||||
events.append(pending_inds.pop(0))
|
||||
for sock in r:
|
||||
pkt, _ = sock.recvfrom(4096)
|
||||
events.append((sock, pkt))
|
||||
for sock, pkt in events:
|
||||
if len(pkt) < 7:
|
||||
continue
|
||||
flags, txn, mid, _ = struct.unpack("<BHHH", pkt[:7])
|
||||
if flags != 0x04:
|
||||
continue
|
||||
tlvs = parse_tlvs(pkt)
|
||||
if sock is ws and mid == 0x0001:
|
||||
sec_slot = query_sec_slot(uim_addr, sec_slot)
|
||||
# WMSEventReport indication
|
||||
if 0x11 in tlvs and len(tlvs[0x11]) >= 8:
|
||||
# Transfer-route MT message: [ack_ind(1), txn_id(4), format(1), len(2), data...]
|
||||
tr = tlvs[0x11]
|
||||
ack_ind = tr[0]
|
||||
mt_txn_id = struct.unpack("<I", tr[1:5])[0]
|
||||
dlen = struct.unpack("<H", tr[6:8])[0]
|
||||
pdu = tr[8:8+dlen]
|
||||
if ack_ind == 0:
|
||||
# Send QMI_WMS_SEND_ACK (0x0026): TLV 0x01 = [txn_id(4), protocol=1(GW), success=1], TLV 0x10 = 3GPP RP-ACK
|
||||
ack_tlvs = (
|
||||
struct.pack("<BHIBB", 0x01, 6, mt_txn_id, 1, 1)
|
||||
+ struct.pack("<BHBH", 0x10, 5, 0x00, 2)
|
||||
+ b"\x00\x00"
|
||||
)
|
||||
qmi_req(ws, wms_addr, w_txn, 0x0026, ack_tlvs)
|
||||
w_txn = (w_txn % 60000) + 1
|
||||
info = decode_sms_deliver(pdu, only_tpdu=True)
|
||||
if info:
|
||||
handle_decoded_sms(info, sec_slot)
|
||||
if 0x10 in tlvs:
|
||||
w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
|
||||
elif sock is vs and mid == 0x002E:
|
||||
# VoiceAllCallStatusIndication
|
||||
got_voice_ind = True
|
||||
sec_slot = query_sec_slot(uim_addr, sec_slot)
|
||||
calls = parse_call_info(tlvs)
|
||||
if not any(c["num"] for c in calls.values()):
|
||||
full_tlvs = qmi_req(vs, voice_addr, v_txn, 0x002F)
|
||||
v_txn = (v_txn % 60000) + 1
|
||||
full_calls = parse_call_info(full_tlvs)
|
||||
for cid, fc in full_calls.items():
|
||||
if cid in calls and fc["num"]:
|
||||
calls[cid]["num"] = fc["num"]
|
||||
sync_sub1_calls(calls, sec_slot, vs, voice_addr)
|
||||
|
||||
if multipart_buf:
|
||||
w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
|
||||
w_txn = flush_stale_multipart(ws, wms_addr, w_txn, sec_slot)
|
||||
|
||||
if not got_voice_ind and (active_calls or has_sub1_call_files()):
|
||||
sec_slot = query_sec_slot(uim_addr, sec_slot)
|
||||
full_tlvs = qmi_req(vs, voice_addr, v_txn, 0x002F)
|
||||
v_txn = (v_txn % 60000) + 1
|
||||
if full_tlvs:
|
||||
sync_sub1_calls(parse_call_info(full_tlvs), sec_slot, vs, voice_addr)
|
||||
|
||||
if not screen_is_idle() and time.time() - last_poll >= 1800.0:
|
||||
w_txn = poll_stored_sms(ws, wms_addr, w_txn, sec_slot)
|
||||
last_poll = time.time()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
ws.close()
|
||||
vs.close()
|
||||
# U9: back off after a QRTR error instead of re-registering every 2 s.
|
||||
time.sleep(30)
|
||||
PY
|
||||
exec /usr/bin/bananarchy-dsds
|
||||
;;
|
||||
|
||||
sim-contacts-import)
|
||||
|
||||
Reference in new issue
Block a user