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
@@ -16,6 +16,7 @@ KBD_PATH=/sys/class/leds/white:kbd_backlight/brightness
|
||||
RL_PATH=/sys/devices/system/cpu/cpufreq/schedutil/rate_limit_us
|
||||
GPU_GOV_PATH=/sys/class/devfreq/1c00000.gpu/governor
|
||||
WIFI_OFFLOAD_PATH=/sys/module/wcn36xx/parameters/screen_off_offload
|
||||
SPM_SCREEN_OFF_PATH=/sys/module/cpuidle_qcom_spm/parameters/screen_off
|
||||
COVER_MARKER=/run/bananarchy/cover-backlight
|
||||
FORCE_MARKER=/run/bananarchy/cover-bl-force
|
||||
STATE_CACHE=/run/bananarchy/cover-power-state
|
||||
@@ -86,7 +87,9 @@ if [ "$(read_value "$LID_PROFILE")" != "flip" ]; then
|
||||
[ -w "$GPU_GOV_PATH" ] && set_if_changed "$GPU_GOV_PATH" "powersave"
|
||||
[ -w "$WIFI_OFFLOAD_PATH" ] && set_if_changed "$WIFI_OFFLOAD_PATH" "Y"
|
||||
force_dpms "Off"
|
||||
[ -w "$SPM_SCREEN_OFF_PATH" ] && set_if_changed "$SPM_SCREEN_OFF_PATH" "Y"
|
||||
else
|
||||
[ -w "$SPM_SCREEN_OFF_PATH" ] && set_if_changed "$SPM_SCREEN_OFF_PATH" "N"
|
||||
[ -w "$GPU_GOV_PATH" ] && set_if_changed "$GPU_GOV_PATH" "simple_ondemand"
|
||||
[ -w "$WIFI_OFFLOAD_PATH" ] && set_if_changed "$WIFI_OFFLOAD_PATH" "N"
|
||||
force_dpms "On"
|
||||
@@ -180,14 +183,23 @@ else
|
||||
fi
|
||||
|
||||
[ -n "$DESIRED_KBD" ] && set_if_changed "$KBD_PATH" "$DESIRED_KBD"
|
||||
if [ "$DESIRED_DPMS" = "Off" ] || [ "$marker" = "0" ] || [ "$marker" = "1" ]; then
|
||||
if [ "$DESIRED_DPMS" = "Off" ]; then
|
||||
[ -w "$GPU_GOV_PATH" ] && set_if_changed "$GPU_GOV_PATH" "powersave"
|
||||
[ -w "$WIFI_OFFLOAD_PATH" ] && set_if_changed "$WIFI_OFFLOAD_PATH" "Y"
|
||||
else
|
||||
[ -w "$GPU_GOV_PATH" ] && set_if_changed "$GPU_GOV_PATH" "simple_ondemand"
|
||||
fi
|
||||
if [ "$DESIRED_DPMS" = "Off" ] || [ "$marker" = "0" ] || [ "$marker" = "1" ]; then
|
||||
[ -w "$WIFI_OFFLOAD_PATH" ] && set_if_changed "$WIFI_OFFLOAD_PATH" "Y"
|
||||
else
|
||||
[ -w "$WIFI_OFFLOAD_PATH" ] && set_if_changed "$WIFI_OFFLOAD_PATH" "N"
|
||||
fi
|
||||
if [ "$DESIRED_DPMS" != "Off" ]; then
|
||||
[ -w "$SPM_SCREEN_OFF_PATH" ] && set_if_changed "$SPM_SCREEN_OFF_PATH" "N"
|
||||
fi
|
||||
force_dpms "$DESIRED_DPMS"
|
||||
if [ "$DESIRED_DPMS" = "Off" ]; then
|
||||
[ -w "$SPM_SCREEN_OFF_PATH" ] && set_if_changed "$SPM_SCREEN_OFF_PATH" "Y"
|
||||
fi
|
||||
[ -w "$RL_PATH" ] && set_if_changed "$RL_PATH" "40000"
|
||||
|
||||
if [ "$FORCE" -eq 1 ]; then
|
||||
|
||||
Executable
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -10,9 +10,15 @@ PARKED="$RUNDIR/parked"
|
||||
AIDFILE="$RUNDIR/secondary.aid"
|
||||
SLOTFILE="$RUNDIR/secondary.slot"
|
||||
TOKEN="$RUNDIR/token"
|
||||
RAT_PARKED="$RUNDIR/rat_parked"
|
||||
RAT_SAVED="$RUNDIR/saved_rat"
|
||||
RAT_TOKEN="$RUNDIR/rat.token"
|
||||
IPV6_RA_SAVED="$RUNDIR/wlan0_accept_ra"
|
||||
BOOTTOKEN="$RUNDIR/boot.token"
|
||||
READYSTAMP="$RUNDIR/modem_ready.stamp"
|
||||
DRXLOCK="$RUNDIR/lock.drx"
|
||||
ACCEPT_RA=/proc/sys/net/ipv6/conf/wlan0/accept_ra
|
||||
SPM_PARAM_DIR=/sys/module/cpuidle_qcom_spm/parameters
|
||||
QMI="timeout 8 qmicli --silent -pd qrtr://0"
|
||||
|
||||
if [ "$(id -u)" != "0" ]; then
|
||||
@@ -23,6 +29,10 @@ WIFI_LISTEN_INTERVAL=5
|
||||
MODEM_DRX_MODE=6
|
||||
DSDS_SECONDARY_MODE=active
|
||||
DSDS_PARK_DELAY=300
|
||||
CPU_RPM_SLEEP=1
|
||||
CPU_L2_SLEEP=1
|
||||
WIFI_SCREEN_OFF_IPV6_MUTE=1
|
||||
WIFI_STANDBY_RAT=keep
|
||||
[ -r "$CONF" ] && . "$CONF"
|
||||
|
||||
mkdir -p "$RUNDIR" 2>/dev/null || true
|
||||
@@ -153,8 +163,95 @@ unpark() {
|
||||
rm -f "$PARKED" "$AIDFILE" "$SLOTFILE" "$RUNDIR"/drx.wwan* 2>/dev/null || true
|
||||
}
|
||||
|
||||
set_spm_bool() {
|
||||
path="$1"
|
||||
val="$2"
|
||||
[ -w "$path" ] || return 0
|
||||
case "$val" in
|
||||
1|Y|y) want="Y" ;;
|
||||
0|N|n) want="N" ;;
|
||||
*) return 0 ;;
|
||||
esac
|
||||
printf '%s\n' "$want" > "$path" 2>/dev/null || true
|
||||
}
|
||||
|
||||
apply_cpu_lpm() {
|
||||
set_spm_bool "$SPM_PARAM_DIR/rpm_sleep" "$CPU_RPM_SLEEP"
|
||||
set_spm_bool "$SPM_PARAM_DIR/l2_sleep" "$CPU_L2_SLEEP"
|
||||
}
|
||||
|
||||
mute_wifi_ipv6_ra() {
|
||||
[ "$WIFI_SCREEN_OFF_IPV6_MUTE" = "1" ] || return 0
|
||||
[ -w "$ACCEPT_RA" ] || return 0
|
||||
ip -4 addr show dev wlan0 2>/dev/null | grep -q 'inet ' || return 0
|
||||
if [ ! -f "$IPV6_RA_SAVED" ]; then
|
||||
cur_ra=""
|
||||
IFS= read -r cur_ra < "$ACCEPT_RA" 2>/dev/null || cur_ra=""
|
||||
case "$cur_ra" in ''|*[!0-9]*) cur_ra=1 ;; esac
|
||||
printf '%s\n' "$cur_ra" > "$IPV6_RA_SAVED" 2>/dev/null || true
|
||||
fi
|
||||
printf '0\n' > "$ACCEPT_RA" 2>/dev/null || true
|
||||
}
|
||||
|
||||
restore_wifi_ipv6_ra() {
|
||||
[ -f "$IPV6_RA_SAVED" ] || return 0
|
||||
saved_ra=1
|
||||
IFS= read -r saved_ra < "$IPV6_RA_SAVED" 2>/dev/null || saved_ra=1
|
||||
case "$saved_ra" in ''|*[!0-9]*) saved_ra=1 ;; esac
|
||||
[ -w "$ACCEPT_RA" ] && printf '%s\n' "$saved_ra" > "$ACCEPT_RA" 2>/dev/null || true
|
||||
rm -f "$IPV6_RA_SAVED" 2>/dev/null || true
|
||||
}
|
||||
|
||||
park_wifi_rat() {
|
||||
[ "$WIFI_STANDBY_RAT" = "gsm" ] || return 0
|
||||
[ -f "$RAT_PARKED" ] && return 0
|
||||
oper=""
|
||||
[ -r /sys/class/net/wlan0/operstate ] && { IFS= read -r oper < /sys/class/net/wlan0/operstate 2>/dev/null || oper=""; }
|
||||
[ "$oper" = "up" ] || return 0
|
||||
saved_rat="$($QMI --nas-get-system-selection-preference 2>/dev/null | awk -F"'" '
|
||||
/Mode preference:/ { gsub(/[[:space:]]*,[[:space:]]*/, "|", $2); print $2; exit }
|
||||
')"
|
||||
[ -n "$saved_rat" ] || saved_rat="gsm|umts|lte"
|
||||
[ "$saved_rat" = "gsm" ] && return 0
|
||||
printf '%s\n' "$saved_rat" > "$RAT_SAVED" 2>/dev/null || true
|
||||
if $QMI --nas-set-system-selection-preference='gsm' >/dev/null 2>&1; then
|
||||
: > "$RAT_PARKED"
|
||||
log "Wi-Fi standby RAT parked to gsm (saved: $saved_rat)"
|
||||
return 0
|
||||
fi
|
||||
rm -f "$RAT_SAVED" 2>/dev/null || true
|
||||
log "failed to park Wi-Fi standby RAT to gsm"
|
||||
return 1
|
||||
}
|
||||
|
||||
unpark_wifi_rat() {
|
||||
[ -f "$RAT_PARKED" ] || return 0
|
||||
saved_rat=""
|
||||
[ -r "$RAT_SAVED" ] && { IFS= read -r saved_rat < "$RAT_SAVED" 2>/dev/null || saved_rat=""; }
|
||||
[ -n "$saved_rat" ] || saved_rat="gsm|umts|lte"
|
||||
if $QMI --nas-set-system-selection-preference="$saved_rat" >/dev/null 2>&1; then
|
||||
log "Wi-Fi standby RAT restored ($saved_rat)"
|
||||
else
|
||||
log "failed to restore Wi-Fi standby RAT ($saved_rat)"
|
||||
fi
|
||||
rm -f "$RAT_PARKED" "$RAT_SAVED" 2>/dev/null || true
|
||||
}
|
||||
|
||||
screenoff() {
|
||||
apply_cpu_lpm
|
||||
mute_wifi_ipv6_ra
|
||||
apply_modem_drx cached || true
|
||||
if [ "$WIFI_STANDBY_RAT" = "gsm" ]; then
|
||||
rtok="$(date +%s)-$$"
|
||||
printf '%s\n' "$rtok" > "$RAT_TOKEN"
|
||||
(
|
||||
sleep 30
|
||||
cur=""
|
||||
[ -r "$RAT_TOKEN" ] && { read -r cur < "$RAT_TOKEN" 2>/dev/null || cur=""; }
|
||||
[ "$cur" = "$rtok" ] || exit 0
|
||||
"$0" _park_rat >/dev/null 2>&1
|
||||
) &
|
||||
fi
|
||||
[ "$DSDS_SECONDARY_MODE" = "eco" ] || return 0
|
||||
token="$(date +%s)-$$"
|
||||
printf '%s\n' "$token" > "$TOKEN"
|
||||
@@ -168,7 +265,11 @@ screenoff() {
|
||||
}
|
||||
|
||||
screenon() {
|
||||
rm -f "$TOKEN" 2>/dev/null || true
|
||||
rm -f "$TOKEN" "$RAT_TOKEN" 2>/dev/null || true
|
||||
set_spm_bool "$SPM_PARAM_DIR/screen_off" 0
|
||||
apply_cpu_lpm
|
||||
restore_wifi_ipv6_ra
|
||||
unpark_wifi_rat
|
||||
unpark
|
||||
apply_modem_drx cached || true
|
||||
}
|
||||
@@ -176,6 +277,9 @@ screenon() {
|
||||
apply_now() {
|
||||
rm -f "$BOOTTOKEN" "$READYSTAMP" "$RUNDIR"/drx.wwan* 2>/dev/null || true
|
||||
write_modprobe || true
|
||||
apply_cpu_lpm
|
||||
[ "$WIFI_SCREEN_OFF_IPV6_MUTE" = "1" ] || restore_wifi_ipv6_ra
|
||||
[ "$WIFI_STANDBY_RAT" = "gsm" ] || unpark_wifi_rat
|
||||
apply_modem_drx force || true
|
||||
}
|
||||
|
||||
@@ -198,8 +302,9 @@ modem_ready() {
|
||||
}
|
||||
|
||||
boot() {
|
||||
rm -f "$TOKEN" "$PARKED" "$AIDFILE" "$SLOTFILE" "$READYSTAMP" "$RUNDIR"/drx.wwan* 2>/dev/null || true
|
||||
rm -f "$TOKEN" "$RAT_TOKEN" "$PARKED" "$AIDFILE" "$SLOTFILE" "$RAT_PARKED" "$RAT_SAVED" "$IPV6_RA_SAVED" "$READYSTAMP" "$RUNDIR"/drx.wwan* 2>/dev/null || true
|
||||
write_modprobe || true
|
||||
apply_cpu_lpm
|
||||
btok="$$-$(cat /proc/uptime 2>/dev/null | awk '{print $1}' || echo 0)"
|
||||
printf '%s\n' "$btok" > "$BOOTTOKEN"
|
||||
(
|
||||
@@ -223,16 +328,37 @@ boot() {
|
||||
) >/dev/null 2>&1 &
|
||||
}
|
||||
|
||||
debugfs_summary() {
|
||||
dir="$1"
|
||||
[ -d "$dir" ] || { printf 'n/a'; return 0; }
|
||||
out=""
|
||||
for f in "$dir"/*; do
|
||||
[ -r "$f" ] || continue
|
||||
val="$(tr '\n\t' ' ' < "$f" 2>/dev/null | awk '{$1=$1; print}')"
|
||||
[ -n "$val" ] && out="${out:+$out; }${f##*/}: $val"
|
||||
done
|
||||
printf '%s' "${out:-n/a}"
|
||||
}
|
||||
|
||||
status() {
|
||||
printf 'WIFI_LISTEN_INTERVAL=%s\n' "$WIFI_LISTEN_INTERVAL"
|
||||
printf 'MODEM_DRX_MODE=%s\n' "$MODEM_DRX_MODE"
|
||||
printf 'DSDS_SECONDARY_MODE=%s\n' "$DSDS_SECONDARY_MODE"
|
||||
printf 'DSDS_PARK_DELAY=%s\n' "$DSDS_PARK_DELAY"
|
||||
printf 'CPU_RPM_SLEEP=%s\n' "$CPU_RPM_SLEEP"
|
||||
printf 'CPU_L2_SLEEP=%s\n' "$CPU_L2_SLEEP"
|
||||
printf 'WIFI_SCREEN_OFF_IPV6_MUTE=%s\n' "$WIFI_SCREEN_OFF_IPV6_MUTE"
|
||||
printf 'WIFI_STANDBY_RAT=%s\n' "$WIFI_STANDBY_RAT"
|
||||
if [ -f "$PARKED" ]; then
|
||||
printf 'secondary_parked=yes\n'
|
||||
else
|
||||
printf 'secondary_parked=no\n'
|
||||
fi
|
||||
if [ -f "$RAT_PARKED" ]; then
|
||||
printf 'rat_parked=yes\n'
|
||||
else
|
||||
printf 'rat_parked=no\n'
|
||||
fi
|
||||
if [ -r "$MODPROBE" ]; then
|
||||
printf 'modprobe_conf=%s (%s)\n' "$MODPROBE" "$(tail -n 1 "$MODPROBE")"
|
||||
else
|
||||
@@ -240,6 +366,14 @@ status() {
|
||||
fi
|
||||
printf 'wcn36xx_param=%s\n' "$(cat /sys/module/wcn36xx/parameters/listen_interval 2>/dev/null || echo n/a)"
|
||||
printf 'wcn36xx_screen_off_offload=%s\n' "$(cat /sys/module/wcn36xx/parameters/screen_off_offload 2>/dev/null || echo n/a)"
|
||||
printf 'cpuidle_rpm_sleep=%s\n' "$(cat "$SPM_PARAM_DIR/rpm_sleep" 2>/dev/null || echo n/a)"
|
||||
printf 'cpuidle_l2_sleep=%s\n' "$(cat "$SPM_PARAM_DIR/l2_sleep" 2>/dev/null || echo n/a)"
|
||||
printf 'cpuidle_screen_off=%s\n' "$(cat "$SPM_PARAM_DIR/screen_off" 2>/dev/null || echo n/a)"
|
||||
printf 'cpuidle_rpm_sleep_count=%s\n' "$(cat "$SPM_PARAM_DIR/rpm_sleep_count" 2>/dev/null || echo n/a)"
|
||||
printf 'cpuidle_l2_off_count=%s\n' "$(cat "$SPM_PARAM_DIR/l2_off_count" 2>/dev/null || echo n/a)"
|
||||
printf 'wlan0_accept_ra=%s\n' "$(cat "$ACCEPT_RA" 2>/dev/null || echo n/a)"
|
||||
printf 'qcom_stats=%s\n' "$(debugfs_summary /sys/kernel/debug/qcom_stats)"
|
||||
printf 'qcom_rpm_master_stats=%s\n' "$(debugfs_summary /sys/kernel/debug/qcom_rpm_master_stats)"
|
||||
drx_summary="$(timeout 8 /usr/libexec/msm-modem-uim-selection at all 'AT$QCDRX?' 2>/dev/null | awk '
|
||||
/^\[wwan0at/ { gsub(/[\[\]]/, "", $0); p=$0; next }
|
||||
/\$QCDRX:/ { gsub(/^[[:space:]]+|[[:space:]]+$/, "", $0); if (p != "") out = (out ? out " " : "") p ":" $0 }
|
||||
@@ -255,7 +389,8 @@ case "${1:-}" in
|
||||
screenoff) screenoff ;;
|
||||
screenon) screenon ;;
|
||||
_park) park ;;
|
||||
unpark) unpark ;;
|
||||
_park_rat) park_wifi_rat ;;
|
||||
unpark) restore_wifi_ipv6_ra; unpark_wifi_rat; unpark ;;
|
||||
status) status ;;
|
||||
*)
|
||||
printf 'Usage: %s [boot|apply|modem-ready|screenoff|screenon|unpark|status]\n' "${0##*/}" >&2
|
||||
|
||||
BIN
Binary file not shown.
BIN
Binary file not shown.
BIN
Binary file not shown.
@@ -201,50 +201,4 @@ fi
|
||||
fi
|
||||
) &
|
||||
|
||||
first_iter=1
|
||||
while [ "$(cat "$SESSION_PID_FILE" 2>/dev/null)" = "$$" ]; do
|
||||
if pidof -s dwm >/dev/null 2>&1; then
|
||||
exit 0
|
||||
fi
|
||||
# U14: skip X resource/wallpaper work when the panel is powered down.
|
||||
_dark=0
|
||||
if [ -r /sys/class/backlight/backlight/brightness ]; then
|
||||
_bl=1
|
||||
read -r _bl < /sys/class/backlight/backlight/brightness 2>/dev/null || _bl=1
|
||||
[ "${_bl:-1}" = "0" ] && _dark=1
|
||||
fi
|
||||
if [ "$_dark" = "0" ]; then
|
||||
xrdb -merge "$HOME/.Xresources" >/dev/null 2>&1 || true
|
||||
/usr/bin/bananarchy-sync-dunst-theme --no-restart >/dev/null 2>&1 || true
|
||||
fi
|
||||
WP_FILE="/usr/share/wallpapers/bananarchy.png"
|
||||
if [ -f "$XDG_CONFIG_HOME/sxmo/wallpaper" ]; then
|
||||
custom_wp="$(head -n 1 "$XDG_CONFIG_HOME/sxmo/wallpaper" 2>/dev/null)"
|
||||
[ -n "$custom_wp" ] && [ -f "$custom_wp" ] && WP_FILE="$custom_wp"
|
||||
fi
|
||||
WP_FLAG="--bg-fill"
|
||||
if [ -f "$XDG_CONFIG_HOME/sxmo/wallpaper_mode" ]; then
|
||||
wp_mode="$(head -n 1 "$XDG_CONFIG_HOME/sxmo/wallpaper_mode" 2>/dev/null)"
|
||||
case "$wp_mode" in
|
||||
scale|--bg-scale) WP_FLAG="--bg-scale" ;;
|
||||
max|--bg-max) WP_FLAG="--bg-max" ;;
|
||||
center|--bg-center) WP_FLAG="--bg-center" ;;
|
||||
tile|--bg-tile) WP_FLAG="--bg-tile" ;;
|
||||
*) WP_FLAG="--bg-fill" ;;
|
||||
esac
|
||||
fi
|
||||
if [ "$_dark" = "0" ]; then ( feh --no-fehbg "$WP_FLAG" "$WP_FILE" >/dev/null 2>&1 </dev/null & ); fi
|
||||
if [ "$first_iter" = "0" ]; then
|
||||
pidof -s fcitx5 >/dev/null 2>&1 || superctl start fcitx5 >/dev/null 2>&1 || ( /usr/bin/bananarchy-fcitx5.sh </dev/null & )
|
||||
fi
|
||||
first_iter=0
|
||||
if [ -f /tmp/bananarchy_ext_logging ]; then
|
||||
dwm >/tmp/dwm.log 2>&1 || true
|
||||
else
|
||||
dwm >/dev/null 2>&1 || true
|
||||
fi
|
||||
if [ "$(cat "$SESSION_PID_FILE" 2>/dev/null)" != "$$" ] || pidof -s dwm >/dev/null 2>&1; then
|
||||
exit 0
|
||||
fi
|
||||
sleep 0.2
|
||||
done
|
||||
exec /usr/bin/bananarchy-session-loop "$SESSION_PID_FILE"
|
||||
@@ -1,182 +1,2 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Copyright 2022 Sxmo Contributors
|
||||
|
||||
# include common definitions
|
||||
# shellcheck source=scripts/core/sxmo_common.sh
|
||||
. sxmo_common.sh
|
||||
|
||||
# see networkmanager documentation for these state names
|
||||
statenumtoname() {
|
||||
case "$1" in
|
||||
"int32 -1") printf "failed" ;;
|
||||
"int32 0") printf "unknown" ;;
|
||||
"int32 1") printf "initializing" ;;
|
||||
"int32 2") printf "locked" ;;
|
||||
"int32 3") printf "disabled" ;;
|
||||
"int32 4") printf "disabling" ;;
|
||||
"int32 5") printf "enabling" ;;
|
||||
"int32 6") printf "enabled" ;;
|
||||
"int32 7") printf "searching" ;;
|
||||
"int32 8") printf "registered" ;;
|
||||
"int32 9") printf "disconnecting" ;;
|
||||
"int32 10") printf "connecting" ;;
|
||||
"int32 11") printf "connected" ;;
|
||||
*) printf "ERROR" ;;
|
||||
esac
|
||||
}
|
||||
|
||||
mainloop() {
|
||||
# get initial modem state and handle SIM2/QMI PIN lock or unprovisioned slot
|
||||
(
|
||||
tries=0
|
||||
newstate=""
|
||||
while [ "$tries" -lt 15 ]; do
|
||||
newstate="$(mmcli -m any -K 2>/dev/null | grep "^modem.generic.state " | cut -d':' -f2 | sed 's/^ //')"
|
||||
if [ -n "$newstate" ]; then
|
||||
break
|
||||
fi
|
||||
sleep 2
|
||||
tries=$((tries + 1))
|
||||
done
|
||||
|
||||
uim_st="$(doas -n /usr/libexec/msm-modem-uim-selection status 2>/dev/null || /usr/libexec/msm-modem-uim-selection status 2>/dev/null || true)"
|
||||
if printf "%s\n" "$uim_st" | grep -qE "SLOT[12]_PIN1_STATE=(enabled-not-verified|blocked)|SLOT[12]_APP_STATE=(pin1|puk1)"; then
|
||||
newstate="locked"
|
||||
elif [ "$newstate" = "locked" ] && printf "%s\n" "$uim_st" | grep -q "^MODEM_AVAILABLE=1$"; then
|
||||
newstate="$(mmcli -m any -K 2>/dev/null | grep "^modem.generic.state " | cut -d':' -f2 | sed 's/^ //')"
|
||||
if [ "$newstate" = "locked" ]; then
|
||||
newstate="disabled"
|
||||
fi
|
||||
elif printf "%s\n" "$uim_st" | grep -qE "SLOT[12]_STATE=present" && printf "%s\n" "$uim_st" | grep -q "^PRIMARY_GW_SLOT=0$"; then
|
||||
doas -n /usr/libexec/msm-modem-uim-selection boot >/dev/null 2>&1 || true
|
||||
newstate="$(mmcli -m any -K 2>/dev/null | grep "^modem.generic.state " | cut -d':' -f2 | sed 's/^ //')"
|
||||
elif printf "%s\n" "$uim_st" | grep -q "^SLOT1_STATE=present$" && printf "%s\n" "$uim_st" | grep -q "^SLOT2_STATE=present$" && printf "%s\n" "$uim_st" | grep -q "^SECONDARY_GW_SLOT=0$"; then
|
||||
doas -n /usr/libexec/msm-modem-uim-selection boot >/dev/null 2>&1 || true
|
||||
fi
|
||||
|
||||
if [ -n "$newstate" ]; then
|
||||
# fake oldstate (boot) and reason (0)
|
||||
sxmo_hook_modem.sh "boot" "$newstate" "0"
|
||||
sxmo_hook_statusbar.sh modem
|
||||
fi
|
||||
) &
|
||||
|
||||
# Monitor Secondary GW SIM calls and SMS in Dual-SIM Dual Standby (DSDS)
|
||||
(
|
||||
sleep 4
|
||||
if [ ! -f /tmp/sxmo_dsds_active ]; then
|
||||
doas -n /usr/libexec/msm-modem-uim-selection status >/dev/null 2>&1 || /usr/libexec/msm-modem-uim-selection status >/dev/null 2>&1 || true
|
||||
fi
|
||||
while : ; do
|
||||
if [ "$(cat /tmp/sxmo_dsds_active 2>/dev/null || echo 0)" = "1" ]; then
|
||||
if command -v doas >/dev/null 2>&1; then
|
||||
doas -n /usr/libexec/msm-modem-uim-selection dsds-daemon 2>/dev/null || true
|
||||
else
|
||||
/usr/libexec/msm-modem-uim-selection dsds-daemon 2>/dev/null || true
|
||||
fi
|
||||
sleep 30
|
||||
else
|
||||
sleep 600
|
||||
fi
|
||||
done
|
||||
) &
|
||||
|
||||
# Monitor ModemManager signals using a single dbus-monitor connection
|
||||
dbus-monitor --system \
|
||||
"interface='org.freedesktop.ModemManager1.Modem.Voice',type='signal',member='CallAdded'" \
|
||||
"interface='org.freedesktop.ModemManager1.Modem.Messaging',type='signal',member='Added'" \
|
||||
"interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.freedesktop.ModemManager1.Sms'" \
|
||||
"interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.freedesktop.ModemManager1.Call'" \
|
||||
"interface='org.freedesktop.ModemManager1.Modem',type='signal',member='StateChanged'" \
|
||||
"interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.freedesktop.ModemManager1.Modem.Modem3gpp.Ussd'" |
|
||||
while read -r line; do
|
||||
case "$line" in
|
||||
signal*"interface=org.freedesktop.ModemManager1.Modem.Voice"*"member=CallAdded"*)
|
||||
( sxmo_modem.sh checkforincomingcalls & )
|
||||
;;
|
||||
signal*"interface=org.freedesktop.ModemManager1.Modem.Messaging"*"member=Added"*)
|
||||
( sxmo_modem.sh checkfornewtexts & )
|
||||
;;
|
||||
signal*"path=/org/freedesktop/ModemManager1/SMS/"*"member=PropertiesChanged"*)
|
||||
( sxmo_modem.sh checkfornewtexts & )
|
||||
;;
|
||||
signal*"path=/org/freedesktop/ModemManager1/Call/"*"member=PropertiesChanged"*)
|
||||
( sxmo_modem.sh checkforfinishedcalls & )
|
||||
;;
|
||||
signal*"interface=org.freedesktop.ModemManager1.Modem;"*"member=StateChanged"*)
|
||||
read -r oldstate || true
|
||||
read -r newstate || true
|
||||
read -r reason || true
|
||||
(
|
||||
(
|
||||
sxmo_hook_modem.sh "$(statenumtoname "$oldstate")" \
|
||||
"$(statenumtoname "$newstate")" \
|
||||
"$(echo "$reason" | sed 's/uint32 //')"
|
||||
sxmo_hook_statusbar.sh modem
|
||||
) &
|
||||
)
|
||||
;;
|
||||
signal*"path=/org/freedesktop/ModemManager1/Modem/"*"member=PropertiesChanged"*)
|
||||
MODEM="$(echo "$line" | awk -F'[;=]' '{print $6}')"
|
||||
;;
|
||||
*"string \"NetworkNotification\""*)
|
||||
[ -n "${MODEM:-}" ] && ( sxmo_ussd.sh "$MODEM" "NetworkNotification" "" & )
|
||||
;;
|
||||
*"string \"NetworkRequest\""*)
|
||||
[ -n "${MODEM:-}" ] && ( sxmo_ussd.sh "$MODEM" "NetworkRequest" "" & )
|
||||
;;
|
||||
esac
|
||||
done &
|
||||
|
||||
if [ -f "${SXMO_MMS_BASE_DIR:-"$HOME"/.mms/modemmanager}/mms" ]; then
|
||||
# monitor for received mms
|
||||
dbus-monitor "interface='org.ofono.mms.Service',type='signal',member='MessageAdded'" |
|
||||
while read -r line; do
|
||||
if echo "$line" | grep -q '^object path'; then
|
||||
MESSAGE_PATH="$(echo "$line" | cut -d\" -f2)"
|
||||
fi
|
||||
if echo "$line" | grep -q 'string "received"'; then
|
||||
sxmo_mms.sh processmms "$MESSAGE_PATH"
|
||||
fi
|
||||
done &
|
||||
fi
|
||||
|
||||
if [ -f "${SXMO_VVM_BASE_DIR:-"$HOME"/.vvm/modemmanager}/vvm" ]; then
|
||||
# monitor for vvm (Visual Voice Mail)
|
||||
VVM_START=0
|
||||
dbus-monitor "interface='org.kop316.vvm.Service',type='signal',member='MessageAdded'" |
|
||||
while read -r line; do
|
||||
if echo "$line" | grep -q '^object path'; then
|
||||
VVM_ID="$(echo "$line" | cut -d\" -f2 | rev | cut -d'/' -f1 | rev)"
|
||||
VVM_START=1
|
||||
fi
|
||||
|
||||
if echo "$line" | grep -q '^]'; then
|
||||
VVM_START=0
|
||||
sxmo_vvm.sh processvvm "$VVM_DATE" "$VVM_SENDER" "$VVM_ID" "$VVM_ATTACHMENT"
|
||||
fi
|
||||
|
||||
if [ "$VVM_START" -eq 1 ]; then
|
||||
if echo "$line" | grep -q '^string "Date"'; then
|
||||
read -r line
|
||||
VVM_DATE="$(echo "$line" | cut -d\" -f2)"
|
||||
elif echo "$line" | grep -q '^string "Sender"'; then
|
||||
read -r line
|
||||
VVM_SENDER="$(echo "$line" | cut -d\" -f2)"
|
||||
elif echo "$line" | grep -q '^string "Attachments"'; then
|
||||
read -r line
|
||||
VVM_ATTACHMENT="$(echo "$line" | cut -d\" -f2)"
|
||||
fi
|
||||
fi
|
||||
done &
|
||||
fi
|
||||
|
||||
wait
|
||||
}
|
||||
|
||||
# new session, clean up all phone related files
|
||||
rm "$XDG_RUNTIME_DIR/sxmo_calls/"* 2>/dev/null || true
|
||||
rm -f "$XDG_RUNTIME_DIR"/sxmo.ring.pid 2>/dev/null
|
||||
rm -f "$SXMO_NOTIFDIR"/incomingcall* 2>/dev/null
|
||||
mainloop
|
||||
exec /usr/bin/bananarchy-modemmonitor "$@"
|
||||
@@ -23,7 +23,7 @@ clear_all() {
|
||||
rm -f "$SXMO_NOTIFDIR"/* 2>/dev/null || true
|
||||
dunstctl close-all >/dev/null 2>&1 || true
|
||||
dunstctl history-clear >/dev/null 2>&1 || true
|
||||
pkill -x dunstify >/dev/null 2>&1 || true
|
||||
killall -q dunstify >/dev/null 2>&1 || true
|
||||
sxmo_hook_statusbar.sh notifications >/dev/null 2>&1 || true
|
||||
}
|
||||
|
||||
@@ -73,34 +73,7 @@ _notifications_hook() {
|
||||
}
|
||||
|
||||
monitor() {
|
||||
mkdir -p "$SXMO_NOTIFDIR"
|
||||
|
||||
find "$SXMO_NOTIFDIR" -type f 2>/dev/null | while read -r file; do
|
||||
_handle_new_notif_file "$file" "boot"
|
||||
done
|
||||
|
||||
_notifications_hook
|
||||
|
||||
fifo="$(mktemp -u)"
|
||||
mkfifo "$fifo"
|
||||
inotifywait -mq -e close_write,moved_to,delete "$SXMO_NOTIFDIR" >> "$fifo" &
|
||||
inotif_pid=$!
|
||||
|
||||
finish() {
|
||||
kill "$inotif_pid" 2>/dev/null || true
|
||||
rm -f "$fifo"
|
||||
exit
|
||||
}
|
||||
trap 'finish' TERM INT EXIT
|
||||
|
||||
while read -r notif_folder notif_type notif_file; do
|
||||
if echo "$notif_type" | grep -qE "CLOSE_WRITE|MOVED_TO"; then
|
||||
_handle_new_notif_file "$notif_folder$notif_file"
|
||||
fi
|
||||
_notifications_hook
|
||||
done < "$fifo"
|
||||
|
||||
wait "$inotif_pid"
|
||||
exec /usr/bin/bananarchy-notifmonitor
|
||||
}
|
||||
|
||||
_menu_lines() {
|
||||
@@ -200,7 +173,8 @@ new() {
|
||||
printf "%s\n%s\n%b\n" "$group" "$action" "$msg" > "$tmp_notif"
|
||||
mv -f "$tmp_notif" "$SXMO_NOTIFDIR/$id"
|
||||
|
||||
if ! pgrep -f "sxmo_notifs.sh monitor" >/dev/null 2>&1; then
|
||||
if ! pidof -s bananarchy-notifmonitor >/dev/null 2>&1 && \
|
||||
! pgrep -f "sxmo_notifs.sh monitor" >/dev/null 2>&1; then
|
||||
sxmo_hook_notification.sh "$SXMO_NOTIFDIR/$id" &
|
||||
fi
|
||||
|
||||
|
||||
Executable
+2
@@ -0,0 +1,2 @@
|
||||
#!/bin/sh
|
||||
exec /usr/bin/bananarchy-run-aligned "$@"
|
||||
@@ -1,185 +1,2 @@
|
||||
#!/bin/sh
|
||||
# SPDX-License-Identifier: AGPL-3.0-only
|
||||
# Copyright 2023 Sxmo Contributors
|
||||
|
||||
# shellcheck source=scripts/core/sxmo_common.sh
|
||||
. "$(dirname "$0")/sxmo_common.sh"
|
||||
|
||||
find_jack_event_dev() {
|
||||
for sysname in /sys/class/input/event*/device/name; do
|
||||
[ -r "$sysname" ] || continue
|
||||
read -r dname < "$sysname" 2>/dev/null || continue
|
||||
case "$dname" in
|
||||
*[Jj]ack*|*[Hh]eadset*)
|
||||
ev="${sysname%/device/name}"
|
||||
ev="/dev/input/${ev##*/}"
|
||||
if [ -c "$ev" ]; then
|
||||
printf "%s\n" "$ev"
|
||||
return 0
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
return 1
|
||||
}
|
||||
|
||||
is_hp_plugged() {
|
||||
jdev="$1"
|
||||
if [ -n "$jdev" ] && command -v evtest >/dev/null 2>&1; then
|
||||
evtest --query "$jdev" EV_SW SW_HEADPHONE_INSERT >/dev/null 2>&1
|
||||
rc=$?
|
||||
[ "$rc" -eq 10 ] && return 0
|
||||
fi
|
||||
if command -v amixer >/dev/null 2>&1; then
|
||||
amixer -c 0 cget "name='Headphone Jack'" 2>/dev/null | grep -q ": values=on" && return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
is_mic_plugged() {
|
||||
jdev="$1"
|
||||
if [ -n "$jdev" ] && command -v evtest >/dev/null 2>&1; then
|
||||
evtest --query "$jdev" EV_SW SW_MICROPHONE_INSERT >/dev/null 2>&1
|
||||
rc=$?
|
||||
[ "$rc" -eq 10 ] && return 0
|
||||
fi
|
||||
if command -v amixer >/dev/null 2>&1; then
|
||||
amixer -c 0 cget "name='Mic Jack'" 2>/dev/null | grep -q ": values=on" && return 0
|
||||
fi
|
||||
return 1
|
||||
}
|
||||
|
||||
handle_jack_insert() {
|
||||
jdev="$1"
|
||||
cur_out="$(sxmo_audio.sh device get 2>/dev/null || printf "Speaker")"
|
||||
if [ "$cur_out" != "Headphones" ]; then
|
||||
printf "%s\n" "$cur_out" > /tmp/sxmo_prev_out_device 2>/dev/null || true
|
||||
fi
|
||||
printf "1\n" > /tmp/sxmo_jack_plugged 2>/dev/null || true
|
||||
if is_mic_plugged "$jdev"; then
|
||||
printf "Headset\n" > /tmp/sxmo_audio_in_device 2>/dev/null || true
|
||||
sxmo_audio.sh device setinput Headset >/dev/null 2>&1 || true
|
||||
else
|
||||
printf "Mic1\n" > /tmp/sxmo_audio_in_device 2>/dev/null || true
|
||||
fi
|
||||
sxmo_audio.sh device set Headphones >/dev/null 2>&1 || true
|
||||
sxmo_log "Wired headphones plugged in -> routed audio to Headphones"
|
||||
}
|
||||
|
||||
handle_jack_remove() {
|
||||
printf "0\n" > /tmp/sxmo_jack_plugged 2>/dev/null || true
|
||||
printf "Mic1\n" > /tmp/sxmo_audio_in_device 2>/dev/null || true
|
||||
sxmo_audio.sh device setinput Mic1 >/dev/null 2>&1 || true
|
||||
target_out="Speaker"
|
||||
if [ -r /tmp/sxmo_in_call ]; then
|
||||
read -r incall < /tmp/sxmo_in_call 2>/dev/null || incall=0
|
||||
if [ "$incall" = "1" ]; then
|
||||
target_out="Earpiece"
|
||||
fi
|
||||
fi
|
||||
sxmo_audio.sh device set "$target_out" >/dev/null 2>&1 || true
|
||||
sxmo_log "Wired headphones unplugged -> routed audio to $target_out"
|
||||
}
|
||||
|
||||
monitor_jack_events() {
|
||||
while : ; do
|
||||
jdev="$(find_jack_event_dev || true)"
|
||||
if [ -z "$jdev" ] || ! command -v evtest >/dev/null 2>&1; then
|
||||
sleep 5
|
||||
continue
|
||||
fi
|
||||
|
||||
if is_hp_plugged "$jdev"; then
|
||||
handle_jack_insert "$jdev"
|
||||
else
|
||||
printf "0\n" > /tmp/sxmo_jack_plugged 2>/dev/null || true
|
||||
if [ -n "$(pactl list short sinks 2>/dev/null | awk '$2 ~ /^bluez_output\./ { print $2; exit }')" ]; then
|
||||
sxmo_audio.sh device set Bluetooth >/dev/null 2>&1 || true
|
||||
else
|
||||
sxmo_audio.sh device apply >/dev/null 2>&1 || true
|
||||
fi
|
||||
fi
|
||||
|
||||
evtest "$jdev" 2>/dev/null | while read -r line; do
|
||||
case "$line" in
|
||||
*SW_HEADPHONE_INSERT*value\ 1*)
|
||||
sleep 0.1
|
||||
handle_jack_insert "$jdev"
|
||||
;;
|
||||
*SW_HEADPHONE_INSERT*value\ 0*)
|
||||
handle_jack_remove
|
||||
;;
|
||||
*SW_MICROPHONE_INSERT*value\ 1*)
|
||||
sxmo_audio.sh device setinput Headset >/dev/null 2>&1 || true
|
||||
;;
|
||||
*SW_MICROPHONE_INSERT*value\ 0*)
|
||||
sxmo_audio.sh device setinput Mic1 >/dev/null 2>&1 || true
|
||||
;;
|
||||
esac
|
||||
done
|
||||
sleep 2
|
||||
done
|
||||
}
|
||||
|
||||
handle_change() {
|
||||
prev_bt_sink="$(pactl list short sinks 2>/dev/null | awk '$2 ~ /^bluez_output\./ { print $2; exit }')"
|
||||
if [ -n "$prev_bt_sink" ]; then
|
||||
cur_out="$(cat /tmp/sxmo_audio_out_device 2>/dev/null || true)"
|
||||
if [ "$cur_out" != "Bluetooth" ]; then
|
||||
sxmo_audio.sh device set Bluetooth >/dev/null 2>&1 || true
|
||||
else
|
||||
sxmo_audio.sh device apply >/dev/null 2>&1 || true
|
||||
fi
|
||||
fi
|
||||
|
||||
pactl subscribe 2>/dev/null | while read -r line; do
|
||||
case "$line" in
|
||||
*"Event 'new' on sink"*|*"Event 'new' on card"*|*"Event 'change' on card"*)
|
||||
bt_sink="$(pactl list short sinks 2>/dev/null | awk '$2 ~ /^bluez_output\./ { print $2; exit }')"
|
||||
if [ -n "$bt_sink" ] && [ "$bt_sink" != "$prev_bt_sink" ]; then
|
||||
prev_bt_sink="$bt_sink"
|
||||
sxmo_audio.sh device set Bluetooth >/dev/null 2>&1 || true
|
||||
sxmo_log "Bluetooth sink $bt_sink detected -> routed audio to Bluetooth"
|
||||
fi
|
||||
sxmo_hook_statusbar.sh volume >/dev/null 2>&1 || true
|
||||
;;
|
||||
*"Event 'remove' on sink"*|*"Event 'remove' on card"*)
|
||||
bt_sink="$(pactl list short sinks 2>/dev/null | awk '$2 ~ /^bluez_output\./ { print $2; exit }')"
|
||||
if [ -z "$bt_sink" ] && [ -n "$prev_bt_sink" ]; then
|
||||
prev_bt_sink=""
|
||||
cur_out="$(cat /tmp/sxmo_audio_out_device 2>/dev/null || true)"
|
||||
if [ "$cur_out" = "Bluetooth" ]; then
|
||||
if [ "$(cat /tmp/sxmo_jack_plugged 2>/dev/null || true)" = "1" ]; then
|
||||
sxmo_audio.sh device set Headphones >/dev/null 2>&1 || true
|
||||
elif [ -r /tmp/sxmo_in_call ]; then
|
||||
sxmo_audio.sh device set Earpiece >/dev/null 2>&1 || true
|
||||
else
|
||||
sxmo_audio.sh device set Speaker >/dev/null 2>&1 || true
|
||||
fi
|
||||
sxmo_log "Bluetooth sink removed -> restored local audio route"
|
||||
fi
|
||||
fi
|
||||
sxmo_hook_statusbar.sh volume >/dev/null 2>&1 || true
|
||||
;;
|
||||
*"Event 'change' on sink"*|*"Event 'change' on source"*)
|
||||
if [ ! -d /tmp/sxmo_volset.lock ]; then
|
||||
sxmo_hook_statusbar.sh volume >/dev/null 2>&1 || true
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
done
|
||||
}
|
||||
|
||||
cleanup() {
|
||||
kill 0 2>/dev/null || true
|
||||
}
|
||||
|
||||
trap cleanup EXIT INT TERM
|
||||
|
||||
monitor_jack_events &
|
||||
|
||||
while : ; do
|
||||
handle_change || true
|
||||
# U10: pactl subscribe is event-driven; only back off after a failure.
|
||||
sleep 10
|
||||
done
|
||||
exec /usr/bin/bananarchy-soundmonitor "$@"
|
||||
@@ -70,12 +70,12 @@ xorgdisplay() {
|
||||
if [ -w /sys/devices/system/cpu/cpufreq/policy0/scaling_governor ]; then
|
||||
printf 'powersave\n' > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor 2>/dev/null || true
|
||||
fi
|
||||
xset s off s noblank >/dev/null 2>&1 || true
|
||||
xset dpms force off >/dev/null 2>&1 || true
|
||||
# K5: pin the Adreno 304 devfreq to its minimum OPP while dark.
|
||||
if [ -w /sys/class/devfreq/1c00000.gpu/governor ]; then
|
||||
printf 'powersave\n' > /sys/class/devfreq/1c00000.gpu/governor 2>/dev/null || true
|
||||
fi
|
||||
xset s off s noblank >/dev/null 2>&1 || true
|
||||
xset dpms force off >/dev/null 2>&1 || true
|
||||
# Power policy: park the secondary SIM after the configured dark delay.
|
||||
/usr/bin/bananarchy-power-policy.sh screenoff >/dev/null 2>&1 &
|
||||
;;
|
||||
@@ -85,6 +85,9 @@ xorgdisplay() {
|
||||
if ! "${BANANARCHY_LID_GATE:-/usr/bin/bananarchy-lid-gate.sh}" wake; then
|
||||
return 0
|
||||
fi
|
||||
if [ -w /sys/module/cpuidle_qcom_spm/parameters/screen_off ]; then
|
||||
printf 'N\n' > /sys/module/cpuidle_qcom_spm/parameters/screen_off 2>/dev/null || true
|
||||
fi
|
||||
if [ -w /sys/devices/system/cpu/cpufreq/policy0/scaling_governor ]; then
|
||||
printf 'schedutil\n' > /sys/devices/system/cpu/cpufreq/policy0/scaling_governor 2>/dev/null || true
|
||||
fi
|
||||
|
||||
@@ -1 +0,0 @@
|
||||
console=ttyMSM0,115200
|
||||
@@ -1 +0,0 @@
|
||||
console=ttyMSM0,115200
|
||||
@@ -1 +0,0 @@
|
||||
console=ttyMSM0,115200
|
||||
@@ -1 +0,0 @@
|
||||
console=ttyMSM0,115200
|
||||
@@ -1 +0,0 @@
|
||||
console=ttyMSM0,115200
|
||||
@@ -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)
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=daemon for monitoring modem-related dbuses (calls, sms, mms, etc.)
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Restart=always
|
||||
ExecStart=/usr/bin/bananarchy-modemmonitor
|
||||
@@ -0,0 +1,7 @@
|
||||
[Unit]
|
||||
Description=display notifications popup messages
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Restart=always
|
||||
ExecStart=/usr/bin/bananarchy-notifmonitor
|
||||
@@ -0,0 +1,8 @@
|
||||
[Unit]
|
||||
Description=Sxmo: watch audio changes and update the status bar
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
Restart=always
|
||||
ExecStart=/usr/bin/bananarchy-soundmonitor
|
||||
RestartSec=1s
|
||||
Reference in new issue
Block a user