taler-android

Android apps for GNU Taler (wallet, PoS, cashier)
Log | Files | Refs | README | LICENSE

emu.sh (9834B)


      1 #!/bin/bash
      2 # This file is part of GNU Taler
      3 # (C) 2026 Taler Systems S.A.
      4 #
      5 # GNU Taler is free software; you can redistribute it and/or modify it under the
      6 # terms of the GNU General Public License as published by the Free Software
      7 # Foundation; either version 3, or (at your option) any later version.
      8 #
      9 # GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
     10 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
     11 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
     12 #
     13 # You should have received a copy of the GNU General Public License along with
     14 # GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
     15 #
     16 # Emulator lifecycle for the POS simulator.  One AVD per worker; the worker
     17 # index picks both the AVD name and the (even) console port, so several workers
     18 # can run side by side.
     19 #
     20 # Unlike the wallet's equivalent this does not map any ports by default: the
     21 # terminal talks to a merchant backend on the public internet, which the
     22 # emulator reaches through its own NAT.  "reverse" exists for the mock
     23 # backend, which runs on the host.
     24 #
     25 # Usage:
     26 #   emu.sh create  <worker>            create/replace the AVD
     27 #   emu.sh boot    <worker> [poster]   boot headless, optionally with a QR
     28 #                                      code hanging in the virtual scene
     29 #   emu.sh prepare <worker> [apk]      install the terminal, grant permissions,
     30 #                                      kill animations
     31 #   emu.sh reverse <worker> [port...]  map host ports into the emulator
     32 #   emu.sh serial  <worker>            print the adb serial
     33 #   emu.sh kill    <worker>            shut the emulator down
     34 #
     35 # A phone-sized worker, for the other half of every screen that has two:
     36 #
     37 #   POS_LCD_WIDTH=1920 POS_LCD_HEIGHT=1080 POS_LCD_DENSITY=420 \
     38 #     emu.sh create 3 && ... boot 3 && ... prepare 3
     39 
     40 set -eu
     41 
     42 SIM_ROOT=${POS_SIM_ROOT:-/opt/taler-pos-sim}
     43 export ANDROID_SDK_ROOT=${ANDROID_SDK_ROOT:-/opt/android-sdk}
     44 export ANDROID_HOME=$ANDROID_SDK_ROOT
     45 export ANDROID_AVD_HOME=${ANDROID_AVD_HOME:-$SIM_ROOT/avd}
     46 ADB=$ANDROID_SDK_ROOT/platform-tools/adb
     47 EMULATOR=$ANDROID_SDK_ROOT/emulator/emulator
     48 AVDMANAGER=$ANDROID_SDK_ROOT/cmdline-tools/latest/bin/avdmanager
     49 IMAGE=${POS_SYSTEM_IMAGE:-"system-images;android-36;google_apis;x86_64"}
     50 PKG=${POS_PKG:-net.taler.merchantpos}
     51 BOOT_TIMEOUT=${POS_BOOT_TIMEOUT:-300}
     52 # A PNG to hang on the wall of the emulator's virtual scene, so the camera has
     53 # something real to decode.  Only settable at launch, hence one boot per image.
     54 POSTER=${POS_POSTER:-}
     55 
     56 die() { echo "emu.sh: $*" >&2; exit 1; }
     57 
     58 worker=${2:-0}
     59 avd_name() { echo "taler-pos-$worker"; }
     60 api_level() { echo "$IMAGE" | sed -n 's/.*android-\([0-9][0-9]*\).*/\1/p'; }
     61 # The virtual scene camera, which is what lets a QR code be shown to the
     62 # device, needs an image that can deliver NV21 frames: below API 26 the camera
     63 # service rejects the format and retries until the boot times out.
     64 camera_back() { [ "$(api_level)" -ge 26 ] 2>/dev/null && echo virtualscene || echo emulated; }
     65 old_image() { [ "$(api_level)" -lt 29 ] 2>/dev/null; }
     66 ram_size()       { old_image && echo 2048  || echo 4096; }
     67 heap_size()      { old_image && echo 256   || echo 512; }
     68 data_partition() { old_image && echo 2048M || echo 6144M; }
     69 # Not 5554: the wallet simulator numbers its workers from there, and a second
     70 # harness starting on an occupied port does not boot anything -- it silently
     71 # attaches to the other one's emulators and drives the wrong app.
     72 POS_PORT_BASE=${POS_PORT_BASE:-5584}
     73 # 2560x1600 at 320dpi is 1280x800dp, so smallestScreenWidthDp is 800 and every
     74 # screen takes its tablet branch.  1920x1080 at 420dpi is 731x411dp, which is
     75 # a phone on both counts -- and small enough on the short edge for the amount
     76 # keypad's `isCompactPhone` arm as well.
     77 LCD_WIDTH=${POS_LCD_WIDTH:-2560}
     78 LCD_HEIGHT=${POS_LCD_HEIGHT:-1600}
     79 LCD_DENSITY=${POS_LCD_DENSITY:-320}
     80 console_port() { echo $((POS_PORT_BASE + 2 * worker)); }
     81 serial() { echo "emulator-$(console_port)"; }
     82 
     83 create() {
     84     mkdir -p "$ANDROID_AVD_HOME"
     85     # A tablet profile, not a phone: five of the terminal's screens pick their
     86     # layout on `smallestScreenWidthDp >= 720` -- the order grid, the payment
     87     # screen, the refund URI screen, the QR config tab and the amount keypad --
     88     # so a phone-sized AVD runs a different half of the app.  Both are worth
     89     # running; the default is the tablet, because that is what a counter has on
     90     # it.  The device profile does not decide this on its own: the LCD is set
     91     # below and overrides whatever the profile says, so POS_LCD_* is what
     92     # actually moves the app from one layout to the other.
     93     local device=${POS_AVD_DEVICE:-medium_tablet}
     94     echo no | "$AVDMANAGER" create avd -n "$(avd_name)" -k "$IMAGE" \
     95              -d "$device" --force >/dev/null
     96     local cfg="$ANDROID_AVD_HOME/$(avd_name).avd/config.ini"
     97     python3 - "$cfg" "$(camera_back)" "$(ram_size)" "$(heap_size)" \
     98             "$(data_partition)" "$LCD_WIDTH" "$LCD_HEIGHT" "$LCD_DENSITY" <<'PY'
     99 import sys
    100 path = sys.argv[1]
    101 cfg = {}
    102 for line in open(path):
    103     if '=' in line:
    104         k, v = line.rstrip('\n').split('=', 1)
    105         cfg[k] = v
    106 # A temp data partition would throw away everything on shutdown; the rest is
    107 # headless tuning.  The LCD is landscape because the app is: an emulator whose
    108 # natural orientation is portrait still works, but every screenshot comes out
    109 # rotated and the virtual scene's poster ends up on its side.
    110 cfg.pop('disk.dataPartition.path', None)
    111 cfg.update({
    112     'hw.ramSize': sys.argv[3],
    113     'vm.heapSize': sys.argv[4],
    114     'disk.dataPartition.size': sys.argv[5],
    115     'hw.audioInput': 'no',
    116     'hw.audioOutput': 'no',
    117     'hw.camera.back': sys.argv[2],
    118     'hw.camera.front': 'emulated',
    119     'hw.keyboard': 'yes',
    120     'hw.gpu.enabled': 'yes',
    121     'hw.gpu.mode': 'swiftshader_indirect',
    122     'hw.lcd.width': sys.argv[6],
    123     'hw.lcd.height': sys.argv[7],
    124     'hw.lcd.density': sys.argv[8],
    125     'hw.initialOrientation': 'landscape',
    126     'showDeviceFrame': 'no',
    127 })
    128 with open(path, 'w') as f:
    129     f.writelines(f'{k}={v}\n' for k, v in sorted(cfg.items()))
    130 PY
    131     echo "created $(avd_name)"
    132 }
    133 
    134 kill_emu() {
    135     local s waited=0 port pid
    136     s=$(serial)
    137     port=$(console_port)
    138     "$ADB" -s "$s" emu kill >/dev/null 2>&1 || true
    139     # Waiting matters: `emu kill` returns as soon as the console accepts it,
    140     # and a process still holding the AVD's lock files stops the next boot.
    141     while [ "$waited" -lt 90 ]; do
    142         "$ADB" devices 2>/dev/null | grep -q "^$s" || break
    143         sleep 2
    144         waited=$((waited + 2))
    145     done
    146     for _ in $(seq 1 30); do
    147         pid=$(pgrep -f -- "-port $port" | head -1)
    148         [ -n "$pid" ] || break
    149         kill "$pid" 2>/dev/null || true
    150         sleep 2
    151     done
    152     rm -f "$ANDROID_AVD_HOME/$(avd_name).avd"/*.lock 2>/dev/null || true
    153     echo "killed $s after ${waited}s"
    154 }
    155 
    156 boot() {
    157     local log="$SIM_ROOT/run/emu-$worker.log"
    158     mkdir -p "$SIM_ROOT/run"
    159     "$ADB" start-server >/dev/null 2>&1 || true
    160     local camera poster_args=()
    161     camera=$(camera_back)
    162     local poster=${3:-$POSTER}
    163     if [ -n "$poster" ] && [ "$camera" = virtualscene ]; then
    164         [ -r "$poster" ] || die "no poster image at $poster"
    165         poster_args=(-virtualscene-poster "wall=$poster")
    166     fi
    167     local wipe_args=()
    168     [ "${POS_KEEP_DATA:-0}" = "1" ] || wipe_args=(-wipe-data)
    169     setsid "$EMULATOR" -avd "$(avd_name)" -port "$(console_port)" \
    170         -no-window -no-audio -no-boot-anim -gpu swiftshader_indirect \
    171         -no-snapshot-load -no-snapshot-save "${wipe_args[@]}" \
    172         -camera-back "$camera" "${poster_args[@]}" \
    173         > "$log" 2>&1 < /dev/null &
    174     echo "booting $(avd_name) on $(serial), log $log" >&2
    175     local waited=0
    176     while [ "$waited" -lt "$BOOT_TIMEOUT" ]; do
    177         if [ "$("$ADB" -s "$(serial)" shell getprop sys.boot_completed 2>/dev/null | tr -d '\r\n')" = "1" ]; then
    178             echo "booted after ${waited}s"
    179             return 0
    180         fi
    181         sleep 2
    182         waited=$((waited + 2))
    183     done
    184     tail -20 "$log" >&2 || true
    185     die "emulator did not finish booting within ${BOOT_TIMEOUT}s"
    186 }
    187 
    188 reverse() {
    189     local s p
    190     s=$(serial)
    191     shift 2 2>/dev/null || true
    192     local ports=("$@")
    193     [ ${#ports[@]} -gt 0 ] || ports=(${POS_MOCK_PORT:-19443})
    194     for p in "${ports[@]}"; do
    195         "$ADB" -s "$s" reverse "tcp:$p" "tcp:$p" >/dev/null
    196     done
    197     echo "mapped ${ports[*]} into $s"
    198 }
    199 
    200 prepare() {
    201     local s apk
    202     s=$(serial)
    203     apk=${3:-$SIM_ROOT/apk/pos.apk}
    204     [ -r "$apk" ] || die "no APK at $apk"
    205     # Deterministic, animation-free UI: the driver reads the view hierarchy and
    206     # animations make it race.
    207     "$ADB" -s "$s" shell settings put global window_animation_scale 0
    208     "$ADB" -s "$s" shell settings put global transition_animation_scale 0
    209     "$ADB" -s "$s" shell settings put global animator_duration_scale 0
    210     "$ADB" -s "$s" shell settings put secure long_press_timeout 250
    211     "$ADB" -s "$s" shell svc power stayon true
    212     # The terminal is landscape-locked, so the system will rotate the window
    213     # whatever this says; pinning it stops the *launcher* from rotating under
    214     # the app, which is what makes a screenshot come out sideways.
    215     "$ADB" -s "$s" shell settings put system accelerometer_rotation 0
    216     "$ADB" -s "$s" shell install -r -g "$apk" 2>/dev/null \
    217         || "$ADB" -s "$s" install -r -g "$apk"
    218     "$ADB" -s "$s" shell pm grant "$PKG" android.permission.CAMERA 2>/dev/null || true
    219     echo "prepared $s with $apk"
    220 }
    221 
    222 case "${1:-}" in
    223     create) create ;;
    224     boot) boot "$@" ;;
    225     prepare) prepare "$@" ;;
    226     reverse) reverse "$@" ;;
    227     serial) serial ;;
    228     kill) kill_emu ;;
    229     *) die "usage: emu.sh {create|boot|prepare|reverse|serial|kill} <worker> [arg]" ;;
    230 esac