diff --git a/CHANGELOG.md b/CHANGELOG.md index 216219f..3b38279 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,18 @@ Release versions follow the `
` format (where `2026` is `a`, --- +## Build `a1027` (2026-10-27) + +### New features and improvements +- **Dual-SIM Dual Standby (DSDS) and outgoing SIM selection**: + - Updated `msm-modem-uim-selection` to provision both physical SIM slots simultaneously (`primary-gw-provisioning` and `secondary-gw-provisioning`) with QMI `NAS` Dual-Standby Preference (`DualStandbyWithTuneAway`) and network registration across both subscriptions. + - Added an event-driven QMI `WMS` and `VOICE` QRTR listener (`dsds-daemon`, supervised by `sxmo_modemmonitor.sh`) so both SIM cards can receive incoming voice calls (with `q6voiced` `hw:0,4` audio routing) and SMS messages (single and multipart GSM-7 / UCS-2) simultaneously. + - Added interactive `[1] SIM 1` / `[2] SIM 2` outgoing SIM selection prompts when two SIM cards are active across voice calls (`xcallscreen` / `sxmo_modemdial.sh`), SMS (`xsms` / `sxmo_modemsendsms.sh`), and USSD queries (`xdialer` / `msm-modem-uim-selection ussd`), plus live dual-SIM status and instant default SIM switching in `xmodem`. +- **Instant USB charging state icon update**: + - Added `/etc/udev/rules.d/85-bananarchy-battery.rules` and updated `sxmo_hook_battery.sh` to inspect `/sys/class/power_supply/pm8916-lbc-chgr/online` immediately on `power_supply` udev events so the statusbar charging indicator appears and disappears the moment the cable is plugged in or unplugged. + +--- + ## Build `a1026` (2026-10-26) ### New features and improvements diff --git a/MANUAL.md b/MANUAL.md index be13407..8be83f0 100644 --- a/MANUAL.md +++ b/MANUAL.md @@ -137,7 +137,7 @@ All fifteen phone applications are compiled as shared-object plugins (`/usr/lib/ - **Dialing and T9 search**: typing digits filters saved contacts and recent numbers by phone number and T9 name in real time. Hold **`0`** (`>= 420 ms`) or press `Right` / **Left softkey (`+Sign`)** to insert `+`. - **USSD codes and `*#06#` Dual-SIM IMEI display**: - Typing **`*#06#`** immediately opens the **Device IMEI (`*#06#`)** dialog showing `IMEI 1`, `IMEI 2`, and `IMEI SV`. - - Typing any USSD code (`*...#` or `#...#`, such as `*100#`) switches the center softkey to **`SEND`**. Pressing **Call (green)** or **Center `OK`** runs the USSD session inside an interactive in-dialer modal with scrollable carrier output and multi-step reply support. + - Typing any USSD code (`*...#` or `#...#`, such as `*100#`) switches the center softkey to **`SEND`**. Pressing **Call (green)** or **Center `OK`** runs the USSD session inside an interactive in-dialer modal with scrollable carrier output and multi-step reply support (prompting for **SIM 1** or **SIM 2** first when two SIM cards are active in DSDS). 4. **Call history and anti-spam blocklist (`calllog.so` / `xcalllog`)**: - **Open**: press **Call (green)** on the empty desktop, or select **Call Log** from the System menu or Dialer. @@ -145,7 +145,7 @@ All fifteen phone applications are compiled as shared-object plugins (`/usr/lib/ - **Anti-spam blocklist (`~/.config/sxmo/block.tsv`)**: press **Left softkey (`Options`)** to **Block Number (Spam)** or **Unblock Number**, open **Blocklist (N)** to manage blocked numbers, **Block a Number...** (supports exact numbers, 9-digit suffix matching, or prefix wildcards ending with `*`), or **Clear Spam Log** (`~/.local/share/sxmo/block/modemlog.tsv`). Incoming calls from blocked numbers are automatically hung up and recorded in the `Spam` tab without triggering missed-call notifications. 5. **Incoming and active call screen (`callscreen.so` / `xcallscreen`)**: - - **Automatic activation**: wakes the screen and opens automatically on incoming and outgoing calls. Pressing **Call (green)** during an active call reopens `xcallscreen` from anywhere. + - **Automatic activation and Dual-SIM selection**: wakes the screen and opens automatically on incoming and outgoing calls across both SIM slots (displaying a `[SIM 1]` or `[SIM 2]` badge in the header when Dual-SIM Dual Standby is active). When initiating an outgoing call with two SIMs inserted, `xcallscreen` prompts to choose **`[1] SIM 1`** or **`[2] SIM 2`** (`1`/`2` keys or `Up`/`Down` + `Call`/`Enter`). Pressing **Call (green)** during an active call reopens `xcallscreen` from anywhere. - **Incoming call actions**: press **Call (green)**, **Left softkey (`Accept`)**, **`1`**, or **Center `OK`** to answer; press **`*`** or **`0`** to silence the ringer; press **End (red)**, **Right softkey (`Reject`)**, or **`#`** to decline. - **In-call controls and recording**: - **`[1]` / `*` — microphone mute**: toggles hardware QDSP6 and PipeWire microphone mute (`ON` / `MUTED`). @@ -165,7 +165,7 @@ All fifteen phone applications are compiled as shared-object plugins (`/usr/lib/ - **Open**: select **Texts** from the System menu, or choose **Send SMS** / **Read Messages** from Contacts. - **Conversations, inbox, and spam folder**: browse SMS threads and drafts with contact name resolution, unread indicators, and message bubbles (`Recv` and `Sent`). Press `Left`/`Right` in the thread list (or use **Left softkey (`Options`)**) to switch between **`Inbox`** (`~/.local/share/sxmo/modem`) and the **`Spam`** folder (`~/.local/share/sxmo/block`). - **Anti-spam blocking**: press **Left softkey (`Options`)** on any thread or conversation to **Block Number (Spam)** (which adds the sender to `~/.config/sxmo/block.tsv` and moves their thread into the `Spam` folder), **Unblock & Restore** (which unblocks the sender and restores their thread to `Inbox`), **Manage Blocklist (N)**, or **Block a Number...**. Incoming texts from blocked numbers are silently routed into `~/.local/share/sxmo/block` without ringing or vibrating. - - **Multi-tap composer**: pick a recipient from Contacts/Recents or type a number (hold `0` for `+`), compose messages with multi-tap keypad entry (`#` cycles input mode), monitor live character/segment counts (`0/160`), save drafts automatically, and send via **Call (green)**, **Center `OK`**, or **Left softkey**. + - **Multi-tap composer**: pick a recipient from Contacts/Recents or type a number (hold `0` for `+`), compose messages with multi-tap keypad entry (`#` cycles input mode), monitor live character/segment counts (`0/160`), save drafts automatically, and send via **Call (green)**, **Center `OK`**, or **Left softkey** (prompting to select **SIM 1** or **SIM 2** when two SIM cards are active in DSDS). 8. **File manager (`files.so` / `xfiles`)**: - **Open**: select **Files** from the System menu or press `Mod4+d`. @@ -191,7 +191,7 @@ All fifteen phone applications are compiled as shared-object plugins (`/usr/lib/ 11. **Modem, Dual-SIM, and PIN/PUK manager (`modem.so` / `xmodem`)**: - **Open**: select **Modem** from the System menu, or run `xmodem`. Also opens automatically when a SIM card requires PIN or PUK unlock. - **Four control tabs (`Left`/`Right` or `1`–`4`)**: - - **`1:SIMs`**: inspects both physical SIM slots via QMI UIM (`PRESENT`/`EMPTY`, `[ACTIVE]`, `READY`/`PIN-LOCK`/`PUK-LOCK`, remaining retries, operator, and ICCID). Press `Return` on a slot to **Activate SIM Slot 1 / 2**, **Unlock SIM PIN**, **Unblock SIM with PUK**, **Enable / Disable PIN Lock**, or **Change SIM PIN** (with automatic `ModemManager` reprobe after unlock). + - **`1:SIMs`**: inspects both physical SIM slots via QMI UIM (`PRESENT`/`EMPTY`, `[ACTIVE / DEFAULT]`, `[ACTIVE / DSDS]`, `READY`/`PIN-LOCK`/`PUK-LOCK`, remaining retries, operator, RAT, and phone number). Press `Return` on a slot to **Set as Default / Primary SIM**, **Unlock SIM PIN**, **Unblock SIM with PUK**, **Enable / Disable PIN Lock**, or **Change SIM PIN** (with automatic `ModemManager` reprobe after unlock). - **`2:Radio`**: shows signal bar, registration status, access technology (`LTE`/`UMTS`/`GSM`), operator, both IMEIs, and phone number, with actions to switch **Network Mode** (`4G/3G/2G`, `3G/2G`, `4G Only`, `3G Only`, `2G Only`), **Send USSD Code**, toggle **Modem Power**, or **Restart ModemManager**. - **`3:AT`**: interactive AT command console with presets (`AT`, `ATI`, `AT+CSQ`, `AT+CPIN?`, `AT+COPS?`, etc.) and custom keypad entry. - **`4:Log`**: scrollable history of calls, SMS events, and USSD responses. diff --git a/README.md b/README.md index 8055dc7..167af16 100644 --- a/README.md +++ b/README.md @@ -23,9 +23,9 @@ Instead of spawning slow shell scripts for everyday phone tasks, Bananarchy runs a suite of preloaded C/C++ plugins inside DWM that sleep at 0% CPU and open in `< 2 ms`: - **System and context menus (`dmenu`)**: instant full-screen 10-line vertical menus with live T9 filtering, built-in submenus, and hardware toggles. - **Global controls drawer (`xdrawer`)**: press **both softkeys together** from anywhere to adjust speaker, earpiece, and ringtone volume, ringer mode (`Ring+Vib` / `Vibrate` / `Silent` / `DND`), 3-level vibration intensity (`Light` / `Medium` / `Strong`), flashlight, sound and microphone mute, screen brightness, and keypad backlight. -- **Phone dialer (`xdialer`), call log (`xcalllog`), and call screen (`xcallscreen`)**: press any digit on the home screen to start dialing with live T9 contact matching, run interactive carrier USSD codes (`*100#`, etc.), or type `*#06#` to inspect both IMEIs. Incoming and active calls open a dedicated call screen with earpiece/speaker switching, microphone mute, DTMF keypad, and one-key normalized WAV call recording (`~/Recordings/rec_HHMMSS_.wav`). The call log includes a 5-tab view (`All`, `Miss`, `In`, `Out`, `Spam`) with integrated anti-spam number blocking (`~/.config/sxmo/block.tsv`) that automatically hangs up blocked callers and logs them to the `Spam` tab without triggering missed-call notifications. -- **Contacts (`xcontacts`) and SMS manager (`xsms`)**: full phonebook editor with direct Qualcomm QMI SIM card contact import and export across SIM 1 and SIM 2, paired with a threaded SMS conversation view, multi-tap message composer, and built-in anti-spam blocklist / spam folder (`~/.local/share/sxmo/block`) with one-key thread blocking and restoration. -- **Modem and Dual-SIM manager (`xmodem`)**: 4-tab cellular control center (`SIMs`, `Radio`, `AT`, `Log`) supporting physical SIM 1 / SIM 2 active slot switching, SIM PIN unlock and PUK unblock wizards, 2G/3G/4G radio mode selection, interactive USSD sessions, and a live AT command console. +- **Phone dialer (`xdialer`), call log (`xcalllog`), and call screen (`xcallscreen`)**: press any digit on the home screen to start dialing with live T9 contact matching, run interactive carrier USSD codes (`*100#`, etc.), or type `*#06#` to inspect both IMEIs. When two SIM cards are active in Dual-SIM Dual Standby (DSDS), placing a call or running a USSD code prompts to choose between `SIM 1` and `SIM 2`. Incoming and active calls on either SIM open a dedicated call screen with an active `[SIM 1]`/`[SIM 2]` badge, earpiece/speaker switching, microphone mute, DTMF keypad, and one-key normalized WAV call recording (`~/Recordings/rec_HHMMSS_.wav`). The call log includes a 5-tab view (`All`, `Miss`, `In`, `Out`, `Spam`) with integrated anti-spam number blocking (`~/.config/sxmo/block.tsv`) that automatically hangs up blocked callers and logs them to the `Spam` tab without triggering missed-call notifications. +- **Contacts (`xcontacts`) and SMS manager (`xsms`)**: full phonebook editor with direct Qualcomm QMI SIM card contact import and export across SIM 1 and SIM 2, paired with a threaded SMS conversation view, multi-tap message composer with outgoing `SIM 1` / `SIM 2` selection when two SIMs are active, and built-in anti-spam blocklist / spam folder (`~/.local/share/sxmo/block`) with one-key thread blocking and restoration. +- **Modem and Dual-SIM manager (`xmodem`)**: 4-tab cellular control center (`SIMs`, `Radio`, `AT`, `Log`) supporting Dual-SIM Dual Standby (DSDS) with simultaneous network registration on both SIM slots, default SIM selection, SIM PIN unlock and PUK unblock wizards, 2G/3G/4G radio mode selection, interactive USSD sessions, and a live AT command console. - **Networks and Bluetooth manager (`xnetworks`)**: 3-tab connectivity manager for Wi-Fi networks, WPA2 password entry, Wi-Fi hotspot, USB tethering, 4G/LTE mobile data (`wwan0`) and APN editing, and Bluetooth pairing. - **File manager (`xfiles`), music and tracker player (`xmusic`), and camera (`xcamera`)**: keypad directory browser with built-in text viewer, integrated GUI multi-tap text editor (`Edit in Text Editor`, available as an action on any file), and image viewer (plus one-click actions to launch `.gb`/`.gbc` ROMs in the Game Boy emulator, run `.yab` scripts in Yabasic inside the terminal, play audio, preview images, set any image as wallpaper, or install any audio or tracker file as ringtone), a 3-tab music and chiptune tracker module player (`WAV`, `MP3`, `OGG`, `FLAC`, `Opus`, `MOD`, `XM`, `IT`, `S3M`, and more), and a live V4L2 camera viewfinder with digital zoom, flash/torch control, self-timer, and photo gallery. - **Themes (`xthemes`), wallpapers (`xwallpapers`), and ringtones (`xringtones`)**: installable `.Xresources` color and font themes (`~/.xthemes/*.xth`, 20 preinstalled schemes) with live zero-restart reload across the entire UI and terminal, alongside dedicated managers for desktop wallpapers and call ringtones (supporting both standard audio and tracker modules) with 3-level vibration control. diff --git a/overlay/rootfs/etc/modules b/overlay/rootfs/etc/modules index 7d5021e..e77b575 100644 --- a/overlay/rootfs/etc/modules +++ b/overlay/rootfs/etc/modules @@ -3,3 +3,4 @@ ipv6 panel_mipi_dbi leds_msm8905_torch msm8905-cam +rpmsg_wwan_ctrl diff --git a/overlay/rootfs/etc/udev/rules.d/85-bananarchy-battery.rules b/overlay/rootfs/etc/udev/rules.d/85-bananarchy-battery.rules new file mode 100644 index 0000000..751c5dd --- /dev/null +++ b/overlay/rootfs/etc/udev/rules.d/85-bananarchy-battery.rules @@ -0,0 +1 @@ +SUBSYSTEM=="power_supply", ACTION=="change", RUN+="/bin/sh -c 'su - user -c \"DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/10000 /usr/share/sxmo/default_hooks/sxmo_hook_battery.sh udev\" >/dev/null 2>&1 &'" diff --git a/overlay/rootfs/usr/bin/sxmo_modemcall.sh b/overlay/rootfs/usr/bin/sxmo_modemcall.sh index b70f573..3e3bced 100755 --- a/overlay/rootfs/usr/bin/sxmo_modemcall.sh +++ b/overlay/rootfs/usr/bin/sxmo_modemcall.sh @@ -14,17 +14,24 @@ mkdir -p "$XDG_RUNTIME_DIR/sxmo_calls" set -e vid_to_number() { - mmcli -m any -o "$1" -K | \ - grep call.properties.number | \ - cut -d ':' -f2 | \ - tr -d ' ' + case "$1" in + sub1_*|sub0_*) + doas -n /usr/libexec/msm-modem-uim-selection call-list 2>/dev/null | awk -F'\t' -v id="$1" '$1 == id {print $4; exit}' + ;; + *) + mmcli -m any -o "$1" -K 2>/dev/null | \ + grep call.properties.number | \ + cut -d ':' -f2 | \ + tr -d ' ' + ;; + esac } log_event() { EVT_HANDLE="$1" EVT_VID="$2" - NUM="$(vid_to_number "$EVT_VID")" + NUM="$(vid_to_number "$EVT_VID" 2>/dev/null || true)" TIME="$(date +%FT%H:%M:%S%z)" mkdir -p "$SXMO_LOGDIR" @@ -35,6 +42,22 @@ pickup() { CALLID="$1" NUM="$(vid_to_number "$CALLID" 2>/dev/null || true)" + case "$CALLID" in + sub1_*|sub0_*) + sxmo_log "Invoking pickup hook for $CALLID" + sxmo_hook_pickup.sh || true + doas -n dbus-send --system --type=signal / org.ofono.VoiceCallManager.CallAdded >/dev/null 2>&1 || true + sxmo_modemaudio.sh setup_audio || true + doas -n /usr/libexec/msm-modem-uim-selection call-accept "$CALLID" >/dev/null 2>&1 || \ + /usr/libexec/msm-modem-uim-selection call-accept "$CALLID" >/dev/null 2>&1 || true + touch "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}.pickedupcall" + if command -v xcallscreen >/dev/null 2>&1; then + xcallscreen active "$CALLID" "$NUM" >/dev/null 2>&1 || true + fi + return 0 + ;; + esac + DIRECTION="$( (mmcli -m any -o "$CALLID" -K 2>/dev/null || mmcli -o "$CALLID" -K 2>/dev/null || mmcli --voice-status -o "$CALLID" -K 2>/dev/null) | grep call.properties.direction | @@ -99,6 +122,18 @@ pickup() { hangup() { CALLID="$1" + case "$CALLID" in + sub1_*|sub0_*) + rm -f "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}."* 2>/dev/null || true + touch "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}.hangedupcall" + doas -n /usr/libexec/msm-modem-uim-selection call-hangup "$CALLID" >/dev/null 2>&1 || \ + /usr/libexec/msm-modem-uim-selection call-hangup "$CALLID" >/dev/null 2>&1 || true + doas -n dbus-send --system --type=signal / org.ofono.VoiceCallManager.CallRemoved >/dev/null 2>&1 || true + sxmo_hook_hangup.sh || true + return 0 + ;; + esac + if [ -f "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}.pickedupcall" ] || \ [ -f "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}.initiatedcall" ]; then @@ -129,7 +164,7 @@ hangup() { # We shallow muted/blocked and terminated calls list_active_calls() { - mmcli -m any --voice-list-calls | \ + mmcli -m any --voice-list-calls 2>/dev/null | \ awk '$1=$1' | \ grep -v terminated | \ grep -v "No calls were found" | while read -r line; do @@ -139,6 +174,19 @@ list_active_calls() { fi printf "%s\n" "$line" done + for f in "$XDG_RUNTIME_DIR"/sxmo_calls/sub1_*.*; do + [ -e "$f" ] || continue + base="${f##*/}" + cid="${base%%.*}" + st="${base#*.}" + case "$st" in + ringing-in|dialing|ringing-out|active|held|waiting) + if [ ! -e "$XDG_RUNTIME_DIR/sxmo_calls/${cid}.mutedring" ]; then + printf "/org/freedesktop/ModemManager1/Call/%s (%s)\n" "$cid" "$st" + fi + ;; + esac + done } incall_menu() { diff --git a/overlay/rootfs/usr/bin/sxmo_modemdial.sh b/overlay/rootfs/usr/bin/sxmo_modemdial.sh index 99d6b9f..5356493 100755 --- a/overlay/rootfs/usr/bin/sxmo_modemdial.sh +++ b/overlay/rootfs/usr/bin/sxmo_modemdial.sh @@ -8,8 +8,25 @@ set -e -dial_number() { +REQ_SIM_SLOT="${SXMO_SIM_SLOT:-}" +if [ "${1:-}" = "--sim" ] && [ -n "${2:-}" ]; then + REQ_SIM_SLOT="$2" + shift 2 +fi +resolve_sim_state() { + 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)" + PRIM_SLOT="$(printf "%s\n" "$UIM_ST" | awk -F= '/^PRIMARY_GW_SLOT=/ {print $2; exit}')" + SEC_SLOT="$(printf "%s\n" "$UIM_ST" | awk -F= '/^SECONDARY_GW_SLOT=/ {print $2; exit}')" + PREF_SLOT="$(printf "%s\n" "$UIM_ST" | awk -F= '/^PREFERRED_SLOT=/ {print $2; exit}')" + DUAL_ACTIVE="$(printf "%s\n" "$UIM_ST" | awk -F= '/^DUAL_SIM_ACTIVE=/ {print $2; exit}')" + [ -n "$PRIM_SLOT" ] || PRIM_SLOT="1" + [ -n "$SEC_SLOT" ] || SEC_SLOT="0" + [ -n "$PREF_SLOT" ] || PREF_SLOT="$PRIM_SLOT" + [ -n "$DUAL_ACTIVE" ] || DUAL_ACTIVE="0" +} + +dial_number() { # on pinephone if you attempt to make a call while in a call, modem crashes if sxmo_modemcall.sh list_active_calls | grep -q .; then sxmo_notify_user.sh "Cannot make call while in a call (for now)." @@ -21,6 +38,51 @@ dial_number() { return 1 fi + resolve_sim_state + TARGET_SIM="$REQ_SIM_SLOT" + + # If 2 SIMs are active and no SIM was chosen yet, prompt via xcallscreen + if [ -z "$TARGET_SIM" ] && [ "$DUAL_ACTIVE" = "1" ]; then + if [ -p "/tmp/dwm_plugin_callscreen.fifo" ] && command -v xcallscreen >/dev/null 2>&1; then + printf "PROMPT_SIM %s\n" "$NUMBER" > /tmp/dwm_plugin_callscreen.fifo 2>/dev/null || true + xcallscreen >/dev/null 2>&1 || true + return 0 + fi + TARGET_SIM="$PREF_SLOT" + fi + [ -n "$TARGET_SIM" ] || TARGET_SIM="$PRIM_SLOT" + + # Secondary GW SIM call via QMI VOICE sub=1 + if [ "$TARGET_SIM" = "$SEC_SLOT" ] && [ "$SEC_SLOT" != "0" ]; then + sxmo_log "Attempting to dial on Secondary GW (SIM $TARGET_SIM): $NUMBER" + if [ -p "/tmp/dwm_plugin_callscreen.fifo" ]; then + printf "OUTGOING - %s SIM%s\n" "$NUMBER" "$TARGET_SIM" > /tmp/dwm_plugin_callscreen.fifo 2>/dev/null || true + fi + if command -v xcallscreen >/dev/null 2>&1; then + xcallscreen outgoing "-" "$NUMBER" >/dev/null 2>&1 || true + fi + if ! CALLID="$(doas -n /usr/libexec/msm-modem-uim-selection call-dial "$TARGET_SIM" "$NUMBER" 2>/dev/null || /usr/libexec/msm-modem-uim-selection call-dial "$TARGET_SIM" "$NUMBER" 2>/dev/null)"; then + if command -v xcallscreen >/dev/null 2>&1; then + xcallscreen ended >/dev/null 2>&1 || true + fi + sxmo_notify_user.sh --urgency=critical "We failed to initiate call on SIM $TARGET_SIM" + return 1 + fi + rm "$XDG_RUNTIME_DIR/sxmo_calls/$CALLID."* 2>/dev/null || true + touch "$XDG_RUNTIME_DIR/sxmo_calls/${CALLID}.initiatedcall" + doas -n dbus-send --system --type=signal / org.ofono.VoiceCallManager.CallAdded >/dev/null 2>&1 || true + sxmo_hook_dial.sh || true + sxmo_modemaudio.sh setup_audio || true + if [ -p "/tmp/dwm_plugin_callscreen.fifo" ]; then + printf "OUTGOING %s %s SIM%s\n" "$CALLID" "$NUMBER" "$TARGET_SIM" > /tmp/dwm_plugin_callscreen.fifo 2>/dev/null || true + elif command -v xcallscreen >/dev/null 2>&1; then + xcallscreen outgoing "$CALLID" "$NUMBER" >/dev/null 2>&1 || true + fi + sxmo_jobs.sh start proximity_lock sxmo_proximitylock.sh + sxmo_hook_statusbar.sh state & + return 0 + fi + mm_state="$(mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.generic.state") {print $2; exit}}')" if [ "$mm_state" = "disabled" ] || [ -z "$mm_state" ]; then mmcli -m any -e >/dev/null 2>&1 || true @@ -28,7 +90,10 @@ dial_number() { sleep 1 fi - sxmo_log "Attempting to dial: $NUMBER" + sxmo_log "Attempting to dial (SIM $TARGET_SIM): $NUMBER" + if [ -p "/tmp/dwm_plugin_callscreen.fifo" ]; then + printf "OUTGOING - %s SIM%s\n" "$NUMBER" "$TARGET_SIM" > /tmp/dwm_plugin_callscreen.fifo 2>/dev/null || true + fi if command -v xcallscreen >/dev/null 2>&1; then xcallscreen outgoing "-" "$NUMBER" >/dev/null 2>&1 || true fi @@ -48,7 +113,9 @@ dial_number() { # cleanup all dangling event files, ignore errors rm "$XDG_RUNTIME_DIR/sxmo_calls/$CALLID."* 2>/dev/null || true sxmo_log "Starting call with CALLID: $CALLID" - if command -v xcallscreen >/dev/null 2>&1; then + if [ -p "/tmp/dwm_plugin_callscreen.fifo" ]; then + printf "OUTGOING %s %s SIM%s\n" "$CALLID" "$NUMBER" "$TARGET_SIM" > /tmp/dwm_plugin_callscreen.fifo 2>/dev/null || true + elif command -v xcallscreen >/dev/null 2>&1; then xcallscreen outgoing "$CALLID" "$NUMBER" >/dev/null 2>&1 || true fi @@ -82,7 +149,12 @@ dial_number() { dial_ussd() { USSD="$1" sxmo_log "Dialling USSD: $USSD" - OUTPUT="$(doas -n /usr/libexec/msm-modem-uim-selection ussd initiate "$USSD" 2>/dev/null || /usr/libexec/msm-modem-uim-selection ussd initiate "$USSD" 2>/dev/null || true)" + SIM_ARG="" + if [ -n "$REQ_SIM_SLOT" ]; then + SIM_ARG="--sim $REQ_SIM_SLOT" + fi + # shellcheck disable=SC2086 + OUTPUT="$(doas -n /usr/libexec/msm-modem-uim-selection ussd initiate $SIM_ARG "$USSD" 2>/dev/null || /usr/libexec/msm-modem-uim-selection ussd initiate $SIM_ARG "$USSD" 2>/dev/null || true)" if [ -z "$OUTPUT" ]; then DBUS_MODEM="$(mmcli -J -L 2>/dev/null | jq -r '."modem-list"[]' 2>/dev/null | head -n1)" MM_BUS="org.freedesktop.ModemManager1" diff --git a/overlay/rootfs/usr/bin/sxmo_modemmonitor.sh b/overlay/rootfs/usr/bin/sxmo_modemmonitor.sh index 7c74edc..a395c07 100755 --- a/overlay/rootfs/usr/bin/sxmo_modemmonitor.sh +++ b/overlay/rootfs/usr/bin/sxmo_modemmonitor.sh @@ -46,6 +46,8 @@ mainloop() { 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 @@ -55,6 +57,18 @@ mainloop() { fi ) & + # Monitor Secondary GW SIM calls and SMS in Dual-SIM Dual Standby (DSDS) + ( + while : ; do + 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 -q "^DUAL_SIM_ACTIVE=1$"; then + doas -n /usr/libexec/msm-modem-uim-selection dsds-daemon 2>/dev/null || \ + /usr/libexec/msm-modem-uim-selection dsds-daemon 2>/dev/null || true + fi + sleep 5 + done + ) & + # Monitor for incoming calls dbus-monitor --system "interface='org.freedesktop.ModemManager1.Modem.Voice',type='signal',member='CallAdded'" | while read -r line; do diff --git a/overlay/rootfs/usr/bin/sxmo_modemsendsms.sh b/overlay/rootfs/usr/bin/sxmo_modemsendsms.sh new file mode 100755 index 0000000..114eeac --- /dev/null +++ b/overlay/rootfs/usr/bin/sxmo_modemsendsms.sh @@ -0,0 +1,209 @@ +#!/bin/sh +# SPDX-License-Identifier: AGPL-3.0-only +# Copyright 2022 Sxmo Contributors +# shellcheck disable=SC3045 + +# include common definitions +# shellcheck source=scripts/core/sxmo_common.sh +. sxmo_common.sh + +info() { + sxmo_log "$*" + printf "%s\n" "$*" +} + +err() { + info "$*" + exit 1 +} + +usage() { + printf "Usage: %s [--sim <1|2>] number|contact [-|message]\n" "$(basename "$0")" + exit 1 +} + +REQ_SIM_SLOT="${SXMO_SIM_SLOT:-}" +if [ "${1:-}" = "--sim" ] && [ -n "${2:-}" ]; then + REQ_SIM_SLOT="$2" + shift 2 +fi + +[ 0 -eq $# ] && usage +NUMBER="$1" + +make_attachments_arg() { + LOGDIRNUM="$1" + MAX_SIZE="$(grep "^TotalMaxAttachmentSize" "$MMS_BASE_DIR/mms" | cut -d'=' -f2)" + MAX_NUMBER="$(grep "^MaxAttachments" "$MMS_BASE_DIR/mms" | cut -d'=' -f2)" + [ -z "$MAX_NUMBER" ] && MAX_NUMBER="25" + [ -z "$MAX_SIZE" ] && MAX_SIZE="1100000" + + ATT_NUM=0 + TOTAL_SIZE=0 + while read -r ATTACHMENT; do + [ -f "$ATTACHMENT" ] || err "Attachment ($ATTACHMENT) not found!" + CTYPE=$(file -b --mime-type "$ATTACHMENT") + case "$CTYPE" in + "audio/mpegapplication/octet-stream") + CTYPE="audio/mpeg" + ;; + esac + + ATT_NUM="$((ATT_NUM+1))" + TOTAL_SIZE="$((TOTAL_SIZE+$(wc -c < "$ATTACHMENT")))" + if [ "$ATT_NUM" -gt "$MAX_NUMBER" ]; then + err "Number of attachments ($ATT_NUM) greater than MaxAttachments ($MAX_NUMBER)." + fi + if [ "$ATT_NUM" -ge 1 ] && [ "$TOTAL_SIZE" -gt "$MAX_SIZE" ]; then + err "Total size of attachments ($TOTAL_SIZE) greater than TotalMaxAttachmentSize ($MAX_SIZE)." + fi + printf " %s '%s' -c '%s'" "-a" "$ATTACHMENT" "$CTYPE" + done < "$SXMO_LOGDIR/$LOGDIRNUM/draft.attachments.txt" +} + +if ! echo "$NUMBER" | grep -q '^+'; then + ACTUAL_NUMBER="$(sxmo_contacts.sh --all | grep "^$NUMBER:" | cut -d':' -f2 | sed 's/^ //')" + if [ -z "$ACTUAL_NUMBER" ]; then + info "WARNING: $NUMBER does not look like a phone number or a contact." + else + NUMBER="$ACTUAL_NUMBER" + fi +fi + +finish() { + if [ -n "$TMPFILE" ]; then + rm "$TMPFILE" + fi + exit +} +trap 'finish' INT TERM EXIT + +if [ "-" = "$2" ]; then + TMPFILE="$(mktemp)" + TEXTFILE="$TMPFILE" + cat > "$TEXTFILE" +elif [ "-f" = "$2" ]; then + TMPFILE="$(mktemp)" + awk 'NR > 1 { print prev } { prev=$0 } END { ORS=""; print }' "$3" > "$TMPFILE" + TEXTFILE="$TMPFILE" +else + shift + [ 0 -eq $# ] && usage + + TMPFILE="$(mktemp)" + TEXTFILE="$TMPFILE" + printf "%s" "$*" > "$TEXTFILE" +fi +TEXT="$(cat "$TEXTFILE")" + +# if multiple recipients or attachment, then send via mmsctl +if [ "$(printf %s "$NUMBER" | xargs pnc find | wc -l)" -gt 1 ] || [ -f "$SXMO_LOGDIR/$NUMBER/draft.attachments.txt" ]; then + + MMS_BASE_DIR="${SXMO_MMS_BASE_DIR:-"$HOME"/.mms/modemmanager}" + [ -d "$MMS_BASE_DIR" ] || err "MMS not configured." + + NUMBER="$(printf %s "$NUMBER" | xargs pnc find | sort -u | grep . | xargs printf %s)" + [ -f "$SXMO_LOGDIR/$NUMBER/draft.attachments.txt" ] && ATTACHMENTS_ARG="$(make_attachments_arg "$NUMBER" | sed 's/^ //')" + ATTACHMENTS_ARG="-a '$TEXTFILE' $ATTACHMENTS_ARG" + RECIPIENTS_ARG="$(printf %s "$NUMBER" | sed 's/+/ -r +/g' | sed 's/^ //')" + + info "mmsctl -S $RECIPIENTS_ARG $ATTACHMENTS_ARG" + MMSCTL_RES="$(eval mmsctl -S "$RECIPIENTS_ARG" "$ATTACHMENTS_ARG")" + MMSCTL_OK="$?" + [ "$MMSCTL_OK" -ne 0 ] && err "mmsctl failed with \"$MMSCTL_RES\"" + + info "Waiting for mmsd-tng to send..." + MMS_PIPE="$(mktemp -u)" + mkfifo "$MMS_PIPE" + timeout 60 dbus-monitor "interface='org.ofono.mms.Message',type='signal',member='PropertyChanged'" > "$MMS_PIPE" & + MMS_PIPE_PID="$!" + while read -r line; do + if printf %s "$line" | grep -q 'member=PropertyChanged'; then + MESSAGE_PATH="$(echo "$line" | cut -d'=' -f6 | cut -d';' -f1)" + fi + if printf %s "$line" | grep -q "string \"sent\""; then + SENT_SUCCESS=1 + break + fi + done < "$MMS_PIPE" + rm -f "$MMS_PIPE" + kill "$MMS_PIPE_PID" + + [ -z "$SENT_SUCCESS" ] && err "mmsd-tng did not send the draft." + + [ -f "$SXMO_LOGDIR/$NUMBER/draft.attachments.txt" ] && rm -f "$SXMO_LOGDIR/$NUMBER/draft.attachments.txt" + + sxmo_mms.sh processmms "$MESSAGE_PATH" + + MMS_FILE="$(basename "$MESSAGE_PATH")" + CONTACTNAME="$(sxmo_contacts.sh --name-or-number "$NUMBER")" + sxmo_hook_sendsms.sh "$CONTACTNAME" "$TEXT" "$MMS_FILE" "$CONTACTNAME" + + info "Sent mms text to $CONTACTNAME." +else + TEXTSIZE="${#TEXT}" + 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)" + PRIM_SLOT="$(printf "%s\n" "$UIM_ST" | awk -F= '/^PRIMARY_GW_SLOT=/ {print $2; exit}')" + SEC_SLOT="$(printf "%s\n" "$UIM_ST" | awk -F= '/^SECONDARY_GW_SLOT=/ {print $2; exit}')" + PREF_SLOT="$(printf "%s\n" "$UIM_ST" | awk -F= '/^PREFERRED_SLOT=/ {print $2; exit}')" + [ -n "$PRIM_SLOT" ] || PRIM_SLOT="1" + [ -n "$SEC_SLOT" ] || SEC_SLOT="0" + [ -n "$PREF_SLOT" ] || PREF_SLOT="$PRIM_SLOT" + + TARGET_SIM="$REQ_SIM_SLOT" + [ -n "$TARGET_SIM" ] || TARGET_SIM="$PREF_SLOT" + + SENT_VIA_QMI=0 + if [ "$TARGET_SIM" = "$SEC_SLOT" ] && [ "$SEC_SLOT" != "0" ]; then + if doas -n /usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1 || \ + /usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1; then + SENT_VIA_QMI=1 + else + err "Couldn't send text message via SIM $TARGET_SIM" + fi + fi + + if [ "$SENT_VIA_QMI" = "0" ]; then + SMSNO="$( + mmcli -m any --messaging-create-sms-with-text="$TEXTFILE" --messaging-create-sms="number=$NUMBER" 2>/dev/null | + grep -o "[0-9]*$" || true + )" + SMS_OK=1 + SMS_RES="" + if [ -n "$SMSNO" ]; then + SMS_RES="$(mmcli -s "${SMSNO}" --send --timeout="${SXMO_MM_TIMEOUT:-"30"}" 2>&1)" && SMS_OK=0 || SMS_OK=$? + fi + + if [ "$SMS_OK" != 0 ]; then + # Fallback to direct QMI WMS RawSend on TARGET_SIM + if doas -n /usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1 || \ + /usr/libexec/msm-modem-uim-selection sms-send "$TARGET_SIM" "$NUMBER" "$TEXTFILE" >/dev/null 2>&1; then + SMS_OK=0 + fi + fi + + if [ "$SMS_OK" != 0 ]; then + if echo "$SMS_RES" | grep -q "Invalid number"; then + for i in $(mmcli -m any --messaging-list-sms | grep " (unknown)" | cut -f5 -d' '); do + mmcli -m any -s "$i" -K | grep -q "not requested" && mmcli -m any --messaging-delete-sms="$i" >/dev/null + done + err "Couldn't send text message: Invalid number." + else + err "Couldn't send text message ($SMS_RES)" + fi + fi + + for i in $(mmcli -m any --messaging-list-sms 2>/dev/null | grep " (sent)" | cut -f5 -d' ') ; do + mmcli -m any --messaging-delete-sms="$i" > /dev/null 2>&1 || true + done + fi + + TIME="$(date +%FT%H:%M:%S%z)" + mkdir -p "$SXMO_LOGDIR/$NUMBER" + sxmo_hook_smslog.sh "sent" "$NUMBER" "$NUMBER" "$TIME" "$TEXT" >> "$SXMO_LOGDIR/$NUMBER/sms.txt" + printf "%s\tsent_txt\t%s\t[SIM %s] %s chars\n" "$TIME" "$NUMBER" "$TARGET_SIM" "$TEXTSIZE" >> "$SXMO_LOGDIR/modemlog.tsv" + + CONTACTNAME="$(sxmo_contacts.sh --name-or-number "$NUMBER")" + sxmo_hook_sendsms.sh "$CONTACTNAME" "$TEXT" + info "Sent sms text to $CONTACTNAME (SIM $TARGET_SIM)." +fi diff --git a/overlay/rootfs/usr/lib/dwm/plugins/calllog.so b/overlay/rootfs/usr/lib/dwm/plugins/calllog.so index 4c2dafe..f35bf7d 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/calllog.so and b/overlay/rootfs/usr/lib/dwm/plugins/calllog.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so index 53b9976..f26ee00 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so and b/overlay/rootfs/usr/lib/dwm/plugins/callscreen.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/contacts.so b/overlay/rootfs/usr/lib/dwm/plugins/contacts.so index 985a09a..16d6ba8 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/contacts.so and b/overlay/rootfs/usr/lib/dwm/plugins/contacts.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/dialer.so b/overlay/rootfs/usr/lib/dwm/plugins/dialer.so index 3c3a9b8..ebe7a33 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/dialer.so and b/overlay/rootfs/usr/lib/dwm/plugins/dialer.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/modem.so b/overlay/rootfs/usr/lib/dwm/plugins/modem.so index 6b491df..26155d4 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/modem.so and b/overlay/rootfs/usr/lib/dwm/plugins/modem.so differ diff --git a/overlay/rootfs/usr/lib/dwm/plugins/sms.so b/overlay/rootfs/usr/lib/dwm/plugins/sms.so index a59423e..8e2c40f 100755 Binary files a/overlay/rootfs/usr/lib/dwm/plugins/sms.so and b/overlay/rootfs/usr/lib/dwm/plugins/sms.so differ diff --git a/overlay/rootfs/usr/libexec/msm-modem-uim-selection b/overlay/rootfs/usr/libexec/msm-modem-uim-selection index 9fa27e8..b9d8770 100755 --- a/overlay/rootfs/usr/libexec/msm-modem-uim-selection +++ b/overlay/rootfs/usr/libexec/msm-modem-uim-selection @@ -407,6 +407,69 @@ save_preferred_slot() { fi } +ensure_dsds_nas_registration() { + if ! command -v python3 >/dev/null 2>&1; then + return 0 + fi + python3 - << 'PY' >/dev/null 2>&1 || true +import socket, struct, select + +AF_QIPCRTR = 42 +QRTR_PORT_CTRL = 0xfffffffe +QRTR_TYPE_NEW_SERVER = 4 +QRTR_TYPE_NEW_LOOKUP = 10 +QMI_SERVICE_NAS = 3 + +ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) +node, _ = ls.getsockname() +ls.sendto(struct.pack("= 20: + cmd, srv, inst, srv_node, srv_port = struct.unpack("= 1: + return resp[pos] + pos += tl + return 0 + +for sub in (0, 1): + s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) + qmi_req(s, 1, 0x0045, struct.pack("/dev/null 2>&1 || true - fi - - if [ "$PRIMARY_GW_SLOT" != "0" ]; then - $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=primary-gw-provisioning' >/dev/null 2>&1 || true - fi - - if [ -n "$chosen_aid" ]; then - echo "Selecting AID $chosen_aid on slot $chosen_slot" - if ! $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning,aid=$chosen_aid" >/dev/null 2>&1; then + if [ "$need_prim" = "1" ]; then + if [ "${SECONDARY_GW_SLOT:-0}" = "$chosen_slot" ]; then + $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true + SECONDARY_GW_SLOT=0 + fi + if [ "$PRIMARY_GW_SLOT" != "0" ]; then + $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=primary-gw-provisioning' >/dev/null 2>&1 || true + fi + if [ -n "$chosen_aid" ]; then + echo "Selecting AID $chosen_aid on slot $chosen_slot (primary-gw-provisioning)" + if ! $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning,aid=$chosen_aid" >/dev/null 2>&1; then + $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true + fi + else + echo "Selecting slot $chosen_slot (primary-gw-provisioning)" $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true fi else - echo "Selecting slot $chosen_slot" - $QMICLI_MODEM --uim-change-provisioning-session="slot=$chosen_slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true + echo "Slot $chosen_slot already bound to primary-gw-provisioning ($chosen_app_state)." + fi + + # Dual-SIM Dual Standby (DSDS): provision the second present SIM slot to secondary-gw-provisioning + if [ "$other_state" = "present" ]; then + need_sec=1 + if [ "${SECONDARY_GW_SLOT:-0}" = "$other_slot" ] && { [ "$other_app_state" = "ready" ] || [ "$other_app_state" = "pin1-or-upin-pin-required" ] || [ "$other_app_state" = "puk1-or-upin-puk-required" ] || [ "$other_app_state" = "pin1_or_upin_pin_required" ] || [ "$other_app_state" = "puk1_or_upin_puk_required" ]; }; then + need_sec=0 + fi + if [ "$need_sec" = "1" ]; then + if [ "${SECONDARY_GW_SLOT:-0}" != "0" ] && [ "${SECONDARY_GW_SLOT:-0}" != "$other_slot" ]; then + $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true + fi + if [ -n "$other_aid" ]; then + echo "Selecting AID $other_aid on slot $other_slot (secondary-gw-provisioning)" + if ! $QMICLI_MODEM --uim-change-provisioning-session="slot=$other_slot,activate=yes,session-type=secondary-gw-provisioning,aid=$other_aid" >/dev/null 2>&1; then + $QMICLI_MODEM --uim-change-provisioning-session="slot=$other_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true + fi + else + echo "Selecting slot $other_slot (secondary-gw-provisioning)" + $QMICLI_MODEM --uim-change-provisioning-session="slot=$other_slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true + fi + else + echo "Slot $other_slot already bound to secondary-gw-provisioning ($other_app_state)." + fi + ensure_dsds_nas_registration + else + if [ "${SECONDARY_GW_SLOT:-0}" != "0" ]; then + $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true + fi fi return 0 } @@ -503,6 +603,7 @@ provision_slot() { prepare_slot_for_pin_op() { req_slot="${1:-1}" slot="$req_slot" + PIN_OP_SESSION="primary-gw-provisioning" target_aid="" if detect_qmicli_modem; then QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)" @@ -514,20 +615,28 @@ prepare_slot_for_pin_op() { slot="1" fi eval "target_aid=\$SLOT${slot}_AID" - if [ "$PRIMARY_GW_SLOT" != "$slot" ]; then - if [ "${SECONDARY_GW_SLOT:-0}" = "$slot" ]; then - $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=secondary-gw-provisioning' >/dev/null 2>&1 || true - fi - if [ "$PRIMARY_GW_SLOT" != "0" ]; then - $QMICLI_MODEM --uim-change-provisioning-session='activate=no,session-type=primary-gw-provisioning' >/dev/null 2>&1 || true + if [ "$PRIMARY_GW_SLOT" = "$slot" ]; then + PIN_OP_SESSION="primary-gw-provisioning" + elif [ "${SECONDARY_GW_SLOT:-0}" = "$slot" ]; then + PIN_OP_SESSION="secondary-gw-provisioning" + elif [ "$PRIMARY_GW_SLOT" != "0" ]; then + PIN_OP_SESSION="secondary-gw-provisioning" + if [ -n "$target_aid" ]; then + $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=secondary-gw-provisioning,aid=$target_aid" >/dev/null 2>&1 || \ + $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true + else + $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=secondary-gw-provisioning" >/dev/null 2>&1 || true fi + sleep 0.3 + else + PIN_OP_SESSION="primary-gw-provisioning" if [ -n "$target_aid" ]; then $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=primary-gw-provisioning,aid=$target_aid" >/dev/null 2>&1 || \ $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true else $QMICLI_MODEM --uim-change-provisioning-session="slot=$slot,activate=yes,session-type=primary-gw-provisioning" >/dev/null 2>&1 || true fi - sleep 0.5 + sleep 0.3 fi fi fi @@ -625,6 +734,7 @@ cmd="${1:-boot}" case "$cmd" in boot) + modprobe rpmsg_wwan_ctrl 2>/dev/null || true ensure_usb_network_gadget if command -v systemd-notify >/dev/null 2>&1; then trap '[ $? -eq 0 ] && systemd-notify --ready' EXIT @@ -658,11 +768,139 @@ case "$cmd" in exit 0 fi echo "MODEM_AVAILABLE=1" - parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT" + UIM_KV="$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")" + printf "%s\n" "$UIM_KV" + eval "$UIM_KV" QMI_NAS="$($QMICLI_MODEM --nas-get-serving-system 2>/dev/null || true)" if [ -n "$QMI_NAS" ]; then parse_nas_serving_system "$QMI_NAS" fi + if command -v python3 >/dev/null 2>&1; then + python3 - "${PRIMARY_GW_SLOT:-0}" "${SECONDARY_GW_SLOT:-0}" "${SLOT1_STATE:-absent}" "${SLOT2_STATE:-absent}" << 'PY' 2>/dev/null || true +import socket, struct, select, sys + +prim_slot = int(sys.argv[1]) if len(sys.argv) > 1 and sys.argv[1].isdigit() else 0 +sec_slot = int(sys.argv[2]) if len(sys.argv) > 2 and sys.argv[2].isdigit() else 0 +s1_state = sys.argv[3] if len(sys.argv) > 3 else "absent" +s2_state = sys.argv[4] if len(sys.argv) > 4 else "absent" + +dual_active = 1 if (s1_state == "present" and s2_state == "present" and prim_slot in (1, 2) and sec_slot in (1, 2)) else 0 +print(f"DUAL_SIM_ACTIVE={dual_active}") + +AF_QIPCRTR = 42 +QRTR_PORT_CTRL = 0xfffffffe +QRTR_TYPE_NEW_SERVER = 4 +QRTR_TYPE_NEW_LOOKUP = 10 + +def lookup_srv(sid): + ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) + node, _ = ls.getsockname() + ls.sendto(struct.pack("= 20: + cmd, srv, inst, srv_node, srv_port = struct.unpack("= 7 and resp[0] == 0x02: + r_txn, r_msg, _ = struct.unpack("= 0 and nas_addr: + s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) + qmi_req(s, nas_addr, 1, 0x0045, struct.pack("= 1 and v[0] == 2: + reg = "registered" + rat = r_name + break + elif len(v) >= 1 and v[0] in (1, 3) and reg == "not-registered": + reg = "searching" + op_t = qmi_req(s, nas_addr, 3, 0x0039) + if 0x10 in op_t and len(op_t[0x10]) >= 2: + slen = op_t[0x10][1] + op = op_t[0x10][2:2+slen].decode("utf-8", errors="ignore").strip() + if not op and 0x13 in op_t: + op = op_t[0x13].decode("utf-8", errors="ignore").strip("\x00 ") + sig_t = qmi_req(s, nas_addr, 4, 0x004F) + for t_id in (0x14, 0x13, 0x12): + if t_id in sig_t and len(sig_t[t_id]) >= 1: + val = struct.unpack("= 0 and dms_addr: + sd = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) + qmi_req(sd, dms_addr, 1, 0x0054, struct.pack("&1)" && verified=1 || { - if printf "%s\n" "$mm_pin_out" | grep -qiE "IncorrectPin|SimPin|SimPuk|PinBlocked|incorrect"; then - wrong_pin=1 - fi - } + if [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then + sim_id="$(timeout 3 mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)" + if [ -n "$sim_id" ]; then + mm_pin_out="$(timeout 5 mmcli -i "$sim_id" --pin="$pin" 2>&1)" && verified=1 || { + if printf "%s\n" "$mm_pin_out" | grep -qiE "IncorrectPin|SimPin|SimPuk|PinBlocked|incorrect"; then + wrong_pin=1 + fi + } + fi fi if [ "$verified" = "0" ] && [ "$wrong_pin" = "0" ] && [ -n "$QMICLI_MODEM" ]; then - qmi_pin_out="$($QMICLI_MODEM --uim-verify-pin="PIN1,$pin,session-type=primary-gw-provisioning" 2>&1)" && verified=1 || { + qmi_pin_out="$($QMICLI_MODEM --uim-verify-pin="PIN1,$pin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" 2>&1)" && verified=1 || { if printf "%s\n" "$qmi_pin_out" | grep -qiE "IncorrectPin|PinBlocked|Blocked"; then wrong_pin=1 fi @@ -734,11 +989,10 @@ case "$cmd" in fi fi if [ "$verified" = "1" ]; then - save_preferred_slot "$slot" SIM_WAIT_TIME=2 - provision_slot "$slot" 3 >/dev/null 2>&1 || true + provision_slot "$PREFERRED_SIM_SLOT" 3 >/dev/null 2>&1 || true timeout 4 mmcli -m any -e >/dev/null 2>&1 || true - spawn_enable_and_register "$slot" 1 + spawn_enable_and_register "$PREFERRED_SIM_SLOT" 1 exit 0 fi exit 1 @@ -754,12 +1008,14 @@ case "$cmd" in fi prepare_slot_for_pin_op "$slot" unblocked=0 - sim_id="$(timeout 3 mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)" - if [ -n "$sim_id" ] && timeout 4 mmcli -i "$sim_id" --puk="$puk" --pin="$newpin" >/dev/null 2>&1; then - unblocked=1 + if [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then + sim_id="$(timeout 3 mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)" + if [ -n "$sim_id" ] && timeout 4 mmcli -i "$sim_id" --puk="$puk" --pin="$newpin" >/dev/null 2>&1; then + unblocked=1 + fi fi if [ "$unblocked" = "0" ] && [ -n "$QMICLI_MODEM" ]; then - if $QMICLI_MODEM --uim-unblock-pin="PIN1,$puk,$newpin,session-type=primary-gw-provisioning" >/dev/null 2>&1; then + if $QMICLI_MODEM --uim-unblock-pin="PIN1,$puk,$newpin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" >/dev/null 2>&1; then unblocked=1 elif $QMICLI_MODEM --uim-unblock-pin="PIN1,$puk,$newpin,session-type=card-slot-$slot" >/dev/null 2>&1; then unblocked=1 @@ -776,11 +1032,10 @@ case "$cmd" in fi fi if [ "$unblocked" = "1" ]; then - save_preferred_slot "$slot" SIM_WAIT_TIME=2 - provision_slot "$slot" 3 >/dev/null 2>&1 || true + provision_slot "$PREFERRED_SIM_SLOT" 3 >/dev/null 2>&1 || true timeout 4 mmcli -m any -e >/dev/null 2>&1 || true - spawn_enable_and_register "$slot" 1 + spawn_enable_and_register "$PREFERRED_SIM_SLOT" 1 exit 0 fi exit 1 @@ -796,7 +1051,7 @@ case "$cmd" in fi prepare_slot_for_pin_op "$slot" if [ -n "$QMICLI_MODEM" ]; then - if $QMICLI_MODEM --uim-set-pin-protection="PIN1,$mode,$pin,session-type=primary-gw-provisioning" >/dev/null 2>&1; then + if $QMICLI_MODEM --uim-set-pin-protection="PIN1,$mode,$pin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" >/dev/null 2>&1; then exit 0 fi if $QMICLI_MODEM --uim-set-pin-protection="PIN1,$mode,$pin,session-type=card-slot-$slot" >/dev/null 2>&1; then @@ -806,12 +1061,14 @@ case "$cmd" in exit 0 fi fi - sim_id="$(mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)" - if [ -n "$sim_id" ]; then - if [ "$mode" = "enable" ] && mmcli -i "$sim_id" --enable-pin --pin="$pin" >/dev/null 2>&1; then - exit 0 - elif [ "$mode" = "disable" ] && mmcli -i "$sim_id" --disable-pin --pin="$pin" >/dev/null 2>&1; then - exit 0 + if [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then + sim_id="$(mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)" + if [ -n "$sim_id" ]; then + if [ "$mode" = "enable" ] && mmcli -i "$sim_id" --enable-pin --pin="$pin" >/dev/null 2>&1; then + exit 0 + elif [ "$mode" = "disable" ] && mmcli -i "$sim_id" --disable-pin --pin="$pin" >/dev/null 2>&1; then + exit 0 + fi fi fi exit 1 @@ -827,7 +1084,7 @@ case "$cmd" in fi prepare_slot_for_pin_op "$slot" if [ -n "$QMICLI_MODEM" ]; then - if $QMICLI_MODEM --uim-change-pin="PIN1,$oldpin,$newpin,session-type=primary-gw-provisioning" >/dev/null 2>&1; then + if $QMICLI_MODEM --uim-change-pin="PIN1,$oldpin,$newpin,session-type=${PIN_OP_SESSION:-primary-gw-provisioning}" >/dev/null 2>&1; then exit 0 fi if $QMICLI_MODEM --uim-change-pin="PIN1,$oldpin,$newpin,session-type=card-slot-$slot" >/dev/null 2>&1; then @@ -837,9 +1094,11 @@ case "$cmd" in exit 0 fi fi - sim_id="$(mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)" - if [ -n "$sim_id" ] && mmcli -i "$sim_id" --change-pin="$newpin" --pin="$oldpin" >/dev/null 2>&1; then - exit 0 + if [ "${PIN_OP_SESSION:-primary-gw-provisioning}" = "primary-gw-provisioning" ]; then + sim_id="$(mmcli -m any 2>/dev/null | grep -oE 'SIM/[0-9]+' | head -n1 | cut -d'/' -f2 || true)" + if [ -n "$sim_id" ] && mmcli -i "$sim_id" --change-pin="$newpin" --pin="$oldpin" >/dev/null 2>&1; then + exit 0 + fi fi exit 1 ;; @@ -1004,6 +1263,13 @@ case "$cmd" in ussd) ussd_mode="${2:-initiate}" shift 2 2>/dev/null || true + req_sim="$PREFERRED_SIM_SLOT" + if [ "${1:-}" = "--sim" ] && [ -n "${2:-}" ]; then + req_sim="$2" + shift 2 2>/dev/null || true + elif [ -n "${SXMO_SIM_SLOT:-}" ]; then + req_sim="$SXMO_SIM_SLOT" + fi ussd_code="$*" if [ "$ussd_mode" = "cancel" ]; then mmcli -m any --3gpp-ussd-cancel >/dev/null 2>&1 || true @@ -1015,107 +1281,205 @@ case "$cmd" in echo "ERROR: Empty USSD code" exit 1 fi - mm_state="$(mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.generic.state") {print $2; exit}}' || true)" - if [ "$mm_state" = "disabled" ] || [ -z "$mm_state" ]; then - mmcli -m any -e >/dev/null 2>&1 || true - sleep 1 - fi - modem_dbus_path="$(mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.dbus-path") {print $2; exit}}' || true)" - [ -z "$modem_dbus_path" ] && modem_dbus_path="/org/freedesktop/ModemManager1/Modem/0" - get_ussd_prop() { - prop_name="$1" - if [ -n "$modem_dbus_path" ] && command -v busctl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then - busctl -j get-property org.freedesktop.ModemManager1 "$modem_dbus_path" \ - org.freedesktop.ModemManager1.Modem.Modem3gpp.Ussd "$prop_name" 2>/dev/null | \ - jq -r '.data // empty' 2>/dev/null || true + prim_slot="$PREFERRED_SIM_SLOT" + sec_slot="0" + if detect_qmicli_modem; then + QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)" + if [ -n "$QMI_CARDS" ]; then + eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")" + prim_slot="${PRIMARY_GW_SLOT:-$PREFERRED_SIM_SLOT}" + sec_slot="${SECONDARY_GW_SLOT:-0}" fi - } - get_ussd_state() { - mmcli -m any --3gpp-ussd-status -K 2>/dev/null | \ - awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.3gpp.ussd.status" || $1 == "modem.3gpp.ussd.state") {print $2; exit}}' || true - } - prev_notif="$(get_ussd_prop NetworkNotification)" - prev_req="$(get_ussd_prop NetworkRequest)" - ussd_st="$(get_ussd_state)" - if [ "$ussd_mode" = "respond" ] && [ "$ussd_st" != "user-response" ]; then - case "$ussd_code" in - \**\#|\#*\#) - ussd_mode="initiate" - ;; - esac fi - ev_file="/tmp/ussd_dbus_$$.log" - rm -f "$ev_file" - if command -v dbus-monitor >/dev/null 2>&1; then - dbus-monitor --system "interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.freedesktop.ModemManager1.Modem.Modem3gpp.Ussd'" >"$ev_file" 2>/dev/null & - ev_pid=$! - else - ev_pid="" - fi - cleanup_ev() { - if [ -n "${ev_pid:-}" ]; then - kill "$ev_pid" 2>/dev/null || true - wait "$ev_pid" 2>/dev/null || true + # If requested SIM is Secondary GW, try QMI VOICE USSD on sub=1 or secondary AT port first + if [ "$req_sim" = "$sec_slot" ] && [ "$sec_slot" != "0" ] && command -v python3 >/dev/null 2>&1; then + qmi_ussd="$(python3 - "$ussd_mode" "$ussd_code" << 'PY' 2>/dev/null || true +import socket, struct, select, sys, time + +mode = sys.argv[1] +code = sys.argv[2] +AF_QIPCRTR = 42 +QRTR_PORT_CTRL = 0xfffffffe +QRTR_TYPE_NEW_SERVER = 4 +QRTR_TYPE_NEW_LOOKUP = 10 +QMI_SERVICE_VOICE = 9 + +ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) +node, _ = ls.getsockname() +ls.sendto(struct.pack("= 20: + cmd, srv, inst, srv_node, srv_port = struct.unpack("= 3: + dcs = val[0] + ulen = val[1] + raw = val[2:2+ulen] + if dcs in (2, 0x48) or (len(raw) >= 2 and raw[0] == 0x04): + txt = raw.decode("utf-16-be", errors="ignore").strip() + else: + txt = raw.decode("utf-8", errors="ignore").strip() + if txt: + print(txt) + s.close() + sys.exit(0) +s.close() +sys.exit(1) +PY +)" + if [ -n "$qmi_ussd" ]; then + printf "%s\n" "$qmi_ussd" + exit 0 fi + fi + if [ "$req_sim" = "$prim_slot" ]; then + mm_state="$(mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.generic.state") {print $2; exit}}' || true)" + if [ "$mm_state" = "disabled" ] || [ -z "$mm_state" ]; then + mmcli -m any -e >/dev/null 2>&1 || true + sleep 1 + fi + modem_dbus_path="$(mmcli -m any -K 2>/dev/null | awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.dbus-path") {print $2; exit}}' || true)" + [ -z "$modem_dbus_path" ] && modem_dbus_path="/org/freedesktop/ModemManager1/Modem/0" + get_ussd_prop() { + prop_name="$1" + if [ -n "$modem_dbus_path" ] && command -v busctl >/dev/null 2>&1 && command -v jq >/dev/null 2>&1; then + busctl -j get-property org.freedesktop.ModemManager1 "$modem_dbus_path" \ + org.freedesktop.ModemManager1.Modem.Modem3gpp.Ussd "$prop_name" 2>/dev/null | \ + jq -r '.data // empty' 2>/dev/null || true + fi + } + get_ussd_state() { + mmcli -m any --3gpp-ussd-status -K 2>/dev/null | \ + awk -F':[[:space:]]*' '{gsub(/[[:space:]]+$/, "", $1); if ($1 == "modem.3gpp.ussd.status" || $1 == "modem.3gpp.ussd.state") {print $2; exit}}' || true + } + prev_notif="$(get_ussd_prop NetworkNotification)" + prev_req="$(get_ussd_prop NetworkRequest)" + ussd_st="$(get_ussd_state)" + if [ "$ussd_mode" = "respond" ] && [ "$ussd_st" != "user-response" ]; then + case "$ussd_code" in + \**\#|\#*\#) + ussd_mode="initiate" + ;; + esac + fi + ev_file="/tmp/ussd_dbus_$$.log" rm -f "$ev_file" - } - mm_rc=0 - mm_out="" - if [ "$ussd_mode" = "respond" ]; then - mm_out="$(mmcli --timeout=30 -m any --3gpp-ussd-respond="$ussd_code" 2>&1)" || mm_rc=$? - else - if [ "$ussd_st" = "active" ] || [ "$ussd_st" = "user-response" ]; then - mmcli -m any --3gpp-ussd-cancel >/dev/null 2>&1 || true + if command -v dbus-monitor >/dev/null 2>&1; then + dbus-monitor --system "interface='org.freedesktop.DBus.Properties',member='PropertiesChanged',arg0='org.freedesktop.ModemManager1.Modem.Modem3gpp.Ussd'" >"$ev_file" 2>/dev/null & + ev_pid=$! + else + ev_pid="" fi - mm_out="$(mmcli --timeout=30 -m any --3gpp-ussd-initiate="$ussd_code" 2>&1)" || mm_rc=$? - fi - if [ "$mm_rc" -eq 0 ] && [ -n "$mm_out" ]; then - reply="$(printf "%s\n" "$mm_out" | sed \ - -e "1s/^USSD session initiated; new reply from network: '//" \ - -e "1s/^response successfully sent in USSD session; new reply from network: '//" \ - -e "1s/^USSD response sent; new reply from network: '//" \ - -e "\$s/'$//")" - if [ -n "$reply" ]; then - cleanup_ev - printf "%s\n" "$reply" - exit 0 + cleanup_ev() { + if [ -n "${ev_pid:-}" ]; then + kill "$ev_pid" 2>/dev/null || true + wait "$ev_pid" 2>/dev/null || true + fi + rm -f "$ev_file" + } + mm_rc=0 + mm_out="" + if [ "$ussd_mode" = "respond" ]; then + mm_out="$(mmcli --timeout=30 -m any --3gpp-ussd-respond="$ussd_code" 2>&1)" || mm_rc=$? + else + if [ "$ussd_st" = "active" ] || [ "$ussd_st" = "user-response" ]; then + mmcli -m any --3gpp-ussd-cancel >/dev/null 2>&1 || true + fi + mm_out="$(mmcli --timeout=30 -m any --3gpp-ussd-initiate="$ussd_code" 2>&1)" || mm_rc=$? fi - fi - # Check if the USSD response arrived asynchronously via D-Bus properties - w=0 - while [ "$w" -lt 15 ]; do - cur_req="$(get_ussd_prop NetworkRequest)" - cur_notif="$(get_ussd_prop NetworkNotification)" - cur_st="$(get_ussd_state)" - if [ -n "$cur_req" ] && { [ "$cur_req" != "$prev_req" ] || [ "$cur_st" = "user-response" ] || grep -q "NetworkRequest" "$ev_file" 2>/dev/null; }; then - cleanup_ev - printf "%s\n" "$cur_req" - exit 0 + if [ "$mm_rc" -eq 0 ] && [ -n "$mm_out" ]; then + reply="$(printf "%s\n" "$mm_out" | sed \ + -e "1s/^USSD session initiated; new reply from network: '//" \ + -e "1s/^response successfully sent in USSD session; new reply from network: '//" \ + -e "1s/^USSD response sent; new reply from network: '//" \ + -e "\$s/'$//")" + if [ -n "$reply" ]; then + cleanup_ev + printf "%s\n" "$reply" + exit 0 + fi fi - if [ -n "$cur_notif" ] && { [ "$cur_notif" != "$prev_notif" ] || grep -q "NetworkNotification" "$ev_file" 2>/dev/null || printf "%s" "$mm_out" | grep -q "USSD terminated by network"; }; then - cleanup_ev - printf "%s\n" "$cur_notif" - exit 0 - fi - if [ "$cur_st" != "active" ] && [ "$w" -ge 3 ]; then - if [ -n "$cur_req" ]; then + # Check if the USSD response arrived asynchronously via D-Bus properties + w=0 + while [ "$w" -lt 15 ]; do + cur_req="$(get_ussd_prop NetworkRequest)" + cur_notif="$(get_ussd_prop NetworkNotification)" + cur_st="$(get_ussd_state)" + if [ -n "$cur_req" ] && { [ "$cur_req" != "$prev_req" ] || [ "$cur_st" = "user-response" ] || grep -q "NetworkRequest" "$ev_file" 2>/dev/null; }; then cleanup_ev printf "%s\n" "$cur_req" exit 0 fi - if [ -n "$cur_notif" ]; then + if [ -n "$cur_notif" ] && { [ "$cur_notif" != "$prev_notif" ] || grep -q "NetworkNotification" "$ev_file" 2>/dev/null || printf "%s" "$mm_out" | grep -q "USSD terminated by network"; }; then cleanup_ev printf "%s\n" "$cur_notif" exit 0 fi - break - fi - sleep 0.2 - w=$((w + 1)) - done - cleanup_ev - # Fallback to direct AT+CUSD on the active SIM AT port - if [ "$PREFERRED_SIM_SLOT" = "2" ]; then + if [ "$cur_st" != "active" ] && [ "$w" -ge 3 ]; then + if [ -n "$cur_req" ]; then + cleanup_ev + printf "%s\n" "$cur_req" + exit 0 + fi + if [ -n "$cur_notif" ]; then + cleanup_ev + printf "%s\n" "$cur_notif" + exit 0 + fi + break + fi + sleep 0.2 + w=$((w + 1)) + done + cleanup_ev + fi + # Fallback to direct AT+CUSD on the requested SIM AT port + if [ "$req_sim" = "$sec_slot" ] && [ "$sec_slot" != "0" ]; then + at_candidates="/dev/wwan0at1 /dev/wwan0at0" + elif [ "$req_sim" = "2" ]; then at_candidates="/dev/wwan0at1 /dev/wwan0at0" else at_candidates="/dev/wwan0at0 /dev/wwan0at1" @@ -1153,7 +1517,7 @@ case "$cmd" in exit 0 fi done - if [ -n "$mm_out" ]; then + if [ -n "${mm_out:-}" ]; then printf "%s\n" "$mm_out" else echo "ERROR: USSD request failed" @@ -1161,6 +1525,852 @@ case "$cmd" in exit 1 ;; + sms-send) + req_slot="${2:-$PREFERRED_SIM_SLOT}" + dest_num="${3:-}" + msg_src="${4:-}" + if [ -z "$dest_num" ] || [ -z "$msg_src" ]; then + echo "Usage: $0 sms-send <1|2> " >&2 + exit 1 + fi + prim_slot="$PREFERRED_SIM_SLOT" + sec_slot="0" + if detect_qmicli_modem; then + QMI_CARDS="$($QMICLI_MODEM --uim-get-card-status 2>/dev/null || true)" + if [ -n "$QMI_CARDS" ]; then + eval "$(parse_uim_card_status "$QMI_CARDS" "$PREFERRED_SIM_SLOT")" + prim_slot="${PRIMARY_GW_SLOT:-$PREFERRED_SIM_SLOT}" + sec_slot="${SECONDARY_GW_SLOT:-0}" + fi + fi + target_sub=0 + if [ "$req_slot" = "$sec_slot" ] && [ "$sec_slot" != "0" ]; then + target_sub=1 + fi + python3 - "$target_sub" "$dest_num" "$msg_src" << 'PY' +import os, random, select, socket, struct, sys + +sub = int(sys.argv[1]) if sys.argv[1].isdigit() else 0 +dest = "".join(c for c in sys.argv[2] if c in "+0123456789") +src = sys.argv[3] +if os.path.isfile(src): + with open(src, "r", encoding="utf-8", errors="replace") as f: + text = f.read() +else: + text = src +if text.endswith("\n"): + text = text[:-1] + +if not dest: + print("ERROR: Invalid destination number", file=sys.stderr) + sys.exit(1) + +AF_QIPCRTR = 42 +QRTR_PORT_CTRL = 0xfffffffe +QRTR_TYPE_NEW_SERVER = 4 +QRTR_TYPE_NEW_LOOKUP = 10 +QMI_SERVICE_WMS = 5 + +ls = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) +node, _ = ls.getsockname() +ls.sendto(struct.pack("= 20: + cmd, srv, inst, srv_node, srv_port = struct.unpack("= 8: + packed.append(cur & 0xFF) + cur >>= 8 + shift -= 8 + if shift > 0: + packed.append(cur & 0xFF) + # 0x00 (default SMSC), 0x01 (SMS-SUBMIT), 0x00 (MR), DA, 0x00 (PID), 0x00 (DCS 7-bit), UDL, UD + return [b"\x00\x01\x00" + da + b"\x00\x00" + bytes([len(septets)]) + bytes(packed)] + + u16 = msg.encode("utf-16-be") + if len(u16) <= 140: + return [b"\x00\x01\x00" + da + b"\x00\x08" + bytes([len(u16)]) + u16] + + chunks = [u16[i:i+134] for i in range(0, len(u16), 134)] + ref = random.randint(1, 254) + total = len(chunks) + pdus = [] + for idx, chunk in enumerate(chunks, 1): + udh = bytes([0x05, 0x00, 0x03, ref, total, idx]) + ud = udh + chunk + # 0x41 = SMS-SUBMIT + UDHI + pdus.append(b"\x00\x41\x00" + da + b"\x00\x08" + bytes([len(ud)]) + ud) + return pdus + +s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) +txn = 1 +s.sendto(struct.pack("= 7 and resp[0] == 0x02: + r_txn, r_msg, _ = struct.unpack("= 4: + res, err = struct.unpack("= 20: + cmd, srv, inst, srv_node, srv_port = struct.unpack("= 7 and resp[0] == 0x02: + r_txn, r_msg, _ = struct.unpack("= 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("= 1: + cnt = raw_num[0] + off = 1 + for _ in range(cnt): + if off + 3 > len(raw_num): + break + cid, _, nlen = struct.unpack("= 4 and struct.unpack(" + target_sub = 1 + target_cid = 0 + if arg1.startswith("sub0_"): + target_sub = 0 + target_cid = int(arg1.split("_", 1)[1]) + elif arg1.startswith("sub1_"): + target_sub = 1 + target_cid = int(arg1.split("_", 1)[1]) + elif arg1.isdigit() and sub_cmd != "call-dtmf": + target_cid = int(arg1) + + s = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) + qmi_req(s, 1, 0x0044, struct.pack("= 4 and struct.unpack("= 20: + cmd, srv, inst, srv_node, srv_port = struct.unpack("= 7 and resp[0] == 0x02: + r_txn, r_msg, _ = struct.unpack("?" + "\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 = [] + 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 + 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 decode_sms_deliver(pdu): + try: + if len(pdu) < 10: + return None + smsc_len = pdu[0] + pos = 1 + smsc_len + if pos >= len(pdu): + return None + first_octet = pdu[pos] + mti = first_octet & 0x03 + if mti not in (0, 2): + return None + udhi = (first_octet & 0x40) != 0 + pos += 1 + oa_digits = pdu[pos] + oa_ton_npi = pdu[pos + 1] + oa_byte_len = (oa_digits + 1) // 2 + 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 + if pos + 9 > len(pdu): + return None + pid = pdu[pos] + dcs = pdu[pos + 1] + scts = pdu[pos + 2 : pos + 9] + udl = pdu[pos + 9] + ud = pdu[pos + 10 :] + + # Decode SCTS (YY MM DD HH MM SS TZ) + def unbcd(b): + return ((b & 0x0F) * 10) + ((b >> 4) & 0x0F) + try: + 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]) + iso_ts = f"{yr:04d}-{mo:02d}-{dy:02d}T{hr:02d}:{mi:02d}:{sc:02d}" + except Exception: + iso_ts = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S") + + 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 + 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] + + # Determine alphabet from DCS + if (dcs & 0xC0) == 0x00: + alphabet = (dcs >> 2) & 0x03 + elif (dcs & 0xF0) == 0xF0: + alphabet = 1 if (dcs & 0x04) else 0 + else: + alphabet = 0 + + if alphabet == 2: + payload = ud[udh_bytes : udl] + text = payload.decode("utf-16-be", errors="replace") + elif alphabet == 1: + payload = ud[udh_bytes : udl] + 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) + + return { + "sender": sender or "Unknown", + "time": iso_ts, + "text": text, + "ref": csms_ref, + "total": csms_total, + "seq": csms_seq, + } + except Exception: + return None + +multipart_buf = {} + +def deliver_sms_to_sxmo(sender, iso_ts, text, sim_slot): + num_dir = os.path.join(LOG_DIR, sender) + os.makedirs(num_dir, exist_ok=True) + sms_file = os.path.join(num_dir, "sms.txt") + now_str = datetime.datetime.now().astimezone().isoformat(timespec="seconds") + 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) + tsv_text = text.replace("\t", " ").replace("\r", " ").replace("\n", " ") + with open(os.path.join(LOG_DIR, "modemlog.tsv"), "a", encoding="utf-8") as f: + f.write(f"{now_str}\trecv_txt\t{sender}\t[SIM {sim_slot}] {tsv_text}\n") + try: + subprocess.run(["chown", "-R", "user:user", LOG_DIR], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + except Exception: + pass + send_fifo("/tmp/dwm_plugin_sms.fifo", "REFRESH") + safe_sender = sender.replace("'", "") + safe_text = text.replace("'", "") + run_user_cmd(f"sxmo_hook_sms.sh '{safe_sender}' '{safe_text}'") + +def handle_decoded_sms(info, sim_slot): + if not info: + return + if info["ref"] is not None and info["total"] > 1: + key = (info["sender"], info["ref"], info["total"]) + parts = multipart_buf.setdefault(key, {"ts": time.time(), "segs": {}}) + parts["segs"][info["seq"]] = info["text"] + if len(parts["segs"]) >= info["total"]: + full_text = "".join(parts["segs"].get(i, "") for i in range(1, info["total"] + 1)) + del multipart_buf[key] + deliver_sms_to_sxmo(info["sender"], info["time"], full_text, sim_slot) + else: + deliver_sms_to_sxmo(info["sender"], info["time"], info["text"], sim_slot) + +def poll_stored_sms(wms_sock, wms_addr, txn, sim_slot): + 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(" len(raw_list): + break + idx, tag = struct.unpack("= 4: + dlen = struct.unpack("= 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("= 1: + cnt = raw_num[0] + off = 1 + for _ in range(cnt): + if off + 3 > len(raw_num): + break + cid, _, nlen = struct.unpack("= 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_. + 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 != "terminated": + try: + open(os.path.join(CALLS_DIR, f"{call_key}.{st}"), "w").close() + except Exception: + pass + + if st == prev: + continue + active_calls[cid] = {"state": st, "num": num, "dir": c["dir"]} + + if st == "ringing-in": + with open(os.path.join(LOG_DIR, "modemlog.tsv"), "a", encoding="utf-8") as f: + f.write(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_hook_ring.sh '{num}'") + elif st in ("dialing", "ringing-out"): + set_q6voiced_audio(True) + if prev not in ("dialing", "ringing-out"): + with open(os.path.join(LOG_DIR, "modemlog.tsv"), "a", encoding="utf-8") as f: + f.write(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": + run_user_cmd("pkill -f sxmo_ring.sh || true; pkill -f mpv || true") + set_q6voiced_audio(True) + with open(os.path.join(LOG_DIR, "modemlog.tsv"), "a", encoding="utf-8") as f: + f.write(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": + run_user_cmd("pkill -f sxmo_ring.sh || true") + evt = "call_missed" if prev == "ringing-in" else "call_hangup" + with open(os.path.join(LOG_DIR, "modemlog.tsv"), "a", encoding="utf-8") as f: + f.write(f"{now_str}\t{evt}\t{num}\t[SIM {sim_slot}]\n") + send_fifo("/tmp/dwm_plugin_callscreen.fifo", f"HANGUP {call_key}") + del active_calls[cid] + + has_live = any(v["state"] in ("dialing", "ringing-out", "active", "held") for v in active_calls.values()) + if not has_live and 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 = 1 + if uim_addr: + us = socket.socket(AF_QIPCRTR, socket.SOCK_DGRAM) + ut = qmi_req(us, uim_addr, 1, 0x002F) + us.close() + st_val = ut.get(0x10, b"") + if len(st_val) >= 6: + _, _, _, _, sec_gw_idx = struct.unpack("= 10 else (0, 0, 0, 0, 0xFFFF) + if sec_gw_idx != 0xFFFF: + sec_slot = ((sec_gw_idx >> 8) & 0xFF) + 1 + + 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("= 8: + # Transfer-route MT message: [ack_ind(1), txn_id(4), format(1), len(2), data...] + tr = tlvs[0x11] + dlen = struct.unpack("= 15.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() + time.sleep(2) +PY + ;; + sim-contacts-import) req_slot="${2:-auto}" if ! wait_for_qmicli_modem 3; then diff --git a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_battery.sh b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_battery.sh index 4d6a98d..a10cda2 100755 --- a/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_battery.sh +++ b/overlay/rootfs/usr/share/sxmo/default_hooks/sxmo_hook_battery.sh @@ -1,76 +1,119 @@ #!/bin/sh # configversion: d031535bc22ba19d69704317b8d50560 +export XDG_RUNTIME_DIR="${XDG_RUNTIME_DIR:-/run/user/10000}" +export DISPLAY="${DISPLAY:-:0}" +export PATH="/usr/share/sxmo/default_hooks:/usr/bin:/bin:/usr/sbin:/sbin:$PATH" + SET_LED_PATH="$XDG_RUNTIME_DIR/sxmo_hook_battery_set_led" -object="${1:-/org/freedesktop/UPower/devices/battery_default}" -event="${2:-device changed}" +if [ "${1:-}" = "udev" ]; then + object="/org/freedesktop/UPower/devices/battery_default" + event="device changed" + if [ "${2:-}" != "recheck" ]; then + (sleep 2; "$0" udev recheck >/dev/null 2>&1) & + fi +else + object="${1:-/org/freedesktop/UPower/devices/battery_default}" + event="${2:-device changed}" +fi case "$event" in - "device changed") ;; - *) exit 0 ;; + "device changed") ;; + *) exit 0 ;; esac case "$object" in - */battery_*) - raw_name="${object##*/battery_}" - ;; - *) - exit 0 - ;; + */battery_*) + raw_name="${object##*/battery_}" + ;; + *) + exit 0 + ;; esac sysfs_dir="" if [ -d "/sys/class/power_supply/$raw_name" ]; then - sysfs_dir="/sys/class/power_supply/$raw_name" - name="$raw_name" + sysfs_dir="/sys/class/power_supply/$raw_name" + name="$raw_name" else - for d in /sys/class/power_supply/*; do - [ -r "$d/type" ] || continue - read -r pstype < "$d/type" 2>/dev/null || continue - if [ "$pstype" = "Battery" ]; then - sysfs_dir="$d" - name="${d##*/}" - break - fi - done + for d in /sys/class/power_supply/*; do + [ -r "$d/type" ] || continue + read -r pstype < "$d/type" 2>/dev/null || continue + if [ "$pstype" = "Battery" ]; then + sysfs_dir="$d" + name="${d##*/}" + break + fi + done fi if [ -n "$sysfs_dir" ] && [ -r "$sysfs_dir/capacity" ] && [ -r "$sysfs_dir/status" ]; then - read -r percentage < "$sysfs_dir/capacity" 2>/dev/null || percentage="" - read -r raw_status < "$sysfs_dir/status" 2>/dev/null || raw_status="" - case "$raw_status" in - "Full"|"full") state="fully-charged" ;; - "Charging"|"charging") state="charging" ;; - "Discharging"|"discharging"|"Not charging"|"not charging") state="discharging" ;; - *) state="unknown" ;; - esac + read -r percentage < "$sysfs_dir/capacity" 2>/dev/null || percentage="" + read -r raw_status < "$sysfs_dir/status" 2>/dev/null || raw_status="" + case "$raw_status" in + "Full"|"full") state="fully-charged" ;; + "Charging"|"charging") state="charging" ;; + "Discharging"|"discharging"|"Not charging"|"not charging") state="discharging" ;; + *) state="unknown" ;; + esac else - exit 0 + exit 0 +fi + +chgr_online="" +if [ -r "/sys/class/power_supply/pm8916-lbc-chgr/online" ]; then + read -r chgr_online < "/sys/class/power_supply/pm8916-lbc-chgr/online" 2>/dev/null || chgr_online="" +else + for d in /sys/class/power_supply/*; do + [ -r "$d/type" ] && [ -r "$d/online" ] || continue + read -r pstype < "$d/type" 2>/dev/null || continue + case "$pstype" in + USB*|Mains) + read -r chgr_online < "$d/online" 2>/dev/null || chgr_online="" + [ -n "$chgr_online" ] && break + ;; + esac + done +fi + +if [ "$chgr_online" = "1" ] && [ "$state" = "discharging" ]; then + case "$percentage" in + ''|*[!0-9]*) state="charging" ;; + *) + if [ "$percentage" -ge 99 ]; then + state="fully-charged" + else + state="charging" + fi + ;; + esac +elif [ "$chgr_online" = "0" ] && { [ "$state" = "charging" ] || [ "$state" = "fully-charged" ]; }; then + state="discharging" fi if [ -z "$name" ] || [ -z "$state" ] || [ -z "$percentage" ] || [ "$state" = "unknown" ]; then - exit 0 + exit 0 fi if [ -z "$SXMO_DISABLE_LEDS" ]; then - if [ "$percentage" -lt 25 ] && [ ! -f "$SET_LED_PATH" ]; then - touch "$SET_LED_PATH" - sxmo_led.sh set red 100 - elif [ -f "$SET_LED_PATH" ]; then - rm "$SET_LED_PATH" - sxmo_led.sh set red 0 - fi + if [ "$percentage" -lt 25 ] && [ ! -f "$SET_LED_PATH" ]; then + touch "$SET_LED_PATH" + sxmo_led.sh set red 100 + elif [ -f "$SET_LED_PATH" ]; then + rm "$SET_LED_PATH" + sxmo_led.sh set red 0 + fi fi CACHE_FILE="${XDG_RUNTIME_DIR:-/tmp}/sxmo_bat_state_${name}" ICON_FILE="${XDG_RUNTIME_DIR:-/run/user/10000}/sxmo_status/${SXMO_STATUS_NAME:-default}/040-battery-icon-${name}" NEW_VAL="${state}:${percentage}" if [ -r "$CACHE_FILE" ] && [ -f "$ICON_FILE" ]; then - read -r OLD_VAL < "$CACHE_FILE" 2>/dev/null || OLD_VAL="" - if [ "$OLD_VAL" = "$NEW_VAL" ]; then - exit 0 - fi + read -r OLD_VAL < "$CACHE_FILE" 2>/dev/null || OLD_VAL="" + if [ "$OLD_VAL" = "$NEW_VAL" ]; then + exit 0 + fi fi printf '%s\n' "$NEW_VAL" > "$CACHE_FILE" diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/calllog.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/calllog.so index 4c2dafe..f35bf7d 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/calllog.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/calllog.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so index 53b9976..f26ee00 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/callscreen.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/contacts.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/contacts.so index 985a09a..16d6ba8 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/contacts.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/contacts.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so index 3c3a9b8..ebe7a33 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/dialer.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so index 6b491df..26155d4 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/modem.so differ diff --git a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sms.so b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sms.so index a59423e..8e2c40f 100755 Binary files a/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sms.so and b/prebuilt/sxmo-x11/usr/lib/dwm/plugins/sms.so differ diff --git a/src/dwm-plugins/callscreen_plugin.cpp b/src/dwm-plugins/callscreen_plugin.cpp index 56a5480..0db06f9 100644 --- a/src/dwm-plugins/callscreen_plugin.cpp +++ b/src/dwm-plugins/callscreen_plugin.cpp @@ -165,6 +165,7 @@ enum class CallState { Outgoing = 2, Active = 3, Ended = 4, + SelectSim = 5, }; std::string formatTimerSec(int totalSec) { @@ -435,6 +436,8 @@ int callscreen_run_main(int argc, char** argv) { std::string callId; std::string callNumber; std::string contactName; + int activeSimSlot = 0; + DualSimInfo simInfo = queryDualSimInfo(); std::string endReason = "CALL ENDED"; std::string statusNotice; int64_t statusNoticeUntilMs = 0; @@ -737,19 +740,27 @@ int callscreen_run_main(int argc, char** argv) { XftColor* stateCol = &colBlue; unsigned long stateAccentPx = theme.spec.accent; - if (callState == CallState::Incoming) { + std::string simTag = (activeSimSlot == 1 || activeSimSlot == 2) + ? (" [SIM " + std::to_string(activeSimSlot) + "]") + : ""; + if (callState == CallState::SelectSim) { + stateIcon = kIconOutCall; + stateBadge = "SELECT SIM CARD"; + stateCol = &colYellow; + stateAccentPx = theme.spec.accent; + } else if (callState == CallState::Incoming) { stateIcon = ringMuted ? kIconSoundOff : kIconInCall; - stateBadge = ringMuted ? "RING SILENCED" : "INCOMING CALL"; + stateBadge = (ringMuted ? "RING SILENCED" : "INCOMING") + simTag; stateCol = ringMuted ? &colYellow : &colGreen; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Outgoing) { stateIcon = kIconOutCall; - stateBadge = "DIALING..."; + stateBadge = "DIALING" + simTag + "..."; stateCol = &colYellow; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Active) { stateIcon = kIconPhone; - stateBadge = "IN CALL"; + stateBadge = "IN CALL" + simTag; stateCol = &colGreen; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Ended) { @@ -760,15 +771,17 @@ int callscreen_run_main(int argc, char** argv) { } drawPango(layoutIcon, stateCol, 8, 3, 22, stateIcon); - drawPango(layoutSmall, stateCol, 28, 3, 22, stateBadge, 138); + drawPango(layoutSmall, stateCol, 28, 3, 22, stateBadge, 148); int elapsedSec = 0; if (callState == CallState::Ended) { elapsedSec = lastFinalDurationSec; - } else if (callStartMs > 0 && callState != CallState::Idle) { + } else if (callStartMs > 0 && callState != CallState::Idle && + callState != CallState::SelectSim) { elapsedSec = static_cast((now - callStartMs) / 1000); } - if (callState != CallState::Idle || elapsedSec > 0) { + if ((callState != CallState::Idle && callState != CallState::SelectSim) || + elapsedSec > 0) { std::string timerStr = formatTimerSec(elapsedSec); int tw = pangoWidth(layoutMain, timerStr); drawPango(layoutMain, @@ -819,6 +832,9 @@ int callscreen_run_main(int argc, char** argv) { } else if (dtmfMode) { std::string dtmfLabel = "DTMF (0-9/*/#): " + (dtmfSent.empty() ? "_" : dtmfSent); drawPango(layoutSmall, &colYellow, 8, 88, 26, dtmfLabel, 224); + } else if (callState == CallState::SelectSim) { + drawPango(layoutSmall, &colYellow, 8, 88, 26, + "[1/2] Choose SIM [OK/Call] Dial", 224); } else if (callState == CallState::Incoming) { drawPango(layoutSmall, &colLight, 8, 88, 26, "[Call] Answer [*] Mute [End] Reject", 224); @@ -843,7 +859,51 @@ int callscreen_run_main(int argc, char** argv) { XFillRectangle(dpy, pix, gc, 0, kHeaderH - 2, kWinWidth, 2); // 2. Body Area (kBodyY..kBodyY+kBodyH) - if (callState == CallState::Incoming) { + if (callState == CallState::SelectSim) { + constexpr int kSimRows = 2; + for (int i = 0; i < kSimRows; ++i) { + int slotNum = i + 1; + int ry = kBodyY + (i * kBodyH) / kSimRows; + int nextRy = kBodyY + ((i + 1) * kBodyH) / kSimRows; + int rowH = nextRy - ry; + bool isSel = (selectedRow == i); + bool isPref = (simInfo.preferredSlot == slotNum); + + XSetForeground(dpy, gc, + isSel ? theme.spec.selBg + : ((i % 2 == 0) ? theme.spec.bgAltEven : theme.spec.bgAltOdd)); + XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH); + if (isSel) { + XSetForeground(dpy, gc, theme.spec.accent); + XFillRectangle(dpy, pix, gc, 0, ry, 4, rowH); + } + + std::string op = (slotNum == 1) ? simInfo.slot1Operator : simInfo.slot2Operator; + std::string rat = (slotNum == 1) ? simInfo.slot1Rat : simInfo.slot2Rat; + std::string msisdn = (slotNum == 1) ? simInfo.slot1Number : simInfo.slot2Number; + + std::string title = "[" + std::to_string(slotNum) + "] SIM " + std::to_string(slotNum); + if (!op.empty()) { + title += " - " + op; + } + if (!rat.empty()) { + title += " (" + rat + ")"; + } + std::string subLine = msisdn.empty() + ? (isPref ? "Primary / Default SIM" : "Standby SIM") + : msisdn; + std::string badge = isPref ? "DEFAULT" : "STANDBY"; + int bw = pangoWidth(layoutSmall, badge); + + drawPango(layoutIcon, isSel ? &colGreen : &colBlue, 10, ry, rowH, kIconPhone); + drawPango(layoutMain, isSel ? &colWhite : &colLight, 34, ry + 12, 24, + title, std::max(80, kWinWidth - bw - 48)); + drawPango(layoutSmall, isSel ? &colYellow : &colMuted, 34, ry + 38, 20, + subLine, std::max(80, kWinWidth - 44)); + drawPango(layoutSmall, isPref ? &colGreen : &colMuted, + kWinWidth - bw - 8, ry + 12, 24, badge); + } + } else if (callState == CallState::Incoming) { struct IncomingAction { const char* icon; const char* title; @@ -977,7 +1037,14 @@ int callscreen_run_main(int argc, char** argv) { XftColor* centerCol = &colGreen; XftColor* rightCol = &colRed; - if (callState == CallState::Incoming) { + if (callState == CallState::SelectSim) { + leftLabel = "Dial"; + centerLabel = (selectedRow == 1) ? "CALL SIM 2" : "CALL SIM 1"; + rightLabel = "Cancel"; + leftCol = &colGreen; + centerCol = &colGreen; + rightCol = &colRed; + } else if (callState == CallState::Incoming) { leftLabel = "Accept"; centerLabel = "ANSWER"; rightLabel = "Reject"; @@ -1098,14 +1165,18 @@ int callscreen_run_main(int argc, char** argv) { size_t dot = name.find('.'); if (dot != std::string::npos && dot > 0) { std::string candidate = name.substr(0, dot); - bool allDigits = true; - for (char c : candidate) { - if (!std::isdigit(static_cast(c))) { - allDigits = false; - break; + bool validId = (candidate.rfind("sub1_", 0) == 0 || + candidate.rfind("sub0_", 0) == 0); + if (!validId) { + validId = !candidate.empty(); + for (char c : candidate) { + if (!std::isdigit(static_cast(c))) { + validId = false; + break; + } } } - if (allDigits) { + if (validId) { ::closedir(d); callId = candidate; return callId; @@ -1200,11 +1271,19 @@ int callscreen_run_main(int argc, char** argv) { } std::string cid = resolveActiveModemCallId(); if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { - char cmd[160]; - std::snprintf(cmd, sizeof(cmd), - "mmcli -m any -o '%s' --send-dtmf='%c' >/dev/null 2>&1", - cid.c_str(), ch); - runAsyncCmd(cmd); + if (cid.rfind("sub", 0) == 0) { + char cmd[160]; + std::snprintf(cmd, sizeof(cmd), + "doas -n /usr/libexec/msm-modem-uim-selection call-dtmf '%c' >/dev/null 2>&1", + ch); + runAsyncCmd(cmd); + } else { + char cmd[160]; + std::snprintf(cmd, sizeof(cmd), + "mmcli -m any -o '%s' --send-dtmf='%c' >/dev/null 2>&1", + cid.c_str(), ch); + runAsyncCmd(cmd); + } } render(); }; @@ -1343,7 +1422,7 @@ int callscreen_run_main(int argc, char** argv) { } return; } - if (line == "HANGUP") { + if (line == "HANGUP" || line.rfind("HANGUP ", 0) == 0) { if (callState == CallState::Incoming || callState == CallState::Outgoing || callState == CallState::Active) { hangupCall(); @@ -1376,21 +1455,51 @@ int callscreen_run_main(int argc, char** argv) { return; } - // Parse INCOMING / OUTGOING / ACTIVE / OPEN + // Parse PROMPT_SIM / INCOMING / OUTGOING / ACTIVE / OPEN std::istringstream iss(line); - std::string verb, arg1, arg2; - iss >> verb >> arg1 >> arg2; + std::string verb, arg1, arg2, arg3; + iss >> verb >> arg1 >> arg2 >> arg3; + + if (verb == "PROMPT_SIM") { + simInfo = queryDualSimInfo(true); + callId = "-"; + callNumber.clear(); + contactName.clear(); + updateCallerDetails("-", arg1); + callState = CallState::SelectSim; + selectedRow = (simInfo.preferredSlot == 2) ? 1 : 0; + activeSimSlot = 0; + writeActiveStateFiles(); + showWindow(); + return; + } if (verb == "OPEN" && !arg1.empty()) { std::string low = toLowerStr(arg1); if (low == "incoming" || low == "outgoing" || low == "active") { verb = (low == "incoming") ? "INCOMING" : ((low == "outgoing") ? "OUTGOING" : "ACTIVE"); arg1 = arg2.empty() ? "-" : arg2; - arg2.clear(); - iss >> arg2; + arg2 = arg3; + arg3.clear(); + iss >> arg3; } } + auto parseSimTag = [&](const std::string& cidStr, const std::string& tagStr) { + simInfo = queryDualSimInfo(); + if (tagStr == "SIM1") { + activeSimSlot = 1; + } else if (tagStr == "SIM2") { + activeSimSlot = 2; + } else if (cidStr.rfind("sub1_", 0) == 0) { + activeSimSlot = (simInfo.secondaryGwSlot > 0) ? simInfo.secondaryGwSlot : 1; + } else if (simInfo.dualSimActive) { + activeSimSlot = (simInfo.primaryGwSlot > 0) ? simInfo.primaryGwSlot : simInfo.preferredSlot; + } else { + activeSimSlot = 0; + } + }; + if (verb == "INCOMING") { callId.clear(); callNumber.clear(); @@ -1400,6 +1509,7 @@ int callscreen_run_main(int argc, char** argv) { lastRecordedSec = 0; recordedClipCount = 0; updateCallerDetails(arg1, arg2); + parseSimTag(arg1, arg3); callState = CallState::Incoming; callStartMs = nowMs(); ringMuted = false; @@ -1418,6 +1528,7 @@ int callscreen_run_main(int argc, char** argv) { lastRecordedSec = 0; recordedClipCount = 0; updateCallerDetails(arg1, arg2); + parseSimTag(arg1, arg3); callState = CallState::Outgoing; callStartMs = nowMs(); ringMuted = false; @@ -1434,6 +1545,9 @@ int callscreen_run_main(int argc, char** argv) { bool wasActive = (callState == CallState::Active); bool wasOutgoing = (callState == CallState::Outgoing); updateCallerDetails(arg1, arg2); + if (!arg3.empty() || activeSimSlot == 0) { + parseSimTag(arg1, arg3); + } callState = CallState::Active; if (!wasActive) { callStartMs = nowMs(); @@ -1463,6 +1577,16 @@ int callscreen_run_main(int argc, char** argv) { handleFifoCommand(forwardedCmd); } + auto startDialOnSim = [&](int chosenSim) { + std::string num = normalizePhone(callNumber); + if (num.empty()) { + return; + } + std::string simStr = (chosenSim == 2) ? "2" : "1"; + handleFifoCommand("OUTGOING - " + num + " SIM" + simStr); + runAsyncArgv("sxmo_modemdial.sh", "--sim", simStr.c_str(), num.c_str()); + }; + int xfd = ConnectionNumber(dpy); while (gRunning) { @@ -1553,8 +1677,9 @@ int callscreen_run_main(int argc, char** argv) { continue; } - // Physical Red End / Power button or Escape - if (sym == XK_Escape || sym == XF86XK_PowerOff || kc == 124) { + // Physical Red End / Power button or Escape / BackSpace in SelectSim + if (sym == XK_Escape || sym == XF86XK_PowerOff || kc == 124 || + (callState == CallState::SelectSim && sym == XK_BackSpace)) { writeSoftkeySuppress(nowMs() + 350); if (callState == CallState::Incoming || callState == CallState::Outgoing || callState == CallState::Active) { @@ -1572,7 +1697,10 @@ int callscreen_run_main(int argc, char** argv) { if (nowMs() < startupIgnoreUntilMs) { continue; } - if (callState == CallState::Incoming) { + if (callState == CallState::SelectSim) { + int chosenSim = (selectedRow == 1) ? 2 : 1; + startDialOnSim(chosenSim); + } else if (callState == CallState::Incoming) { acceptIncomingCall(); } else if (callState == CallState::Ended) { callState = CallState::Idle; @@ -1591,6 +1719,16 @@ int callscreen_run_main(int argc, char** argv) { // Keypad digits 0-9 / * / # char dialCh = mapDialKey(sym, kc, ev.xkey.state); if (dialCh != '\0') { + if (callState == CallState::SelectSim) { + if (dialCh == '1') { + selectedRow = 0; + startDialOnSim(1); + } else if (dialCh == '2') { + selectedRow = 1; + startDialOnSim(2); + } + continue; + } if (callState == CallState::Incoming) { if (dialCh == '*' || dialCh == '0') { silenceRing(); @@ -1635,14 +1773,18 @@ int callscreen_run_main(int argc, char** argv) { switch (sym) { case XK_Up: case XK_KP_Up: { - int maxRows = (callState == CallState::Incoming) ? 3 : 4; + int maxRows = (callState == CallState::SelectSim) + ? 2 + : ((callState == CallState::Incoming) ? 3 : 4); selectedRow = (selectedRow + maxRows - 1) % maxRows; render(); break; } case XK_Down: case XK_KP_Down: { - int maxRows = (callState == CallState::Incoming) ? 3 : 4; + int maxRows = (callState == CallState::SelectSim) + ? 2 + : ((callState == CallState::Incoming) ? 3 : 4); selectedRow = (selectedRow + 1) % maxRows; render(); break; @@ -1650,7 +1792,7 @@ int callscreen_run_main(int argc, char** argv) { case XK_Left: case XK_KP_Left: case XF86XK_AudioLowerVolume: - if (callState != CallState::Incoming) { + if (callState != CallState::Incoming && callState != CallState::SelectSim) { adjustVolume(-5); selectedRow = 3; render(); @@ -1659,7 +1801,7 @@ int callscreen_run_main(int argc, char** argv) { case XK_Right: case XK_KP_Right: case XF86XK_AudioRaiseVolume: - if (callState != CallState::Incoming) { + if (callState != CallState::Incoming && callState != CallState::SelectSim) { adjustVolume(+5); selectedRow = 3; render(); @@ -1670,7 +1812,10 @@ int callscreen_run_main(int argc, char** argv) { if (nowMs() < startupIgnoreUntilMs) { break; } - if (callState == CallState::Incoming) { + if (callState == CallState::SelectSim) { + int chosenSim = (selectedRow == 1) ? 2 : 1; + startDialOnSim(chosenSim); + } else if (callState == CallState::Incoming) { if (selectedRow == 0) { acceptIncomingCall(); } else if (selectedRow == 1) { @@ -1712,7 +1857,10 @@ int callscreen_run_main(int argc, char** argv) { runAsyncArgv("xdrawer"); } } else if (comb == 1) { - if (callState == CallState::Incoming) { + if (callState == CallState::SelectSim) { + int chosenSim = (selectedRow == 1) ? 2 : 1; + startDialOnSim(chosenSim); + } else if (callState == CallState::Incoming) { acceptIncomingCall(); } else if (callState == CallState::Outgoing || callState == CallState::Active) { dtmfMode = !dtmfMode; diff --git a/src/dwm-plugins/dialer_plugin.cpp b/src/dwm-plugins/dialer_plugin.cpp index c59954e..515aaa3 100644 --- a/src/dwm-plugins/dialer_plugin.cpp +++ b/src/dwm-plugins/dialer_plugin.cpp @@ -129,9 +129,13 @@ int dialer_run_main(int argc, char** argv) { Inactive = 0, Imei = 1, Ussd = 2, + SelectSim = 3, }; DialerModal modal = DialerModal::Inactive; DeviceImeis deviceImeis; + DualSimInfo simInfo; + int ussdSimSlot = 1; + int simPickIdx = 0; std::string ussdCode; std::string ussdResponse; std::string ussdReplyInput; @@ -420,6 +424,38 @@ int dialer_run_main(int argc, char** argv) { centerLabel = "OK"; rightLabel = "Close"; } + } else if (modal == DialerModal::SelectSim) { + XSetForeground(dpy, gc, theme.spec.bgOverlay); + XFillRectangle(dpy, pix, gc, 12, 34, kWinWidth - 24, 178); + XSetForeground(dpy, gc, theme.spec.accent); + XDrawRectangle(dpy, pix, gc, 12, 34, kWinWidth - 25, 177); + + drawPango(layoutMain, &colYellow, 20, 40, 24, + "Select SIM for " + ussdCode, kWinWidth - 40); + XSetForeground(dpy, gc, theme.spec.divider); + XFillRectangle(dpy, pix, gc, 18, 66, kWinWidth - 36, 1); + + for (int i = 0; i < 2; ++i) { + int slotNum = i + 1; + int ry = 74 + i * 64; + bool isSel = (simPickIdx == i); + XSetForeground(dpy, gc, isSel ? theme.spec.selBg : theme.spec.bgAltEven); + XFillRectangle(dpy, pix, gc, 18, ry, kWinWidth - 36, 56); + if (isSel) { + XSetForeground(dpy, gc, theme.spec.accent); + XFillRectangle(dpy, pix, gc, 18, ry, 4, 56); + } + std::string lbl = (slotNum == 1) ? simInfo.slot1Label : simInfo.slot2Label; + std::string msisdn = (slotNum == 1) ? simInfo.slot1Number : simInfo.slot2Number; + drawPango(layoutMain, isSel ? &colWhite : &colLight, 28, ry + 6, 22, + "[" + std::to_string(slotNum) + "] " + lbl, kWinWidth - 54); + drawPango(layoutSmall, isSel ? &colYellow : &colMuted, 28, ry + 30, 18, + msisdn.empty() ? ((simInfo.preferredSlot == slotNum) ? "Default SIM" : "Standby SIM") : msisdn, + kWinWidth - 54); + } + leftLabel = "Send"; + centerLabel = (simPickIdx == 1) ? "SIM 2" : "SIM 1"; + rightLabel = "Cancel"; } drawPango(layoutMain, &colLight, 6, sbY + 1, kSoftbarH - 1, leftLabel); @@ -456,16 +492,31 @@ int dialer_run_main(int argc, char** argv) { render(); }; - auto executeUssd = [&](const std::string& codeOrReply, bool isReply) { + auto executeUssd = [&](const std::string& codeOrReply, bool isReply, + int chosenSim = 0) { + if (chosenSim == 1 || chosenSim == 2) { + ussdSimSlot = chosenSim; + } else if (!isReply) { + simInfo = queryDualSimInfo(true); + if (simInfo.dualSimActive) { + ussdCode = codeOrReply; + simPickIdx = (simInfo.preferredSlot == 2) ? 1 : 0; + modal = DialerModal::SelectSim; + render(); + return; + } + ussdSimSlot = (simInfo.primaryGwSlot == 2) ? 2 : 1; + } modal = DialerModal::Ussd; if (!isReply || isUssdCode(codeOrReply)) { ussdCode = codeOrReply; } ussdScrollLine = 0; - ussdResponse = "Sending USSD " + codeOrReply + "..."; + ussdResponse = "Sending USSD " + codeOrReply + " [SIM " + + std::to_string(ussdSimSlot) + "]..."; ussdReplyInput.clear(); render(); - ussdResponse = sendModemUssd(codeOrReply, isReply, &ussdSessionActive); + ussdResponse = sendModemUssd(codeOrReply, isReply, &ussdSessionActive, ussdSimSlot); if (visible) { XRaiseWindow(dpy, win); grabPluginKeyboard(dpy, win); @@ -682,6 +733,27 @@ int dialer_run_main(int argc, char** argv) { char dialCh = mapDialKey(sym, ev.xkey.keycode, ev.xkey.state); + if (modal == DialerModal::SelectSim) { + if (dialCh == '1') { + simPickIdx = 0; + executeUssd(ussdCode, false, 1); + } else if (dialCh == '2') { + simPickIdx = 1; + executeUssd(ussdCode, false, 2); + } else if (sym == XK_Up || sym == XK_KP_Up || sym == XK_Down || sym == XK_KP_Down) { + simPickIdx = 1 - simPickIdx; + render(); + } else if (sym == XK_Return || sym == XK_KP_Enter || + sym == XF86XK_Phone || sym == XF86XK_PickupPhone || + sym == XF86XK_Send) { + executeUssd(ussdCode, false, (simPickIdx == 1) ? 2 : 1); + } else if (sym == XK_Escape || sym == XK_BackSpace) { + modal = DialerModal::Inactive; + render(); + } + continue; + } + if (modal == DialerModal::Imei) { if (sym == XK_Return || sym == XK_KP_Enter || sym == XK_Escape || sym == XK_BackSpace || sym == XF86XK_Phone || @@ -846,8 +918,8 @@ int dialer_run_main(int argc, char** argv) { executeUssd(target, false); } else { writeSoftkeySuppress(nowMs() + 350); - hideWindow(true); placePhoneCall(target); + hideWindow(false); } } break; @@ -869,7 +941,9 @@ int dialer_run_main(int argc, char** argv) { runAsyncArgv("xdrawer"); } } else if (comb == 1) { - if (modal == DialerModal::Imei) { + if (modal == DialerModal::SelectSim) { + executeUssd(ussdCode, false, (simPickIdx == 1) ? 2 : 1); + } else if (modal == DialerModal::Imei) { modal = DialerModal::Inactive; render(); } else if (modal == DialerModal::Ussd) { @@ -900,7 +974,10 @@ int dialer_run_main(int argc, char** argv) { render(); } } else if (comb == 2) { - if (modal == DialerModal::Imei) { + if (modal == DialerModal::SelectSim) { + modal = DialerModal::Inactive; + render(); + } else if (modal == DialerModal::Imei) { modal = DialerModal::Inactive; render(); } else if (modal == DialerModal::Ussd) { diff --git a/src/dwm-plugins/modem_plugin.cpp b/src/dwm-plugins/modem_plugin.cpp index 72fdaa9..6096b6f 100644 --- a/src/dwm-plugins/modem_plugin.cpp +++ b/src/dwm-plugins/modem_plugin.cpp @@ -56,8 +56,14 @@ struct SimSlotInfo { std::string upinState = "not-initialized"; int upinRetries = 0; int upukRetries = 0; + std::string regState; + std::string operatorName; + std::string rat; + std::string phoneNumber; + int rssi = 0; bool isActiveProvisioned = false; + bool isSecondaryProvisioned = false; bool isPreferred = false; bool needsPin() const { @@ -84,6 +90,8 @@ struct ModemStatusData { bool qmiAvailable = false; int preferredSlot = 1; int primaryGwSlot = 0; + int secondaryGwSlot = 0; + bool dualSimActive = false; SimSlotInfo slots[2]; bool mmPresent = false; @@ -261,6 +269,10 @@ ModemStatusData queryModemAndSimStatus() { if (!uimKv["PRIMARY_GW_SLOT"].empty()) { d.primaryGwSlot = std::atoi(uimKv["PRIMARY_GW_SLOT"].c_str()); } + if (!uimKv["SECONDARY_GW_SLOT"].empty()) { + d.secondaryGwSlot = std::atoi(uimKv["SECONDARY_GW_SLOT"].c_str()); + } + d.dualSimActive = (uimKv["DUAL_SIM_ACTIVE"] == "1"); d.nasRegState = uimKv["NAS_REG_STATE"]; d.nasOperator = uimKv["NAS_OPERATOR"]; d.nasMcc = uimKv["NAS_MCC"]; @@ -291,7 +303,15 @@ ModemStatusData queryModemAndSimStatus() { if (!uimKv[pfx + "UPUK_RETRIES"].empty()) { s.upukRetries = std::atoi(uimKv[pfx + "UPUK_RETRIES"].c_str()); } + s.regState = uimKv[pfx + "REG_STATE"]; + s.operatorName = uimKv[pfx + "OPERATOR"]; + s.rat = uimKv[pfx + "RAT"]; + s.phoneNumber = uimKv[pfx + "NUMBER"]; + if (!uimKv[pfx + "RSSI"].empty()) { + s.rssi = std::atoi(uimKv[pfx + "RSSI"].c_str()); + } s.isActiveProvisioned = (d.primaryGwSlot == (i + 1)); + s.isSecondaryProvisioned = (d.secondaryGwSlot == (i + 1)); s.isPreferred = (d.preferredSlot == (i + 1)); } @@ -740,8 +760,13 @@ int runModemApp(int argc, char** argv) { 10, cardY + 2, 22, kIconSim); std::string title = "SIM Slot " + std::to_string(s.slotNum); - if (s.isActiveProvisioned) { + if (status.dualSimActive && + (s.isActiveProvisioned || s.isSecondaryProvisioned)) { + title += s.isPreferred ? " [ACTIVE / DEFAULT]" : " [ACTIVE / DSDS]"; + } else if (s.isActiveProvisioned) { title += " [ACTIVE]"; + } else if (s.isSecondaryProvisioned) { + title += " [DSDS STANDBY]"; } else if (s.isPreferred) { title += " [PREF]"; } @@ -759,20 +784,40 @@ int runModemApp(int argc, char** argv) { line2Col = &colOrange; } else if (s.isActiveProvisioned) { std::string reg = status.regStatusLabel(); - if (!status.operatorName.empty()) { - reg += " - " + status.operatorName; + std::string op = !s.operatorName.empty() ? s.operatorName : status.operatorName; + std::string rat = !s.rat.empty() ? s.rat : status.accessTech; + if (!op.empty()) { + reg += " - " + op; } - if (!status.accessTech.empty()) { - reg += " [" + status.accessTech + "]"; + if (!rat.empty()) { + reg += " [" + rat + "]"; } line2 = reg; - if (status.isNetworkRegistered()) { + if (status.isNetworkRegistered() || s.regState == "registered") { line2Col = &colGreen; - } else if (status.isNetworkSearching()) { + } else if (status.isNetworkSearching() || s.regState == "searching") { line2Col = &colOrange; } else { line2Col = &colRed; } + } else if (s.isSecondaryProvisioned || s.regState == "registered" || + s.regState == "searching") { + if (s.regState == "registered") { + line2 = "Registered (DSDS)"; + if (!s.operatorName.empty()) { + line2 += " - " + s.operatorName; + } + if (!s.rat.empty()) { + line2 += " [" + s.rat + "]"; + } + line2Col = &colGreen; + } else if (s.regState == "searching") { + line2 = "Searching Network (DSDS)..."; + line2Col = &colOrange; + } else { + line2 = "Active Standby (" + s.appType + ")"; + line2Col = &colBlue; + } } else if (status.primaryGwSlot == 0) { line2 = "Present (Unactivated - Press Select)"; line2Col = &colOrange; @@ -796,8 +841,11 @@ int runModemApp(int argc, char** argv) { else if (pState == "blocked") pState = "PUK Req"; line3 = pState + " (PIN:" + std::to_string(s.pin1Retries) + " PUK:" + std::to_string(s.puk1Retries) + ")"; - if (s.isActiveProvisioned && !status.ownNumber.empty()) { - line3 += " " + status.ownNumber; + std::string numStr = !s.phoneNumber.empty() + ? s.phoneNumber + : (s.isActiveProvisioned ? status.ownNumber : ""); + if (!numStr.empty()) { + line3 += " " + numStr; } } else { line3 = "Insert nano-SIM & restart/switch"; @@ -820,7 +868,9 @@ int runModemApp(int argc, char** argv) { std::string(kIconRefresh) + (status.primaryGwSlot == 0 ? (" Activate SIM " + std::to_string(otherSlot)) - : (" Switch Active to SIM " + std::to_string(otherSlot))), + : (status.dualSimActive + ? (" Set Default SIM to Slot " + std::to_string(otherSlot)) + : (" Switch Active to SIM " + std::to_string(otherSlot)))), std::string(kIconUnlock) + " Unlock SIM (PIN / PUK)", std::string(kIconLock) + " Enable / Disable SIM PIN", std::string(kIconKey) + " Change SIM PIN Code", @@ -1043,7 +1093,7 @@ int runModemApp(int argc, char** argv) { drawPango(layoutMain, &colYellow, 20, 48, 24, hdr, kWinWidth - 40); const char* actLabels[5] = { - "Set as Active SIM Slot", + "Set as Default / Primary SIM", "Unlock SIM (Enter PIN)", "Unblock SIM (Enter PUK)", "Enable / Disable SIM PIN", @@ -1457,7 +1507,8 @@ int runModemApp(int argc, char** argv) { const auto& s = status.slots[row]; if (s.needsPin() || s.needsPuk()) { openPinOrPukModalForSlot(sNum); - } else if (s.state == "present" && !s.isActiveProvisioned) { + } else if (s.state == "present" && !s.isActiveProvisioned && + !s.isSecondaryProvisioned) { switchSimSlotNow(sNum); } else { targetSlot = sNum; diff --git a/src/dwm-plugins/phone_data.h b/src/dwm-plugins/phone_data.h index 7c315bd..c0cb505 100644 --- a/src/dwm-plugins/phone_data.h +++ b/src/dwm-plugins/phone_data.h @@ -1421,15 +1421,314 @@ inline bool clearCallLogFile(const std::string& logPath) { return true; } -inline void placePhoneCall(const std::string& rawNumber) { +struct DualSimInfo { + bool dualSimActive = false; + bool slot1Present = false; + bool slot2Present = false; + int preferredSlot = 1; + int primaryGwSlot = 1; + int secondaryGwSlot = 0; + std::string slot1Operator; + std::string slot2Operator; + std::string slot1Number; + std::string slot2Number; + std::string slot1Rat; + std::string slot2Rat; + std::string slot1Label; + std::string slot2Label; + std::string slot1Short; + std::string slot2Short; +}; + +inline DualSimInfo queryDualSimInfo(bool forceRefresh = false) { + static DualSimInfo cached; + static int64_t lastQueryMs = 0; + int64_t now = nowMs(); + if (!forceRefresh && lastQueryMs > 0 && (now - lastQueryMs) < 3000) { + return cached; + } + + DualSimInfo info; + { + std::ifstream conf("/etc/conf.d/msm-modem-uim-selection"); + std::string line; + while (std::getline(conf, line)) { + if (line.rfind("preferred_sim_slot=", 0) == 0) { + int v = std::atoi(line.c_str() + 19); + if (v == 1 || v == 2) info.preferredSlot = v; + } + } + } + + constexpr int kAfQipcrtr = 42; + constexpr uint32_t kQrtrPortCtrl = 0xfffffffeu; + constexpr uint32_t kQrtrTypeNewServer = 4; + constexpr uint32_t kQrtrTypeNewLookup = 10; + constexpr uint32_t kQmiServiceDms = 2; + constexpr uint32_t kQmiServiceNas = 3; + constexpr uint32_t kQmiServiceUim = 11; + + struct SockAddrQrtr { + unsigned short sq_family; + uint32_t sq_node; + uint32_t sq_port; + }; + struct QrtrCtrlPkt { + uint32_t cmd; + uint32_t service; + uint32_t instance; + uint32_t node; + uint32_t port; + } __attribute__((packed)); + + auto lookupService = [&](uint32_t sid, uint32_t& outNode, uint32_t& outPort) -> bool { + int fd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (fd < 0) return false; + SockAddrQrtr localSq {}; + socklen_t sl = sizeof(localSq); + if (::getsockname(fd, reinterpret_cast(&localSq), &sl) < 0) { + ::close(fd); + return false; + } + SockAddrQrtr ctrlSq { kAfQipcrtr, localSq.sq_node, kQrtrPortCtrl }; + QrtrCtrlPkt lookup { kQrtrTypeNewLookup, sid, 0, 0, 0 }; + if (::sendto(fd, &lookup, sizeof(lookup), 0, + reinterpret_cast(&ctrlSq), + sizeof(ctrlSq)) < 0) { + ::close(fd); + return false; + } + bool found = false; + for (int i = 0; i < 12; ++i) { + struct pollfd pfd { fd, POLLIN, 0 }; + if (::poll(&pfd, 1, 40) <= 0) break; + QrtrCtrlPkt pkt {}; + ssize_t n = ::recv(fd, &pkt, sizeof(pkt), 0); + if (n >= static_cast(sizeof(pkt)) && pkt.cmd == kQrtrTypeNewServer) { + if (pkt.service == sid && pkt.port != 0) { + outNode = pkt.node; + outPort = pkt.port; + found = true; + } + if (pkt.service == 0 && pkt.node == 0 && pkt.port == 0) break; + } + } + ::close(fd); + return found; + }; + + uint32_t uimNode = 0, uimPort = 0; + if (lookupService(kQmiServiceUim, uimNode, uimPort)) { + int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (sfd >= 0) { + SockAddrQrtr uimSq { kAfQipcrtr, uimNode, uimPort }; + uint8_t req[7] = { 0x00, 0x01, 0x00, 0x2F, 0x00, 0x00, 0x00 }; + if (::sendto(sfd, req, sizeof(req), 0, + reinterpret_cast(&uimSq), + sizeof(uimSq)) >= 0) { + struct pollfd pfd { sfd, POLLIN, 0 }; + if (::poll(&pfd, 1, 60) > 0) { + uint8_t buf[1024]; + ssize_t rlen = ::recv(sfd, buf, sizeof(buf), 0); + if (rlen >= 7 && buf[0] == 0x02 && buf[3] == 0x2F) { + size_t pos = 7; + while (pos + 3 <= static_cast(rlen)) { + uint8_t tt = buf[pos]; + uint16_t tl = static_cast(buf[pos + 1]) | + (static_cast(buf[pos + 2]) << 8); + pos += 3; + if (pos + tl > static_cast(rlen)) break; + if (tt == 0x10 && tl >= 9) { + const uint8_t* p = buf + pos; + uint16_t gwPri = static_cast(p[0]) | (static_cast(p[1]) << 8); + uint16_t gwSec = static_cast(p[4]) | (static_cast(p[5]) << 8); + if (gwPri != 0xFFFF) info.primaryGwSlot = ((gwPri >> 8) & 0xFF) + 1; + if (gwSec != 0xFFFF) info.secondaryGwSlot = ((gwSec >> 8) & 0xFF) + 1; + uint8_t numSlots = p[8]; + size_t off = 9; + for (uint8_t s = 0; s < numSlots && s < 2; ++s) { + if (off + 6 > tl) break; + uint8_t cstate = p[off]; + if (s == 0) info.slot1Present = (cstate == 1); + if (s == 1) info.slot2Present = (cstate == 1); + uint8_t numApps = p[off + 5]; + off += 6; + for (uint8_t a = 0; a < numApps; ++a) { + if (off + 7 > tl) break; + uint8_t aidLen = p[off + 6]; + if (off + 14 + aidLen > tl) break; + off += 14 + aidLen; + } + } + } + pos += tl; + } + } + } + } + ::close(sfd); + } + } + + info.dualSimActive = info.slot1Present && info.slot2Present && + (info.primaryGwSlot == 1 || info.primaryGwSlot == 2) && + (info.secondaryGwSlot == 1 || info.secondaryGwSlot == 2); + + uint32_t nasNode = 0, nasPort = 0; + uint32_t dmsNode = 0, dmsPort = 0; + bool hasNas = lookupService(kQmiServiceNas, nasNode, nasPort); + bool hasDms = lookupService(kQmiServiceDms, dmsNode, dmsPort); + + auto querySubMeta = [&](int slot, int sub, std::string& outOp, + std::string& outRat, std::string& outNum) { + if (sub < 0) return; + if (hasNas) { + int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (sfd >= 0) { + SockAddrQrtr nasSq { kAfQipcrtr, nasNode, nasPort }; + uint8_t bindReq[11] = { + 0x00, 0x01, 0x00, 0x45, 0x00, 0x04, 0x00, + 0x01, 0x01, 0x00, static_cast(sub) + }; + ::sendto(sfd, bindReq, sizeof(bindReq), 0, + reinterpret_cast(&nasSq), sizeof(nasSq)); + struct pollfd pfd { sfd, POLLIN, 0 }; + if (::poll(&pfd, 1, 40) > 0) { + uint8_t tmp[256]; + ::recv(sfd, tmp, sizeof(tmp), 0); + } + uint8_t ssReq[7] = { 0x00, 0x02, 0x00, 0x24, 0x00, 0x00, 0x00 }; + ::sendto(sfd, ssReq, sizeof(ssReq), 0, + reinterpret_cast(&nasSq), sizeof(nasSq)); + if (::poll(&pfd, 1, 50) > 0) { + uint8_t buf[1024]; + ssize_t rlen = ::recv(sfd, buf, sizeof(buf), 0); + if (rlen >= 7 && buf[0] == 0x02 && buf[3] == 0x24) { + size_t pos = 7; + while (pos + 3 <= static_cast(rlen)) { + uint8_t tt = buf[pos]; + uint16_t tl = static_cast(buf[pos + 1]) | + (static_cast(buf[pos + 2]) << 8); + pos += 3; + if (pos + tl > static_cast(rlen)) break; + if (tt == 0x01 && tl >= 5 && buf[pos + 3] >= 1) { + uint8_t rb = buf[pos + 4]; + if (rb == 8) outRat = "4G"; + else if (rb == 5) outRat = "3G"; + else if (rb == 4) outRat = "2G"; + } else if (tt == 0x12 && tl >= 5) { + uint8_t dlen = buf[pos + 4]; + if (5 + dlen <= tl && dlen > 0) { + outOp.assign(reinterpret_cast(buf + pos + 5), dlen); + outOp = trimStr(outOp); + } + } + pos += tl; + } + } + } + ::close(sfd); + } + } + if (hasDms) { + int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); + if (sfd >= 0) { + SockAddrQrtr dmsSq { kAfQipcrtr, dmsNode, dmsPort }; + uint8_t bindReq[11] = { + 0x00, 0x01, 0x00, 0x54, 0x00, 0x04, 0x00, + 0x01, 0x01, 0x00, static_cast(sub) + }; + ::sendto(sfd, bindReq, sizeof(bindReq), 0, + reinterpret_cast(&dmsSq), sizeof(dmsSq)); + struct pollfd pfd { sfd, POLLIN, 0 }; + if (::poll(&pfd, 1, 40) > 0) { + uint8_t tmp[256]; + ::recv(sfd, tmp, sizeof(tmp), 0); + } + uint8_t msReq[7] = { 0x00, 0x02, 0x00, 0x24, 0x00, 0x00, 0x00 }; + ::sendto(sfd, msReq, sizeof(msReq), 0, + reinterpret_cast(&dmsSq), sizeof(dmsSq)); + if (::poll(&pfd, 1, 50) > 0) { + uint8_t buf[512]; + ssize_t rlen = ::recv(sfd, buf, sizeof(buf), 0); + if (rlen >= 7 && buf[0] == 0x02 && buf[3] == 0x24) { + size_t pos = 7; + while (pos + 3 <= static_cast(rlen)) { + uint8_t tt = buf[pos]; + uint16_t tl = static_cast(buf[pos + 1]) | + (static_cast(buf[pos + 2]) << 8); + pos += 3; + if (pos + tl > static_cast(rlen)) break; + if (tt == 0x01 && tl > 0) { + std::string raw(reinterpret_cast(buf + pos), tl); + raw = trimStr(raw); + if (!raw.empty()) { + outNum = (raw.front() == '+') ? raw : ("+" + raw); + } + } + pos += tl; + } + } + } + ::close(sfd); + } + } + (void)slot; + }; + + int sub1 = (info.primaryGwSlot == 1) ? 0 : ((info.secondaryGwSlot == 1) ? 1 : -1); + int sub2 = (info.primaryGwSlot == 2) ? 0 : ((info.secondaryGwSlot == 2) ? 1 : -1); + querySubMeta(1, sub1, info.slot1Operator, info.slot1Rat, info.slot1Number); + querySubMeta(2, sub2, info.slot2Operator, info.slot2Rat, info.slot2Number); + + auto formatSlotStrings = [](int s, const std::string& op, const std::string& rat, + const std::string& num, std::string& outLabel, + std::string& outShort) { + std::string base = "SIM " + std::to_string(s); + outShort = op.empty() ? base : (base + " (" + op + ")"); + outLabel = base; + if (!op.empty()) { + outLabel += ": " + op; + } + if (!rat.empty()) { + outLabel += " [" + rat + "]"; + } + if (!num.empty()) { + outLabel += " " + num; + } + }; + + formatSlotStrings(1, info.slot1Operator, info.slot1Rat, info.slot1Number, + info.slot1Label, info.slot1Short); + formatSlotStrings(2, info.slot2Operator, info.slot2Rat, info.slot2Number, + info.slot2Label, info.slot2Short); + + cached = info; + lastQueryMs = now; + return info; +} + +inline void placePhoneCall(const std::string& rawNumber, int simSlot = 0) { std::string num = normalizePhone(rawNumber); if (num.empty()) { return; } - if (!sendPluginCommand("callscreen", "OUTGOING - " + num)) { + if (simSlot == 0) { + DualSimInfo dsi = queryDualSimInfo(); + if (dsi.dualSimActive) { + if (!sendPluginCommand("callscreen", "PROMPT_SIM " + num)) { + runAsyncArgv("sxmo_modemdial.sh", num.c_str()); + } + return; + } + simSlot = (dsi.primaryGwSlot == 2) ? 2 : 1; + } + std::string simTag = "SIM" + std::to_string(simSlot); + if (!sendPluginCommand("callscreen", "OUTGOING - " + num + " " + simTag)) { runAsyncArgv("xcallscreen", "outgoing", "-", num.c_str()); } - runAsyncArgv("sxmo_modemdial.sh", num.c_str()); + std::string simStr = std::to_string(simSlot); + runAsyncArgv("sxmo_modemdial.sh", "--sim", simStr.c_str(), num.c_str()); } inline void closeOtherPlugins(const char* selfPluginName) { @@ -1940,11 +2239,11 @@ inline bool queryQrtrDmsImeis(DeviceImeis& out) { dmsSq.sq_node = dmsNode; dmsSq.sq_port = dmsPort; - // 1. QMI_DMS_BIND_SUBSCRIPTION (0x0057), TLV 0x01 = uint32_t(subType) + // 1. QMI_DMS_BIND_SUBSCRIPTION (0x0054), TLV 0x01 = uint32_t(subType) if (subType > 0) { uint8_t bindReq[14] = { 0x00, 0x01, 0x00, // flags=0 (req), txn_id=1 - 0x57, 0x00, // msg_id = 0x0057 + 0x54, 0x00, // msg_id = 0x0054 0x07, 0x00, // tlv_len = 7 0x01, 0x04, 0x00, // TLV 0x01, len 4 static_cast(subType & 0xFF), 0x00, 0x00, 0x00 @@ -2049,16 +2348,20 @@ inline bool isUssdCode(const std::string& code) { inline std::string sendModemUssd(const std::string& input, bool isReply = false, - bool* outSessionActive = nullptr) { + bool* outSessionActive = nullptr, + int simSlot = 0) { if (outSessionActive) *outSessionActive = false; std::string clean = trimStr(input); if (clean.empty()) return "Empty USSD request."; int rc = 0; std::string mode = (isReply && !isUssdCode(clean)) ? "respond" : "initiate"; + std::string simArg = (simSlot == 1 || simSlot == 2) + ? ("--sim " + std::to_string(simSlot) + " ") + : ""; std::string cmd = "doas -n /usr/libexec/msm-modem-uim-selection ussd " + mode + " " + - shellQuote(clean) + " 2>&1"; + simArg + shellQuote(clean) + " 2>&1"; std::string out = trimStr(runCaptureCmd(cmd, &rc)); if (out.empty()) { diff --git a/src/dwm-plugins/sms_plugin.cpp b/src/dwm-plugins/sms_plugin.cpp index be4fb0c..af039d4 100644 --- a/src/dwm-plugins/sms_plugin.cpp +++ b/src/dwm-plugins/sms_plugin.cpp @@ -30,6 +30,7 @@ enum class ViewMode { ConfirmDelete = 5, Blocklist = 6, AddBlock = 7, + SelectSim = 8, }; enum class TextCaseMode { @@ -169,6 +170,8 @@ int runSmsApp(int argc, char** argv) { int selectedPicker = 0; int confirmSelected = 0; int blockSelected = 0; + int simPickIdx = 0; + DualSimInfo simInfo; std::string addBlockInput; std::string activeNumber; @@ -341,13 +344,26 @@ int runSmsApp(int argc, char** argv) { }; auto startAsyncSendSms = [&](const std::string& rawRecipient, - const std::string& body) { + const std::string& body, + int chosenSim = 0) { std::string recipient = normalizePhone(rawRecipient); if (recipient.empty() || trimStr(body).empty()) { statusBanner = "Set recipient and message"; statusBannerUntilMs = nowMs() + 2000; return; } + if (chosenSim == 0) { + simInfo = queryDualSimInfo(false); + if (simInfo.dualSimActive) { + simPickIdx = (simInfo.preferredSlot == 2) ? 1 : 0; + mode = ViewMode::SelectSim; + return; + } + chosenSim = simInfo.preferredSlot; + } + if (chosenSim != 1 && chosenSim != 2) { + chosenSim = 1; + } { std::lock_guard lk(sendMutex); if (sendingInProgress) { @@ -356,12 +372,13 @@ int runSmsApp(int argc, char** argv) { sendingInProgress = true; } saveSmsDraft(recipient, body); - statusBanner = "Sending SMS to " + recipient + "..."; + statusBanner = "Sending SMS (SIM " + std::to_string(chosenSim) + ") to " + + recipient + "..."; statusBannerUntilMs = nowMs() + 15000; int writePipe = notifyPipe[1]; - std::thread([recipient, body, writePipe, &sendMutex, &sendingInProgress, - &statusBanner, &statusBannerUntilMs]() { + std::thread([recipient, body, chosenSim, writePipe, &sendMutex, + &sendingInProgress, &statusBanner, &statusBannerUntilMs]() { std::string draftPath = getModemLogDirPath() + "/" + recipient + "/draft.txt"; ContactBook::ensureParentDir(draftPath); @@ -370,6 +387,7 @@ int runSmsApp(int argc, char** argv) { out << body << "\n"; } + std::string simStr = std::to_string(chosenSim); int rc = -1; pid_t pid = ::fork(); if (pid == 0) { @@ -381,11 +399,11 @@ int runSmsApp(int argc, char** argv) { if (nullfd > 2) ::close(nullfd); } execlp("sxmo_modemsendsms.sh", "sxmo_modemsendsms.sh", - recipient.c_str(), "-f", draftPath.c_str(), - static_cast(nullptr)); + "--sim", simStr.c_str(), recipient.c_str(), "-f", + draftPath.c_str(), static_cast(nullptr)); execl("/usr/bin/sxmo_modemsendsms.sh", "sxmo_modemsendsms.sh", - recipient.c_str(), "-f", draftPath.c_str(), - static_cast(nullptr)); + "--sim", simStr.c_str(), recipient.c_str(), "-f", + draftPath.c_str(), static_cast(nullptr)); _exit(127); } else if (pid > 0) { int status = 0; @@ -411,12 +429,13 @@ int runSmsApp(int argc, char** argv) { ContactBook::ensureParentDir(smsPath); std::ofstream smsOut(smsPath, std::ios::app); if (smsOut.is_open()) { - smsOut << "Sent at " << tbuf << ":\n" << body << "\n\n"; + smsOut << "Sent at " << tbuf << " [SIM " << chosenSim << "]:\n" + << body << "\n\n"; } std::ofstream logOut(getModemLogFilePath(), std::ios::app); if (logOut.is_open()) { - logOut << tbuf << "\tsent_txt\t" << recipient << "\t" - << body.size() << " chars\n"; + logOut << tbuf << "\tsent_txt\t" << recipient << "\t[SIM " + << chosenSim << "] " << body.size() << " chars\n"; } removeSmsDraft(recipient); } @@ -424,7 +443,9 @@ int runSmsApp(int argc, char** argv) { { std::lock_guard lk(sendMutex); sendingInProgress = false; - statusBanner = (rc == 0) ? "SMS Sent!" : "Saved to Sent (modem offline)"; + statusBanner = (rc == 0) + ? ("SMS Sent (SIM " + std::to_string(chosenSim) + ")!") + : "Saved to Sent (modem offline)"; statusBannerUntilMs = nowMs() + 2200; } if (writePipe >= 0) { @@ -944,6 +965,48 @@ int runSmsApp(int argc, char** argv) { i == 0 ? "No, Keep Thread" : "Yes, Delete Thread", 184); } drawSoftkeyBar("Select", "Confirm", "Cancel"); + + } else if (mode == ViewMode::SelectSim) { + XSetForeground(dpy, gc, pt.spec.bgHeader); + XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, 36); + drawPango(layoutIcon, &colYellow, 8, 0, 36, kIconSim); + drawPango(layoutMain, &colWhite, 30, 0, 36, "Select SIM for SMS", 200); + + std::string cname = book.resolveName(composeRecipient); + std::string toLine = + "To: " + (cname.empty() ? composeRecipient : cname); + drawPango(layoutSmall, &colLight, 12, 44, 22, toLine, 216); + + for (int i = 0; i < 2; ++i) { + int ry = 74 + i * 74; + bool isSel = (simPickIdx == i); + XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgAltEven); + XFillRectangle(dpy, pix, gc, 10, ry, kWinWidth - 20, 64); + XSetForeground(dpy, gc, isSel ? pt.spec.accent : pt.spec.border); + XDrawRectangle(dpy, pix, gc, 10, ry, kWinWidth - 21, 63); + + std::string op = (i == 0) ? simInfo.slot1Operator : simInfo.slot2Operator; + std::string rat = (i == 0) ? simInfo.slot1Rat : simInfo.slot2Rat; + std::string num = (i == 0) ? simInfo.slot1Number : simInfo.slot2Number; + if (op.empty()) op = "SIM " + std::to_string(i + 1); + std::string title = "[" + std::to_string(i + 1) + "] SIM " + + std::to_string(i + 1) + " - " + op; + if (!rat.empty()) title += " [" + rat + "]"; + std::string sub = num.empty() ? "Ready" : num; + if (simInfo.preferredSlot == (i + 1)) { + sub += " (Default)"; + } + + drawPango(layoutIcon, isSel ? &colYellow : &colGreen, 18, ry + 8, 22, + kIconSim); + drawPango(layoutMain, &colWhite, 40, ry + 8, 22, title, kWinWidth - 54); + drawPango(layoutSmall, isSel ? &colLight : &colMuted, 40, ry + 34, 18, + sub, kWinWidth - 54); + } + + drawPango(layoutSmall, &colMuted, 12, 230, 20, + "Press 1 or 2, or Up/Down + Send", 216); + drawSoftkeyBar("Send", "Select", "Back"); } int64_t tNow = nowMs(); @@ -1257,6 +1320,14 @@ int runSmsApp(int argc, char** argv) { } else { mode = prevMode; } + } else if (mode == ViewMode::SelectSim) { + if (isLeft) { + mode = ViewMode::Compose; + startAsyncSendSms(composeRecipient, composeText, + (simPickIdx == 1) ? 2 : 1); + } else { + mode = ViewMode::Compose; + } } drawUI(); }; @@ -1348,7 +1419,12 @@ int runSmsApp(int argc, char** argv) { (kc == 177 || sym == XF86XK_PickupPhone || sym == XF86XK_Phone || sym == _EVDEVK(0x1bd) || sym == _EVDEVK(0x0a9)); if (isCallKey) { - if (mode == ViewMode::Compose) { + if (mode == ViewMode::SelectSim) { + mode = ViewMode::Compose; + startAsyncSendSms(composeRecipient, composeText, + (simPickIdx == 1) ? 2 : 1); + drawUI(); + } else if (mode == ViewMode::Compose) { startAsyncSendSms(composeRecipient, composeText); drawUI(); } else if (mode == ViewMode::ThreadView && !activeNumber.empty()) { @@ -1590,6 +1666,21 @@ int runSmsApp(int argc, char** argv) { } else if (sym == XK_Return || sym == XK_KP_Enter) { handleSoftkeyAction(true); } + } else if (mode == ViewMode::SelectSim) { + char d = mapDialKey(sym, kc, ev.xkey.state); + if (d == '1') { + simPickIdx = 0; + handleSoftkeyAction(true); + } else if (d == '2') { + simPickIdx = 1; + handleSoftkeyAction(true); + } else if (sym == XK_Up || sym == XK_Down || sym == XK_KP_Up || + sym == XK_KP_Down) { + simPickIdx = 1 - simPickIdx; + drawUI(); + } else if (sym == XK_Return || sym == XK_KP_Enter) { + handleSoftkeyAction(true); + } } } }