#!/usr/bin/python3 -u
# Quectel EC20/EC25: carry phone call audio over USB audio (UAC).
#
# The module plays call audio on its PCM pins by default, which the
# TaishanPi 3M does not route anywhere. Two things are needed:
#
#   early <tty>  Run by udev on the main AT port before ModemManager uses
#                it. Enables the module's USB audio function (stored in the
#                module, done once; the module then restarts), and waits
#                until the SIM state is known.
#   late <tty>   Run as a service on a second AT port that ModemManager is
#                told to ignore. Waits until the module is registered, then
#                selects USB as the voice path with AT+QPCMV=1,2.
#
# AT+QPCMV=1,2 is lost on every module restart, and it must NOT be sent
# before the module has registered: sent early (seconds after boot) it
# answers OK and reads back 1,2, but every call in that boot is digital
# silence, and sending it again later does not help.
import os, re, select, sys, syslog, termios, time

def at(fd, cmd, wait=3.0):
    try:
        while select.select([fd], [], [], 0)[0]:
            os.read(fd, 4096)
    except BlockingIOError:
        pass
    os.write(fd, (cmd + '\r').encode())
    out, end = b'', time.time() + wait
    while time.time() < end:
        if select.select([fd], [], [], 0.2)[0]:
            try:
                out += os.read(fd, 4096)
            except BlockingIOError:
                continue
            if b'\r\nOK\r\n' in out or b'ERROR' in out:
                break
    return out.decode(errors='replace')

def open_port(dev):
    fd = os.open(dev, os.O_RDWR | os.O_NOCTTY | os.O_NONBLOCK)
    a = termios.tcgetattr(fd)
    a[0] = a[1] = a[3] = 0
    a[2] = termios.CS8 | termios.CREAD | termios.CLOCAL
    termios.tcsetattr(fd, termios.TCSANOW, a)
    # The AT port enumerates seconds before the firmware answers on it.
    for _ in range(40):
        if 'OK' in at(fd, 'AT', 0.5):
            at(fd, 'ATE0')
            return fd
        time.sleep(0.5)
    syslog.syslog('module did not answer AT on %s, giving up' % dev)
    sys.exit(0)

def early(fd):
    # Right after boot the firmware can take several seconds per command
    # and interleaves unsolicited messages (RDY, +CPIN...); retry.
    r = ''
    for _ in range(5):
        r = at(fd, 'AT+QCFG="USBCFG"', 5.0)
        if '"usbcfg"' in r:
            break
        time.sleep(1)
    # +QCFG: "usbcfg",0x2C7C,0x0125,diag,nmea,at,modem,rmnet,adb,uac
    if '"usbcfg"' in r:
        f = r.split('"usbcfg",', 1)[1].split()[0].split(',')
        if len(f) == 9 and f[8] == '0':
            f[8] = '1'
            syslog.syslog('enabling USB audio (UAC) and restarting the module')
            at(fd, 'AT+QCFG="USBCFG",' + ','.join(f))
            at(fd, 'AT+CFUN=1,1')
            return
    else:
        syslog.syslog('could not read USBCFG: %r' % r)

    # Hand the port to ModemManager only once the SIM state is known. After
    # a cold start the SIM sometimes stays "not inserted" (CME ERROR 10/13)
    # until the radio is cycled; ModemManager then reports sim-missing and
    # never looks again.
    for attempt in range(2):
        for _ in range(20):
            r = at(fd, 'AT+CPIN?', 2.0)
            if '+CPIN:' in r:
                syslog.syslog('SIM: ' + r.split('+CPIN:', 1)[1].splitlines()[0].strip())
                return
            time.sleep(0.5)
        if attempt == 0:
            syslog.syslog('SIM not ready (%s), cycling the radio' % r.strip())
            at(fd, 'AT+CFUN=0', 5.0)
            time.sleep(2)
            at(fd, 'AT+CFUN=1', 5.0)
    syslog.syslog('SIM still not ready: %s' % r.strip())

def registered(r):
    # +CREG: <n>,<stat>[,<lac>,<ci>[,<act>]]; stat 1 is home, 5 is roaming.
    # With <n> set to 2 the location fields follow, so look at the second
    # field and not at the end of the line.
    return any(m.group(1) in ('1', '5')
               for m in re.finditer(r'\+CE?REG:\s*\d+\s*,\s*(\d+)', r))

def late(fd):
    # Wait for registration; this can take as long as the user needs to
    # enter the SIM PIN. The loop ends when the module goes away.
    while True:
        if registered(at(fd, 'AT+CEREG?') + at(fd, 'AT+CREG?')):
            break
        time.sleep(3)
    # IMS (VoLTE) registration follows the LTE attach; give it time.
    for _ in range(15):
        if '"ims",1,1' in at(fd, 'AT+QCFG="ims"'):
            break
        time.sleep(2)
    time.sleep(10)
    # Nothing runs this again until the module re-enumerates, so do not give
    # up on one ERROR or one unanswered command.
    for _ in range(3):
        r = at(fd, 'AT+QPCMV=1,2')
        if 'OK' in r:
            break
        time.sleep(2)
    syslog.syslog('voice over USB audio: ' + ('ok' if 'OK' in r else 'failed: ' + r.strip()))

if __name__ == '__main__':
    syslog.openlog('lckfb-tspi-3m-modem-voice')
    try:
        mode, dev = sys.argv[1], sys.argv[2]
        fd = open_port(dev)
        early(fd) if mode == 'early' else late(fd)
    except OSError as e:
        syslog.syslog('%s: %s' % (sys.argv[1:], e))
