What’s in a ring?
I wanted to see if I could programmatically send/receive SMS and phone calls through my server without needing to pay for an external service. The only acceptable cost was paying for the cellular connection/plan. Obviously, if you were to deploy something in production, it would be a no-brainer to use an external service like Twilio.
So, all I had to begin with was a USB cellular modem, a SIM card, and a dream. A dream of materialising into a server rack the entire century-old apparatus of telephony: a dial tone, a ring, a human voice, and a keypad.
Actually, figuring out what modem to get in itself was a head scratcher. A lot of the USB modems online advertise GSM, but the carriers these days only support LTE and 5G. You could always buy a much more expensive PCIe expansion card stack, but I did not want to splurge on this.
Before we begin, we need to brush up on some basic glossary.
First, an MVNO (Mobile Virtual Network Operator) is a carrier that doesn’t own any spectrum or radio towers on its own. In my case I decided to go with Tello because their plans are super cheap. They issue a SIM card which accesses the Tello network, which is just wholesale access to T-Mobile’s network. T-Mobile agrees to recognise the SIM and bill back through Tello.
A cell tower talks to the modem, verifies that the SIM is allowed to camp there, allocates resources, and then upstreams everything to the carrier core. The core is where all the goofy stuff happens. To answer part of the question posed in the title of this post, a ring begins as the carrier core finding that tower, paging my modem (over radio), and the modem answering. This all happens before my server hears a single byte.
LTE is all IP and doesn’t have the old circuit-switched voice at all, so voice runs on top of it as VoLTE (Voice over LTE), which is basically a data session that happens to be a phone call. This is why a data modem can act as a phone in the first place, and it’s also why keypad presses don’t show up as tones in the audio, which comes back to bite us later.
Getting the modem online for data was pretty easy (and almost instant). Once the modem automatically registered on the network, it just showed up as an available network device. These modems all have great support on macOS, Linux, and Windows, as network devices.
One major issue to solve with voice is latency, since it is so sensitive to delay. I run slin16 (16 kHz signed linear PCM) over the USB audio interface, and there is still a noticeable gap between the call picking up and the first word coming back.
In the middle of all this is Asterisk, an open-source PBX (Private Branch Exchange). It handles the calls and runs the dialplan, which is the set of rules that decides what happens to each incoming call.
On my server, I’m running Asterisk 23.1.0 inside a FreePBX setup, and incoming cellular calls land in the [from-dongle] context. Since a public number is going to get robocalls (and I want you to be able to call it as long as I am paying for the SIM), the dialplan strips the caller ID down to digits and checks it against a whitelist. If you are on it you get routed to the voice bridge, and if not you get rickrolled and hung up on.
Here’s a trimmed version of [from-dongle]:
[from-dongle]
exten => s,1,NoOp(Inbound cellular call from ${CALLERID(num)})
same => n,Set(CID=${FILTER(0-9,${CALLERID(num)})})
same => n,GotoIf($["${CID}" = "15551234567"]?allowed:rickroll)
same => n(allowed),Answer()
same => n,Set(CALLUUID=${UUID()})
same => n,Set(IDRES=${CURL(http://gpt-live-bridge:9093/identify?uuid=${CALLUUID}&cid=${CID})})
same => n,AudioSocket(${CALLUUID},gpt-live-bridge:9092)
same => n,Hangup()
same => n(rickroll),Answer()
same => n,Playback(custom/rickroll)
same => n,Hangup()
exten => h,1,NoOp(Cleaning up modem PCM audio path)
same => n,System(/usr/sbin/asterisk -rx "quectel cmd quectel0 AT+CPCMREG=0")
The h (hangup) extension at the bottom runs AT+CPCMREG=0, which tears down the modem’s PCM audio after a call ends. If you skip it on (at least) the SIM7600, the next call can come up muted.
Asterisk can’t talk to a cellular modem by itself, so it needs a channel driver, which for this modem is chan_quectel. The modem is controlled with AT commands over a USB serial port and replies in plain text, so when someone calls it prints RING and the caller ID on /dev/ttyUSB2 while the audio goes over /dev/ttyUSB4. chan_quectel parses that text into calls and audio frames for Asterisk, and turns whatever Asterisk wants to do back into AT commands.
The config is pretty short:
[general]
interval=15
[quectel0]
context=from-dongle
audio=/dev/ttyUSB4
data=/dev/ttyUSB2
group=0
rxgain=0
txgain=0
autodeletesms=yes
resetquectel=yes
slin16=yes
; subscriber number redacted
; exten=+1XXXXXXXXXX
Once it’s registered on Tello with Voice and SMS both showing Yes, it mostly works, except for keypad presses. On VoLTE the modem sends those as their own line on the serial port, something like +RXDTMF: 5, and chan_quectel has no handler for it, so it logs Ignoring unknown result to messages.log and the digit is gone. I didn’t want to maintain a patched fork of the driver, so I worked around it in the bridge.
Texts take a different path. Incoming SMS comes in through the modem and chan_quectel into Asterisk, and to send one you can ask Asterisk directly:
asterisk -rx 'quectel sms quectel0 +15551234567 "Hello from my server"'
That only takes a number and a message, so there is no way to set the Data Coding Scheme (DCS) byte, which controls the encoding and the message class. For normal texts that is fine. If you want to change the message class you have to skip Asterisk and send raw PDUs to the modem on its spare serial port, /dev/ttyUSB3.
On a whitelisted call, the carrier pages the modem, the modem prints RING, chan_quectel hands the call to [from-dongle], and Asterisk checks the whitelist, picks up and generates a UUID for the call. The audio is then handed to AudioSocket, which streams raw audio over TCP. AudioSocket sends the call’s UUID when it connects but not the caller ID, so the dialplan calls /identify with both right before AudioSocket() so the bridge knows who the UUID belongs to.
The UUID in the first AudioSocket frame is 16 raw bytes (frame type 0x01, a two-byte length of 16, then the bytes).
import asyncio
import struct
import uuid
FRAME_HANGUP = 0x00
FRAME_UUID = 0x01
FRAME_AUDIO = 0x10
async def handle_audiosocket(reader: asyncio.StreamReader, writer: asyncio.StreamWriter):
header = await reader.readexactly(3)
kind, length = struct.unpack("!BH", header)
payload = await reader.readexactly(length)
if kind != FRAME_UUID or length != 16:
raise ValueError(f"Expected 16-byte binary UUID frame, got kind={kind:#x} len={length}")
call_uuid = str(uuid.UUID(bytes=payload))
caller_id = pending_identities.pop(call_uuid, None)
memory = load_caller_memory(caller_id) # per-caller notes on server
await run_live_session(call_uuid, caller_id, memory, reader, writer)
Once the UUID matches, the bridge loads that caller’s memory file from my server and opens an OpenAI Realtime / GPT-Live session with it as context, and tells the model to speak first. The model’s reply then goes all the way back through the bridge, Asterisk, chan_quectel, the modem and T-Mobile before the caller hears it. After the call, the server saves the audio, the transcript and an updated memory file, so it can greet you by name the next time you call.
For the dropped keypresses, the bridge has a background task that tails messages.log for the +RXDTMF lines and forwards each digit to the active call (ignoring repeats within 1.5 seconds):
import asyncio
import re
import time
from pathlib import Path
from typing import Callable, Optional
DTMF_RE = re.compile(
r"(?:\+RXDTMF|DTMFDET|QTONEDET|CDTMF)\s*[:=]\s*([0-9A-D*#])",
re.IGNORECASE,
)
async def tail_asterisk_dtmf(
log_path: Path,
get_active_call: Callable[[], Optional[object]],
dedupe_window_s: float = 1.5,
) -> None:
last_digit: Optional[str] = None
last_seen: float = 0.0
with log_path.open("r", encoding="utf-8", errors="replace") as fh:
fh.seek(0, 2) # start at EOF
while True:
line = fh.readline()
if not line:
await asyncio.sleep(0.05)
continue
match = DTMF_RE.search(line)
if not match:
continue
digit = match.group(1).upper()
now = time.monotonic()
if digit == last_digit and (now - last_seen) < dedupe_window_s:
continue
last_digit, last_seen = digit, now
active_call = get_active_call()
if active_call is not None:
await active_call.on_digit(digit)
I also tried to send a class 0 flash SMS, which is an old GSM feature where the message pops up on the screen instead of going into the inbox.
Since quectel sms can’t set the DCS byte, I went around Asterisk. I switched the modem to PDU mode (AT+CMGF=0), and sent a GSM 7-bit PDU with DCS set to 0x10 (class 0, flash). I tried it with three different encodings and the modem came back with a +CMGS confirmation every time.
This is what I sent to my AT&T iPhone. It was accepted by my modem and still arrived as a normal text :(
import serial
import time
# Attempt that was valid at our modem (DCS 0x10 = GSM 7-bit, Class 0 flash)
# and still arrived as an ordinary SMS on the receiving AT&T iPhone.
# Stop any other SMS poller before touching /dev/ttyUSB3.
def send_raw_pdu(port: str, tpdu_len: int, pdu_hex: str) -> str:
with serial.Serial(port, 115200, timeout=5) as ser:
ser.write(b"AT+CMGF=0\r") # PDU mode
time.sleep(0.3)
ser.read_all()
ser.write(f"AT+CMGS={tpdu_len}\r".encode())
time.sleep(0.3)
prompt = ser.read_all().decode(errors="replace")
if ">" not in prompt:
raise RuntimeError(f"Expected '>' PDU prompt, got: {prompt!r}")
ser.write(pdu_hex.encode() + b"\x1a") # Ctrl-Z terminates PDU
time.sleep(2.0)
return ser.read_all().decode(errors="replace")
# Look for "+CMGS: <mr>" followed by "OK" in the returned transcript.
I can’t send a text to myself on this line, so I don’t know if it was Tello, T-Mobile, or AT&T that stripped the flag, but there isn’t anything I can change on my end to fix it. I would love some help with this.
For anything real, use Twilio. Besides not having to babysit USB ports and AT commands, the biggest limit with my setup is that one modem and one SIM can only handle one call at a time, so if someone is already on the line the next caller doesn’t get through.
The cost is closer than I expected though:
| My server + SIM7600G-H + Tello | Twilio | |
|---|---|---|
| Upfront hardware | ~$40–$70 (modem + antennas + SIM) | $0 |
| Monthly | ~$10–$25 (unlimited talk/text) | ~$1.15 per US local number (+ A2P 10DLC fees for SMS) |
| Usage | Flat plan minutes/texts | ~$0.0085/min inbound, ~$0.014/min outbound, ~$0.0079/SMS segment + carrier fees |
| Concurrent calls | 1 | As many as you want |
Still, it was fun actually wiring all of this up myself instead of paying an API to hide it. You can call +1 720-345-4122 if you want to try it. Unless you’re on the whitelist, you’ll get Rick Astley.