DSC IP Communicator: Sur-Gard-Style IP Receiver & Central Station Alarm Platform
An open, carrier-grade IP alarm monitoring receiver built from the ground up for physical security panels communicating via SIA DC-09 and Ademco Contact ID over UDP/TCP. Architected around the inviolable principle of "Acknowledge first, process later": wire frames are acknowledged in under 2 milliseconds from clear headers, while parsing, AES-128 decryption, database ledgering, map plotting, SMS dispatch, and Sur-Gard automation feeds run over persistent NATS JetStream queues without ever stalling physical alarm sockets.
Mission-Critical Receiver SLA
Proprietary Boxes & Monolithic Latency
Commercial alarm receivers (like Sur-Gard System IV/5) are expensive hardware appliances sold with strict line-licensing fees and opaque firmware. When modern security fleets expand across thousands of IP communicators (DSC PowerSeries, Neo, Alexor), reporting over cellular LTE or broadband, traditional monolithic architectures fail under alarm storms.
If an incoming packet requires a synchronous database transaction or an external key lookup before returning an acknowledgement (ACK), the physical communicator times out and re-transmits. This triggers catastrophic retry avalanches, congested UDP sockets, and delayed human response when burglaries or fire signals occur.
Asynchronous, Decoupled Event Mesh
DSC IP Communicator enforces one core rule: a slow step must never touch the network
socket. Lightweight Python asyncio UDP and TCP daemons validate CRC-16 framing and
immediately dispatch reverse ACK frames in single-digit milliseconds using only the clear packet header.
Raw hex payloads are published to NATS JetStream. Independent, durable consumers decrypt AES-128 payloads, map Contact ID tokens, persist audit rows in PostgreSQL, update real-time WebGL vector maps via Server-Sent Events (SSE), sound sirens on terminal consoles, and forward Sur-Gard automation feeds without coupling.
End-to-End System Topology
The pipeline completely decouples incoming physical alarm traffic from persistent business logic, operators, and external automation software:
[ DSC / SIA DC-09 Panels ] (UDP/TCP Port 3061)
│
├────── Immediate Wire ACK (< 2ms built from clear header)
│
[ Ingest Daemon ] (Python asyncio DatagramProtocol & StreamServer)
│
│ orjson Hex Payload (`dsc.raw` subject)
│
[ NATS JetStream Message Bus ] (Durable Stream: `DSC`)
│
├──[ Decoder Worker ] (AES-128-CBC Decrypt, Contact ID / SIA Parser)
│ │
│ ├─[ Catalog NATS ] (Request/Reply Account & Key Lookup)
│ ├─[ Automation Line ] (Sur-Gard MLR2 TCP Port 1025)
│ └─[ Notification Engine ] (Email / Telegram / SMS Modem)
│
├──[ Persist Worker ] (Django ORM, PostgreSQL / SQLite Ledger)
│ │
│ └─Publish `dsc.map`
│
└──[ Supervision Watchdog ] (Window Timer: Silent Panel ──`YS` Fault)
[ Real-Time Operator Consoles ]
├─ Web Dashboard NOC (Server-Sent Events `/events/stream/` + MapLibre GL JS)
├─ Terminal Guard Console (Textual TUI with siren & motive clearance hotkeys)
├─ Desktop Admin Tool (Tkinter desktop client)
└─ GSM Serial Gateway (pyserial AT Command modem controller)
Every service runs as an isolated process in Docker
Compose or native systemd units orchestrated by dsc.target.
Microservice Matrix
| Process | Runtime | Responsibility |
|---|---|---|
ingest |
asyncio | Socket, immediate ACK, publish dsc.raw |
decoder |
JetStream | DC-09 parse, AES decrypt, publish dsc.event |
catalog |
Django 5 | System of record, web UI, auth, API |
catalog_nats |
Command | NATS request/reply account, motive & GSM lookups |
persist |
Command | Write event ledger, apply acks, publish dsc.map |
supervision |
Timer | Transforms panel silence into an internal YS fault |
automation |
Consumer | Emits Sur-Gard MLR2 lines on TCP port 1025 |
notify |
Plugins | Multi-channel fanout (Email, Telegram, SMS) |
guard_console |
Textual | Keyboard-driven live terminal queue for duty officers |
desktop |
Tkinter | Desktop maintenance UI for panel account fleets |
panel_simulator |
Python | DC-09 traffic generator (poll, arm, alarm, restore) |
gsm_gateway |
Serial+NATS | Dedicated hardware GSM modem AT-command sender |
Core Architectural Pillars
Explore how each layer in the DSC IP Communicator platform guarantees zero message loss, sub-millisecond responsiveness, and operator safety.
Sub-Millisecond Wire Ingest & ACK
Handles concurrent UDP and TCP alarm packets on port 3061. Employs CRC-16/CCITT verification to reject corrupt packets instantly. Reverse ACK frames are synthesized immediately from sequence, receiver, prefix, and account tokens without database interaction, keeping panel transmit queues empty.
SIA DC-09 & Contact ID Normalization
Dissects ASCII framing envelopes: LF, CRC, hex length, body, and CR. Unpacks Ademco Contact ID payloads
into event codes, qualifiers (event vs. restore), partitions, and zones. Normalizes signals against
comprehensive security tables (e.g., 130 Burglary, 110 Fire, 301 AC
Loss).
Fault-Tolerant NATS JetStream
A single DSC stream persists all alarm raw data, decoded events, and SMS jobs. Durable queue
consumers ensure downstream database slowdowns or SMS delays never block listener threads. Core NATS
request/reply handles instantaneous account and encryption key lookups.
Per-Account AES-128-CBC Decryption
Encrypted DC-09 frames have their 16-byte hex keys fetched dynamically over NATS request/reply from the
catalog without exposing database credentials to decoder nodes. Implements PKCS#7 unpadding and zero-IV
AES-CBC decryption using Python's cryptography engine.
Supervision & Silent Line Faults
In security monitoring, silence is an alarm. The supervision engine maintains live heartbeat timers across
thousands of panel accounts using periodic NULL polls. If a panel exceeds its configured
supervision window (e.g., 300s), an internal YS communication fault is generated.
Sur-Gard MLR2 Automation Gateway
Exposes a TCP stream on port 1025 emulating a standard Sur-Gard receiver line with 0x14
terminators. Allows DSC IP Communicator to sit transparently in front of legacy commercial monitoring
software (Manitou, Bold Gemini, SIMS) without requiring software overhauls.
Live SSE Dashboard & WebGL Map
Lightweight Server-Sent Events push unacknowledged alarms to web browsers with zero socket overhead. Integrates MapLibre GL JS with OpenFreeMap vector tiles to plot accounts geographically, flash red on critical events, open location details, and trigger browser audio sirens.
Textual TUI & Motive Clearance
Duty operators run a dedicated Textual terminal application with keyboard hotkeys ([a]
Acknowledge, [b] Backend, [q] Quit) and terminal sirens. Enforces mandatory
catalog motives (e.g., False Alarm, Guard Dispatched, System Test) synced in real-time across terminals
and web.
Hardware GSM Modem & Docker Ops
Decoupled pyserial gateway controls USB/serial GSM modems using raw AT text commands
(AT+CMGF=1, AT+CMGS) isolated behind NATS. The entire 12-process architecture
spins up with one docker compose up or runs natively under Ubuntu/Debian
systemd.
System Screenshots & Operations Gallery
Click any screenshot to open the interactive carousel lightbox with zoom, pan, and full-resolution controls.
Central Station Operator Login
Secure role-based sign-in for monitoring guards, system administrators, and multi-tenant client subscribers with social provider integration.
Operator & Client Registration
Invitation-based onboarding portal with password complexity validation and automated account association rules.
Central Administration Hub
Operations navigation grid showing direct launch triggers for Live Events, Monitored Locations, Panel Accounts, and Telemetry Gateways.
Real-Time MapLibre Vector Map
WebGL map plotting all protected client facilities across the region with OpenFreeMap vector tiles, showing worst-case health status per site.
Geographic Alarm Incident Popup
Interactive map marker drill-down showing triggering account #1234, street address, emergency contact numbers, and 1-click event log jump.
Operator Profile & Localization
User preferences card supporting bilingual Spanish/English localization, dark theme options, and escalation alert channel routing.
Monitored Locations & Sites
Hierarchical facility catalog managing geographic coordinates, active subscriber accounts, assigned security zones, and rollup status.
Panel Fleet & Account Keys
Registry of field communicators detailing account codes, AES-128 encryption keys, supervision heartbeat seconds (300s), and current line health.
Emergency Escalation Contacts
Multi-tier keyholder contact directory with phone priority order, Telegram handle bindings, and SMS dispatch permissions per site.
Subscriber Clients & Portfolios
Customer management table isolating accounts by subscriber company, managing service SLAs, and restricting login scopes.
Notification Dispatch Providers
Configuration console for outbound alert dispatchers: Telegram Bot tokens, SMTP gateways, Twilio SMS REST APIs, and GSM serial modems.
Hardware GSM Modem Telemetry
Live status dashboard for the serial GSM modem gateway showing COM port attachment, carrier registration, signal RSSI, and NATS heartbeats.
Alarm Clearance Motives Catalog
Standardized clearance taxonomy forcing operators to select verified causes (False Alarm, Dispatch Guard, Maintenance Test) for legal audits.
Live Events Queue (Server-Sent Events)
High-priority live alarm stream updating in real time via HTTP SSE with visual flashing badges, audio sirens, and instant operator triage actions.
Filtered Live Queue & Priorities
Real-time faceted filter view slicing alarms by Criticality, Account ID, Zone, and Acknowledged status during major storm conditions.
Event Forensics & Wire Inspection
Detailed event drill-down displaying decoded Contact ID tokens, raw DC-09 byte envelopes, IP transport origins, and 1-click clearance with operator note.
Historical Event Audit Trail
High-performance DataTables ledger with millisecond search, sorting, and CSV/PDF export across millions of archived alarm reports.
Notification Delivery Receipts
Granular delivery attempt ledger tracking SMS carrier message IDs, Telegram response codes, SMTP handshakes, and retry timestamps.
Textual TUI Terminal Guard Console
High-speed terminal user interface built with Textual: keyboard
hotkeys ([a] Ack, [b] Backend, [q] Quit), live JetStream feed,
and bell audio alerts.
Core Implementation Snippets
Review authentic implementation patterns extracted from DSC IP Communicator production services.
core/framing.py
SIA DC-09 Wire Envelope
CRC-16/CCITT Calculation & Reverse ACK Builder
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:
"""Builds LF + CRC(4) + LEN(4) + BODY + CR envelope."""
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:
"""Synthesizes the SIA reverse ACK frame back to the alarm communicator."""
body = f'"ACK"{sequence}{receiver}{prefix}#{account}[]'
return build_frame(body)
The reverse ACK reuses sequence, receiver, prefix, and account from the inbound packet, informing the panel to clear its local retransmission buffer immediately.
services/ingest/main.py
asyncio Network Socket
Immediate Wire ACK & Decoupled NATS Publish
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
# Asynchronously schedule persistent NATS publish off the network loop
asyncio.create_task(self._publish(data, addr, ack_sent))
async def _publish(self, data: bytes, addr, ack_sent: bool):
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 listener executes zero database queries and zero decryption before responding. Fast
orjson preserves unparsed raw hex for downstream auditing.
services/decoder/crypto.py
Symmetric Cryptography
AES-128-CBC Decryption & PKCS#7 Unpadding
def decrypt_cbc(blob: bytes, key: bytes) -> bytes:
"""Decrypts SIA DC-09 AES-128-CBC payload using zero IV vector."""
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,
}
Keys are looked up on demand via NATS request/reply from the catalog service, ensuring cryptographic keys are never hard-coded in worker containers.
services/supervision/main.py
Heartbeat Watchdog
Silent Line Fault Detection (YS Event Generator)
for code, state in list(states.items()):
if not state["enabled"] or state["last_seen"] is None:
continue
silent = now - state["last_seen"]
# If panel exceeded supervision window and fault hasn't been re-issued
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 supervision service suppresses self-generated fault loops and maintains an anti-flapping guard to avoid flood storms during prolonged network outages.
services/automation/surgard.py
MLR2 Line Protocol
Sur-Gard MLR2 TCP Port 1025 Frame Emitter
def surgard_cid(event: dict, receiver: str = RECEIVER, line: str = LINE) -> bytes:
"""Formats an event into a Sur-Gard MLR2 string terminated with 0x14."""
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"
Outbound automation lines maintain stateless auto-reconnection over TCP port 1025, allowing standard central station software to receive clean alarm data.
services/gsm_gateway/main.py
Serial AT Commands
Hardware GSM Modem Text Mode Transmission
def send_sms(to: str, text: str):
"""Sends SMS via pyserial AT commands with Ctrl-Z termination."""
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])) # 0x1A = Ctrl-Z commit
reply = port.read(256).decode(errors="replace")
finally:
port.close()
if "ERROR" in reply:
raise RuntimeError(reply.strip())
The GSM board communicates strictly over NATS subjects (sms.send.*,
sms.result.*), isolating physical serial port hardware from cloud databases.
Production Deployment: Docker & systemd
The entire platform is designed for zero-headache deployment across single developer laptops or carrier VPS instances:
- Docker Compose: Single command orchestrates NATS
JetStream, PostgreSQL, Django web app, Ingest listener, Decoders, Supervision, and Automation. Ports are
mapped cleanly: Ingest (
3061TCP/UDP), NATS (4223), Catalog (8010). - Native systemd Units: On Ubuntu/Debian production
hosts, each Python process runs under its own unit under
dsc.target. Ingest listens directly on3061, while Gunicorn powers the SSE web dashboard. - Nginx SSE Proxying: Configured with
proxy_buffering offfor/events/stream/so heartbeat comments (: ping) immediately stream to the MapLibre dashboard.
# docker-compose.yml excerpt
services:
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
restart: unless-stopped
decoder:
build: .
environment:
NATS_URL: nats://nats:4222
command: python /app/services/decoder/main.py
depends_on: [nats]
Standards & Technical References
Built upon decades of established physical security specifications and modern distributed systems engineering:
Digital Communication Standard, Internet Protocol event reporting specification.
Security Industry AssociationIndustry-standard payload format for burglar alarm, fire, and restore reporting.
Ademco CP-04 Standard TablesCloud-native messaging system with durable streams, at-least-once delivery, and consumer groups.
docs.nats.ioOpen-source WebGL map rendering engine paired with free vector tiles for live tracking.
maplibre.orgModern Python terminal user interface framework for async event-driven keyboard consoles.
textualize.ioWHATWG HTML Living Standard for push notifications from HTTP server to web browsers.
whatwg.org