SIA DC-09 & Contact ID NATS JetStream 2.10 asyncio < 2ms Ingest ACK AES-128-CBC Decryption Sur-Gard MLR2 TCP 1025

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.

SIA DC-09 (ANSI/SIA CP-04) Ademco Contact ID Sur-Gard MLR2 (TCP 1025) Python 3.12 asyncio NATS JetStream (Durable Queues) AES-128-CBC Cryptography Heartbeat Supervision Watchdog Server-Sent Events (SSE) MapLibre GL JS & OpenFreeMap Textual TUI Guard Console Tkinter Admin Tool GSM Modem AT Gateway Django 5 & PostgreSQL Docker Compose & systemd

Mission-Critical Receiver SLA

<2ms
Wire Ingest ACK Time
100%
Durable JetStream Bus
300s
Poll Supervision Fault
1025 TCP
Sur-Gard MLR2 Feed
Zero lost reports: unparsed or encrypted-without-key signals preserved in raw hex audit queues.
The Central Station Dilemma

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.

The Architectural Solution

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:

System Architecture Topology
  [ 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
Deep Technical Breakdown

Core Architectural Pillars

Explore how each layer in the DSC IP Communicator platform guarantees zero message loss, sub-millisecond responsiveness, and operator safety.

Wire Protocol

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.

asyncio CRC-16/CCITT Reverse ACK
Protocol Parsing

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).

SIA DC-09 ADM-CID Event Mapping
Streaming Bus

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.

JetStream Durable Queues Request/Reply
Cryptography

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.

AES-128-CBC PKCS#7 Dynamic Keys
Supervision

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.

Poll Watchdog YS Faults Anti-Flapping
Legacy Bridge

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.

Sur-Gard MLR2 TCP 1025 Drop-in Gateway
Operations NOC

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.

Server-Sent Events MapLibre GL JS OpenFreeMap
Operator TUI

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.

Textual TUI Hotkeys Motive Audit
Hardware & Ops

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.

pyserial AT Docker Compose systemd Units
Visual Showcase

System Screenshots & Operations Gallery

Click any screenshot to open the interactive carousel lightbox with zoom, pan, and full-resolution controls.

Central Monitoring Station Secure Login
Authentication Figure 01

Central Station Operator Login

Secure role-based sign-in for monitoring guards, system administrators, and multi-tenant client subscribers with social provider integration.

Client & Operator Registration
Onboarding Figure 02

Operator & Client Registration

Invitation-based onboarding portal with password complexity validation and automated account association rules.

Central Station Administration Overview
NOC Overview Figure 03

Central Administration Hub

Operations navigation grid showing direct launch triggers for Live Events, Monitored Locations, Panel Accounts, and Telemetry Gateways.

MapLibre WebGL Live Monitoring Map
Geographic NOC Figure 04

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 Drill-Down
Incident Triage Figure 05

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 & Notification Preferences
Preferences Figure 06

Operator Profile & Localization

User preferences card supporting bilingual Spanish/English localization, dark theme options, and escalation alert channel routing.

Protected Locations Catalog Directory
Catalog Figure 07

Monitored Locations & Sites

Hierarchical facility catalog managing geographic coordinates, active subscriber accounts, assigned security zones, and rollup status.

Alarm Panel Account Fleet Directory
Fleet Management Figure 08

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 Directory
Escalation Figure 09

Emergency Escalation Contacts

Multi-tier keyholder contact directory with phone priority order, Telegram handle bindings, and SMS dispatch permissions per site.

Multi-Tenant Clients Directory
Multi-Tenant Figure 10

Subscriber Clients & Portfolios

Customer management table isolating accounts by subscriber company, managing service SLAs, and restricting login scopes.

Notification & Dispatch Provider Configuration
Telephony Figure 11

Notification Dispatch Providers

Configuration console for outbound alert dispatchers: Telegram Bot tokens, SMTP gateways, Twilio SMS REST APIs, and GSM serial modems.

Hardware GSM Gateway Telemetry & Status
Hardware Edge Figure 12

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 Acknowledgment Motives Catalog
Audit Motives Figure 13

Alarm Clearance Motives Catalog

Standardized clearance taxonomy forcing operators to select verified causes (False Alarm, Dispatch Guard, Maintenance Test) for legal audits.

Real-Time SSE Live Events Alarm Feed
Live Feed Figure 14

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 Events Alarm Stream
Queue Slicing Figure 15

Filtered Live Queue & Priorities

Real-time faceted filter view slicing alarms by Criticality, Account ID, Zone, and Acknowledged status during major storm conditions.

Raw DC-09 Wire Payload & Event Breakdown Modal
Forensics Figure 16

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 Log with DataTables
Audit Ledger Figure 17

Historical Event Audit Trail

High-performance DataTables ledger with millisecond search, sorting, and CSV/PDF export across millions of archived alarm reports.

Multi-Channel Notification Dispatch Audit
Dispatch Log Figure 18

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
Terminal TUI Figure 19

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.

Code Level Walkthrough

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

core/framing.py
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

services/ingest/main.py
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

services/decoder/crypto.py
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)

services/supervision/main.py
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

services/automation/surgard.py
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

services/gsm_gateway/main.py
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 (3061 TCP/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 on 3061, while Gunicorn powers the SSE web dashboard.
  • Nginx SSE Proxying: Configured with proxy_buffering off for /events/stream/ so heartbeat comments (: ping) immediately stream to the MapLibre dashboard.
docker-compose.yml
# 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:

SIA DC-09 Standard

Digital Communication Standard, Internet Protocol event reporting specification.

Security Industry Association
Ademco Contact ID

Industry-standard payload format for burglar alarm, fire, and restore reporting.

Ademco CP-04 Standard Tables
NATS JetStream

Cloud-native messaging system with durable streams, at-least-once delivery, and consumer groups.

docs.nats.io
MapLibre GL JS & OpenFreeMap

Open-source WebGL map rendering engine paired with free vector tiles for live tracking.

maplibre.org
Textual TUI Framework

Modern Python terminal user interface framework for async event-driven keyboard consoles.

textualize.io
Server-Sent Events (SSE)

WHATWG HTML Living Standard for push notifications from HTTP server to web browsers.

whatwg.org
Next Engineering Project

VoltGrid EV Charging Network