A burglar alarm is only useful if someone hears it. In the world of monitored security, that "someone" is a central station: a room full of operators watching screens, where every panel in the field checks in over a phone line or the internet. The hardware that answers those calls is called a receiver, and the most common name in the business is Sur-Gard.
This article walks through a working, open receiver built for panels that speak SIA DC-09, the IP alarm reporting standard. Panels send Contact ID or SIA events; the receiver acknowledges them, decrypts them, stores them, alerts the guard, and can even feed a Sur-Gard automation line back out. It is a study in small services talking over an event bus, and in making a legacy alarm protocol behave like a modern data pipeline.
01. Why Build This at All
Commercial receivers are appliances: you buy the box, pay per line, and hope the vendor supports the one protocol your panel fleet speaks. The protocol itself is not secret. SIA DC-09 is an open standard, and the event data inside it (Contact ID) has been documented for decades.
So the interesting engineering problem is not reading the protocol — it is everything around it:
- Sub-Millisecond Wire Response: Acknowledging the panel in milliseconds so it immediately clears its local retransmission buffer.
- Decoupled Persistence: Never dropping an alarm report because a downstream relational database or an external SMS API was busy.
- Zero-Trust Cryptography: Decrypting per-account AES-128 traffic without hardcoding shared secrets in worker threads.
- Active Line Supervision: Deciding when silence means a cut line or communication failure, rather than assuming no news is good news.
- Instant Operator Triage: Putting a human in front of a critical alarm with a one-key acknowledgement and mandatory motive audit reasons.
That cluster of concerns is what this project solves, and it shapes every design decision below.
02. The Shape of the System: Decoupled Event Mesh
The pipeline has one inviolable rule: a slow step must never touch the socket. Ingest talks to panels and does almost nothing. Everything expensive — parsing, decryption, database writes, notifications, and mapping — happens later, off the network thread, over a persistent message bus.
panels --UDP/TCP 3061--> ingest --dsc.raw--> decoder --dsc.event--> persist --> catalog DB
| | |
| | +--> dsc.map
| +-- catalog.account.get (catalog NATS, request/reply)
| +--> automation (Sur-Gard TCP 1025)
| +--> notify (email / Telegram / SMS)
+-- DC-09 ACK built from the clear header, before publish
web dashboard (SSE) and guard console read the stored events and dsc.operator
Each box is its own process. The listener does not import Django; the guard UI does not read UDP; the SMS modem lives on the machine that owns the physical serial port. This separation is what lets the system use the right tool for each job instead of one fragile monolith.
| Process | Runtime | Responsibility |
|---|---|---|
ingest |
asyncio UDP + TCP | Socket, immediate wire ACK, publish dsc.raw |
decoder |
JetStream consumer | DC-09 parse, AES decrypt, publish dsc.event |
catalog |
Django 5 | System of record, web UI, auth, API |
catalog_nats |
Django command | Account, motive, and account-list lookups; GSM heartbeats |
persist |
Django command | Write events, apply acknowledgements, publish dsc.map |
supervision |
timer + consumer | Turn panel silence into an internal YS line fault |
automation |
JetStream consumer | Emit a Sur-Gard line on TCP port 1025 |
notify |
Django command | Fan out to email, Telegram, SMS modem |
guard_console |
Textual TUI | Live terminal queue for the person on duty |
desktop |
Tkinter | Panel list from the catalog HTTP API |
panel_simulator |
plain Python | Generate realistic DC-09 traffic (poll, arm, alarm, restore) |
gsm_gateway |
serial + NATS | Send SMS through an attached hardware modem |
03. On the Wire: SIA DC-09 and Contact ID
SIA DC-09 is an open standard for alarm panels to report over IP (UDP or TCP) instead of a phone line. A frame is a small ASCII envelope wrapped in framing bytes: an LF, a CRC, a hex length, the body, and a CR.
\n67D60027"ADM-CID"1234R0L0#1234[#1234|113001001]\r
\n 67D6 0027 "ADM-CID" 1234 R0 L0 #1234 [#1234|113001001] \r
lf crc length identifier sequence receiver prefix account payload cr
Contact ID is the payload format Ademco defined for phone-line reporting and virtually every panel still emits. A nine-digit token encodes a qualifier (1 = new event vs. 3 = restore), a three-digit event code (130 burglary, 301 AC fail, 110 fire), a partition, and a zone. The receiver keeps a lookup table from code to description and priority.
Two details matter for reliability. The CRC-16/CCITT check lets ingest reject garbage before it wastes any other service's time, and the ACK is a reverse frame built from the same sequence, receiver, prefix, and account, so the panel can match it to the report it just sent:
def crc16_ccitt(data: bytes) -> int:
"""CRC-16/CCITT, polynomial 0x1021, initial value 0x0000."""
crc = 0x0000
for byte in data:
crc ^= byte << 8
for _ in range(8):
crc = ((crc << 1) ^ 0x1021) & 0xFFFF if crc & 0x8000 else (crc << 1) & 0xFFFF
return crc
def build_frame(body: str) -> bytes:
length = f"{len(body):04X}"
crc = f"{crc16_ccitt((length + body).encode('ascii')):04X}"
return LF + crc.encode("ascii") + length.encode("ascii") + body.encode("ascii") + CR
def build_ack(sequence: str, receiver: str, prefix: str, account: str) -> bytes:
body = f'"ACK"{sequence}{receiver}{prefix}#{account}[]'
return build_frame(body)
Framing a message is also how the project turns a parsed alarm back into a Sur-Gard line later. One protocol layer, two directions.
04. Ingest: Answer Fast, Think Later
Ingest is the front door, and it is deliberately dumb. asyncio is Python's built-in cooperative-concurrency library: one thread, an event loop, and coroutines that yield instead of blocking. It is an ideal fit because the listener is entirely I/O-bound — it waits on sockets and message-bus writes far more than it computes — so thousands of field panels cost almost nothing in memory and context switching.
The UDP side is a DatagramProtocol, TCP a plain stream server, and both paths do the same thing: validate, ACK, and hand the raw bytes to the bus:
class PanelProtocol(asyncio.DatagramProtocol):
def datagram_received(self, data: bytes, addr):
header = split_frame(data)
if header and header.identifier not in {"ACK"}:
reply = build_ack(header.sequence, header.receiver,
header.prefix, header.account)
self.transport.sendto(reply, addr)
ack_sent = True
else:
self.transport.sendto(b"\x06", addr) # any sender, even a noisy one
ack_sent = False
asyncio.create_task(self._publish(data, addr, ack_sent))
Notice what is not here: no parsing of the alarm, no database, no decryption. The panel gets its ACK from the clear header immediately (< 2ms), and the publish is scheduled as a task. A single 0x06 goes back to anything that is not a well-formed report, so a misconfigured device is not left waiting indefinitely.
The published envelope is JSON. orjson — a fast, Rust-backed JSON library — serializes it because this code runs on the hot path of every report, and it round-trips bytes and datetimes natively:
envelope = {
"id": uuid4().hex,
"received_at": datetime.now(timezone.utc).isoformat(),
"transport": "udp",
"source": f"{addr[0]}:{addr[1]}",
"listener": f"{BIND}:{PORT}",
"payload_hex": data.hex(),
"ack_sent": ack_sent,
}
await self.js.publish(subject_raw(), orjson.dumps(envelope))
The raw bytes travel as hex. That is deliberate: an unknown, corrupted, or broken frame is still preserved end-to-end, so a future parser can be written from real traffic rather than guesswork.
05. The Bus: NATS and JetStream
NATS is a lightweight, high-performance messaging system built around publish/subscribe subjects. JetStream is its persistence layer: it stores messages in streams and lets consumers replay them with durable positions.
This project uses JetStream as the only bus between services, and the reason is fault isolation. If the database or the SMS modem stalls, its consumer falls behind; the UDP socket keeps accepting and acknowledging panels. Nothing is lost because the stream remembers.
async def connect(url=None, name=""):
nc = NATS()
await nc.connect(**connect_kwargs(url, name))
js = nc.jetstream()
stream, subjects = stream_name(), stream_subjects()
try:
await js.add_stream(name=stream, subjects=subjects, storage=stream_storage())
except Exception:
await js.update_stream(name=stream, subjects=subjects)
return nc, js
Consumers name a durable, so their read position survives a restart and the work is not repeated from the beginning of the stream:
consumer = durable("NATS_DURABLE_DECODER", "decoder")
sub = await js.subscribe(subject_raw(), durable=consumer, queue=consumer)
while True:
msg = await sub.next_msg(timeout=None)
...
await msg.ack()
Not everything belongs on the persistent stream, though. Account lookups and small reference data are transient questions with immediate answers, so they use core NATS request/reply instead: one process asks, whichever catalog process is listening replies. That keeps the durable streams for alarms only and gives lookups a natural timeout instead of an unbounded backlog.
06. Decoding: Bytes to an Event
AES-CBC (Advanced Encryption Standard in Cipher Block Chaining mode) is the symmetric cipher DC-09 allows for payloads. Panels are provisioned with a per-account key; the receiver must hold the same key to read them. The cryptography library provides the primitive. The framing tells us whether a payload is encrypted, and the key is fetched from the catalog over request/reply, never hard-coded:
def decrypt_cbc(blob: bytes, key: bytes) -> bytes:
decryptor = Cipher(algorithms.AES(key), modes.CBC(b"\x00" * 16)).decryptor()
raw = decryptor.update(blob) + decryptor.finalize()
pad = raw[-1]
if 1 <= pad <= 16 and raw.endswith(bytes([pad]) * pad):
raw = raw[:-pad]
return raw
def parse_contact_id(token: str) -> dict | None:
compact = "".join(token.split())
if len(compact) < 9 or compact[0] not in "13":
return None
code = compact[1:4]
description, priority = CONTACT_ID.get(code, (f"Contact ID {code}", "INFO"))
if compact[0] == "3": # qualifier 3 = restore
description, priority = f"Restore: {description}", "INFO"
return {
"qualifier": compact[0], "event_code": code,
"partition": compact[4:6], "zone": compact[6:9],
"description": description, "priority": priority,
}
Poll messages (NULL) deserve special mention because they shape the rest of the design. A panel sends them just to say "I'm alive." They are stored at DEBUG priority and hidden from guards by default, but supervision reads them to prove the panel is still reporting.
07. The Catalog: Django as the System of Record
Django is used for the parts where correctness and a database matter: clients, locations, panels, contacts, events, motives, and delivery attempts. django-allauth handles sign-in. PostgreSQL is the production database, with SQLite as the zero-setup default for local runs. A relational store with migrations is exactly right for a system of record that must be auditable.
def ensure_panel(event: dict) -> Account | None:
code = (event.get("account_code") or "").strip()
account = Account.objects.filter(account_code=code).select_related("location").first()
new_status = status_for(event)
if account is None:
account = Account.objects.create(account_code=code, name=f"Panel {code}",
status=new_status or "ok")
elif new_status is not None and account.status != new_status:
account.status = new_status
account.save(update_fields=["status"])
if account.location_id and new_status is not None:
location = account.location
location.status = worst_status(location.accounts.values_list("status", flat=True))
location.save(update_fields=["status"])
return account
Lookups are a separate process, nats_catalog, so a slow page render never holds up an encryption key request:
async def account_get(msg):
code = json.loads(msg.data.decode()).get("account_code", "")
payload = await sync_to_async(self._account)(code) # ORM on a worker thread
await msg.respond(json.dumps(payload).encode())
The seam between sync and async is handled with sync_to_async, since Django's ORM is synchronous and the NATS client is asynchronous.
08. Live Views: SSE, MapLibre & Audible Alerts
Guards need the board to update without refreshing, so the catalog streams events with Server-Sent Events (SSE) — a one-way HTTP stream where the server keeps a connection open and pushes data: lines. It is simpler than WebSockets because traffic only flows outward. The generator polls the database for new rows past a watermark, emits them, sends a heartbeat comment to keep proxies happy, then sleeps:
def generate():
latest = _stream_events(user, allowed, focus_location, focus_account) \
.order_by("-received_at", "-id").values_list("received_at", "id").first()
watermark = latest[0] if latest else None
seen = {latest[1]} if latest else set()
while True:
for row in _events_after(user, watermark, seen, allowed, ...):
seen.add(row["pk"]); watermark = row["received_at"]
yield f"data: {json.dumps(row['payload'])}\n\n"
yield ": ping\n\n"
time.sleep(integer("SSE_POLL_SECONDS", 2))
response = StreamingHttpResponse(generate(), content_type="text/event-stream")
09. Supervision: When Silence Becomes a Fault
A panel that stops reporting is itself an alarm. Supervision watches for that. It loads each account's supervision_seconds window from the catalog at startup, then refreshes a last_seen timestamp on every event for a known account — polls included. On a timer it checks for accounts that have reported at least once but have since gone quiet, and emits an internal YS communication-fault event:
for code, state in list(states.items()):
if not state["enabled"] or state["last_seen"] is None:
continue
silent = now - state["last_seen"]
if silent > state["seconds"] and now - state["last_fault"] > state["seconds"]:
state["last_fault"] = now
await js.publish(subject_event(), orjson.dumps({
"id": uuid4().hex,
"received_at": datetime.now(timezone.utc).isoformat(),
"source": "supervision", "protocol": "internal",
"account_code": code, "qualifier": "1", "event_code": fault,
"partition": "00", "zone": "000", "priority": "CRITICAL",
"description": f"No poll from account {code} for {int(silent)}s",
}))
The process deliberately ignores its own YS faults when refreshing last_seen, and it will not repeat a fault until a full window has passed again — otherwise a long outage would flood the queue with identical alarms.
10. Automation: Emulating Sur-Gard MLR2 on TCP 1025
A central station is rarely greenfield. The automation output here speaks the Sur-Gard MLR2 line format, which is a compact text record sent over TCP (port 1025) and terminated with a 0x14 byte. This is how the receiver can sit alongside, or replace, an existing commercial head end:
def surgard_cid(event: dict, receiver: str = RECEIVER, line: str = LINE) -> bytes:
account = (event.get("account_code") or "0000")[-4:].zfill(4)
qualifier = event.get("qualifier") or "1"
code = (event.get("event_code") or "000").zfill(3)[-3:]
part = (event.get("partition") or "00").zfill(2)[-2:]
zone = (event.get("zone") or "000").zfill(3)[-3:]
body = f"5{receiver}{line} 18{account}{qualifier}{code}{part}{zone}"
return body.encode("ascii") + b"\x14"
If no automation host is configured, the line is simply logged, making the whole pipeline safe to run in development. If a connection breaks, the next event reopens it automatically.
11. The Edges: Textual, Tkinter, Simulator & GSM Modem
The person on duty deserves their own interface. The guard console is built with Textual, a Python framework for rich terminal user interfaces. It shows critical alarms and warnings newest-first, rings the bell, and plays a siren on a fresh critical alarm — but only if the event is less than 20 seconds old, preventing historical JetStream replays from ringing sirens. A single key acknowledges an alarm with a mandatory motive:
BINDINGS = [
("a", "acknowledge", "Acknowledge"),
("b", "backend", "Backend"),
("q", "quit", "Quit"),
]
You cannot develop an alarm receiver without traffic, so the panel simulator generates realistic DC-09 frames and walks each panel through a plausible day: poll, arm, alarm, restore:
def contact_id(panel: Panel, qualifier: str, code: str, zone: str = "000") -> Signal:
sequence = take_sequence(panel)
token = f"{qualifier}{code}01{zone}"
body = f'"ADM-CID"{sequence}L0#{panel.account}[#{panel.account}|{token}]'
return Signal(panel.account, sequence, "ADM-CID", f"{code} zone {zone}", build_frame(body))
Finally, the SMS path. A pyserial-driven gateway on a small board with a GSM modem sends text messages using AT text mode commands: AT+CMGF=1 selects text mode, AT+CMGS starts a message, and 0x1A (Ctrl-Z) commits it:
def send_sms(to: str, text: str):
port = serial.Serial(MODEM, MODEM_BAUD, timeout=MODEM_TIMEOUT)
try:
port.write(b"AT+CMGF=1\r"); port.readline()
port.write(f'AT+CMGS="{to}"\r'.encode()); port.readline()
port.write(text.encode("utf-8") + bytes([0x1A]))
reply = port.read(256).decode(errors="replace")
finally:
port.close()
if "ERROR" in reply:
raise RuntimeError(reply.strip())
12. Shipping It: Docker, a VPS, and Configuration
Docker Compose runs the whole stack with one command. Every service builds the same image but starts a different command, which keeps deployment simple: NATS, PostgreSQL, the Django web process, ingest, decoder, supervision, and automation all come up together:
ingest:
build: .
environment:
NATS_URL: nats://nats:4222
INGEST_PORT: "3061"
ports:
- "${INGEST_PUBLISH_PORT:-3061}:3061/udp"
- "${INGEST_PUBLISH_PORT:-3061}:3061/tcp"
command: python /app/services/ingest/main.py
Configuration is environment-first. A small shared module reads every value with a sane default:
def text(name: str, default: str) -> str:
value = os.environ.get(name)
return default if value is None or not value.strip() else value.strip()
def nats_url() -> str:
# 4223 is the host port published by Compose; inside the network it is nats://nats:4222
return text("NATS_URL", "nats://127.0.0.1:4223")
On a Debian or Ubuntu VPS, systemd runs each Python process as its own unit under dsc.target. Nginx acts as the public HTTP reverse proxy, disabling buffering for /events/stream/ so SSE comments reach browsers without delay. Ingest sits directly exposed on UDP & TCP port 3061.
13. What Makes It Work
Three core engineering ideas carry the whole design:
- Acknowledge first, process later: Keeps physical alarm communicators happy and the network socket clear, even when downstream databases or workers are under heavy load.
- A durable bus is the contract: Services can restart, scale, or fail independently as long as NATS JetStream subjects and event shapes hold.
- Give unknowns a home: Encrypted-but-keyless, unparsed, and poll messages are all preserved with priority and status tags. In life-safety systems, "we did not understand this, but we kept it" is an essential feature, not a failure.
Everything else — Django for the book of record, Textual for the guard, Tkinter for fleet admin, and a modem for SMS — is the right tool dropped into a slot the pipeline defined first.
14. References & Technical Standards
Digital Communication Standard, Internet Protocol event reporting standard.
Reporting format specification for event code, qualifier, and zone layout.
High-performance publish/subscribe messaging system with persistent streams.
Open-source WebGL map renderer paired with OpenFreeMap vector styles.
Rich Python terminal user interfaces for async event-driven keyboard consoles.
WHATWG standard for lightweight real-time HTTP server-to-browser push streaming.