Ajax Alarm Events and a Local AI: Event Triage
An alarm system such as Ajax produces many events and most of them are routine. We build a small helper on a local AI server: rules guard the floor, the model suggests a priority and a human decides. Nothing is sent and nobody is called automatically.
mistral, checked on ollama.com) and the outdated n8n export. We added: the public ways for events to leave the system, our own neutral event format, rules that set the lowest priority (the model can only raise it), a model answer constrained by a schema, behaviour when the model fails, an audit table and a way to measure how often it is wrong.rules.py (plain Python, no extra packages) with invented values. The other files were checked for syntax errors but were not run — which is why there is neither a "TESTED" nor a "VERIFIED" label. The table of event codes follows the common Contact ID style and was not checked against an Ajax document ⚠️. The quality of mistral in Bulgarian and the speed of the machine were not measured.01What you'll learn
- What the public ways are for Ajax events to reach monitoring software, and where the public information ends.
- How to describe an event in your own neutral format.
- Why the rules come before the model, and how the model only raises the priority and never lowers it.
- How to ask a local model for an answer that follows a schema (JSON schema) through Ollama.
- What happens when the model is down, and how not to lose an event.
- How to wire n8n so that it notifies a human, and how to measure how often the system is wrong.
02Before you start
- A machine of the NVIDIA GB10 class with DGX OS, running Ollama (see lesson 04-01 for the basics).
- The
mistralmodel: 7B, about 4.4 GB, 32K context (per ollama.com as of 03.10.2026):ollama pull mistral. - PostgreSQL 14 or newer (the current version is 18) and Python 3.10 or newer.
- The packages
fastapi,uvicorn,asyncpg,httpxandpydantic(version 2). They are not pinned: after the first successful run, write your versions intorequirements.txt. - Access to the events by one of the routes in step 1 — or invented events, with which the whole lesson works.
03Steps
Where the events come from
Our layer does not talk to the hub directly. It sits after the monitoring software and receives the events from it. That way we do not depend on undocumented addresses and we change nothing in the alarm system itself. Ajax's public information (03.10.2026) shows these routes:
Route What it is (per Ajax) Protocols and notes Ajax PRO Desktop an app for monitoring and handling alarms alarms are handled inside the app Ajax Translator PRO / Translator translates events for the station software SIA DC-09, Contact ID (SurGard), Manitou, MASXML and others — see Ajax's table Ajax Cloud Signaling events go through the Ajax cloud, with no server of your own at the station SIA DC-09, SurGard (Contact ID), Manitou, MASXML and others Direct connection TCP/IP or a serial port SIA DC-09 (SIA-DCS) Enterprise API an interface for large companies with thousands of systems access on request; the documentation is provided after the request — we do not reproduce it here The practical way: if your monitoring software (or Ajax PRO Desktop) can forward or export events — over HTTP, into a file or through n8n — feed them to the service from step 6. If you have access to the Enterprise API, Ajax gives you the documentation and it overrides this lesson. If you have neither, carry on with invented events: everything below works that way.
An event in your own neutral format
Whatever the source, you reduce the event to a small set of fields. That way the service does not change when you change the software.
Field What it is Example (invented) site_ref your own internal site number site-001 event_code the event code from the monitoring software 130 qualifier E — new event, R — restore (Contact ID style) E zone zone or room north entrance device_type device type motion detector occurred_at when it happened (time with zone) 2026-10-03T02:30:00+03:00 source where it came from test ✅No names in the eventUse only an internal site number. A customer name, an address or a person in the event is not needed and increases the risk.The tables
We keep separately what the rules say (
rule_floor), what the model suggested (model_pri) and the final priority (priority). That way you can always explain why a decision was made.sql · schema.sql-- Needs PostgreSQL 14 or newer CREATE TABLE sites ( site_ref TEXT PRIMARY KEY, -- your own neutral id, e.g. 'site-001' tz TEXT NOT NULL DEFAULT 'Europe/Sofia', open_time TIME NOT NULL DEFAULT '08:00', close_time TIME NOT NULL DEFAULT '20:00' ); CREATE TABLE alarm_events ( id BIGSERIAL PRIMARY KEY, received_at TIMESTAMPTZ NOT NULL DEFAULT now(), occurred_at TIMESTAMPTZ NOT NULL, site_ref TEXT NOT NULL, source TEXT NOT NULL, -- 'cms-export' | 'enterprise-api' | 'test' event_code TEXT NOT NULL, -- e.g. a Contact ID style code: '130' qualifier TEXT, -- 'E' new event, 'R' restore zone TEXT, device_type TEXT, rule_floor TEXT NOT NULL, -- lowest priority the rules allow model_pri TEXT, -- what the model suggested (NULL if it failed) priority TEXT NOT NULL, -- final = the higher of the two ai_reason TEXT, status TEXT NOT NULL DEFAULT 'new', -- new | acknowledged | closed handled_by TEXT, handled_at TIMESTAMPTZ ); CREATE INDEX ON alarm_events (site_ref, received_at DESC); CREATE INDEX ON alarm_events (status, received_at DESC);Events are not deleted by the system on their own; you decide the retention period with your lawyer.
The rules — the floor
We run simple rules first. They answer the question "how low can this priority go?". Why before the model: a model can be wrong or fail; a rule cannot. An unknown code is never ignored, and an event outside business hours is raised by one level (except the periodic test).
Code Meaning Lowest 110 · 120 fire · panic CRITICAL 130 · 137 · 140 burglary · tamper · general alarm HIGH 301 · 302 · 350 · 381 mains loss · low system battery · communication trouble · lost radio device MEDIUM 384 · 401 · 602 device low battery · open/close by a user · periodic test LOW anything else unknown code MEDIUM python · rules.pyfrom datetime import datetime, time from zoneinfo import ZoneInfo ORDER = ["LOW", "MEDIUM", "HIGH", "CRITICAL"] # Lowest priority per event code. Codes follow the common Contact ID style; # use the codes your monitoring software really sends. FLOOR = { "110": "CRITICAL", # fire "120": "CRITICAL", # panic "130": "HIGH", # burglary alarm "137": "HIGH", # tamper "140": "HIGH", # general alarm "301": "MEDIUM", # mains power loss "302": "MEDIUM", # low system battery "350": "MEDIUM", # communication trouble "381": "MEDIUM", # loss of supervision (radio device) "384": "LOW", # radio device, low battery "401": "LOW", # open/close by user "602": "LOW", # periodic test report } UNKNOWN_FLOOR = "MEDIUM" # an unknown code is never ignored def floor_for(code: str) -> str: return FLOOR.get(code, UNKNOWN_FLOOR) def at_least(a: str, b: str) -> str: """Return the higher of two priorities.""" return a if ORDER.index(a) >= ORDER.index(b) else b def bump(level: str) -> str: return ORDER[min(ORDER.index(level) + 1, len(ORDER) - 1)] def outside_hours(when: datetime, tz: str, opens: time, closes: time) -> bool: local = when.astimezone(ZoneInfo(tz)).time() return not (opens <= local <= closes)⚠️The codes are not checked against AjaxThe table follows the common Contact ID style. What exactly your hub sends and by which route, see in the Translator manual or in your monitoring software, and fixFLOOR.The model suggests
We pull the model and call it through the Ollama API. We ask for an answer that follows a schema: the
formatparameter accepts a JSON schema, so the priority is always one of the four values. Temperature 0 makes the answers more repeatable (it does not guarantee identical ones).bashollama pull mistralpython · triage.pyimport json import os import httpx from rules import ORDER OLLAMA_URL = os.environ.get("OLLAMA_URL", "http://localhost:11434") MODEL = os.environ.get("TRIAGE_MODEL", "mistral") SCHEMA = { "type": "object", "properties": { "priority": {"type": "string", "enum": ORDER}, "reason": {"type": "string"}, "false_alarm_likelihood": {"type": "string", "enum": ["low", "medium", "high"]}, }, "required": ["priority", "reason", "false_alarm_likelihood"], } SYSTEM = ( "You help a human operator triage events from a monitored alarm system. " "You only suggest a priority; a human decides what to do. " "Priorities: LOW (routine), MEDIUM (needs a look), HIGH (likely real, act soon), " "CRITICAL (act now). Use the context. If unsure, choose the higher priority. " "Reply with JSON only." ) async def ask_model(ctx: dict, lang: str = "Bulgarian"): """Return a dict with priority/reason, or None if the model is unavailable or answers badly.""" user = ( f"Event context:\n{json.dumps(ctx, ensure_ascii=False)}\n" f"Write the reason in {lang}, at most 25 words." ) payload = { "model": MODEL, "stream": False, "format": SCHEMA, "options": {"temperature": 0, "num_predict": 200}, "messages": [ {"role": "system", "content": SYSTEM}, {"role": "user", "content": user}, ], } try: async with httpx.AsyncClient(timeout=60) as client: r = await client.post(f"{OLLAMA_URL}/api/chat", json=payload) r.raise_for_status() out = json.loads(r.json()["message"]["content"]) if out.get("priority") not in ORDER: return None return out except Exception: return NoneIf the model does not answer, or answers in a way that cannot be read,
ask_modelreturnsNoneand the final priority is at least MEDIUM. The instructions are in English, and the reason is asked for in the operator's language. Howmistralcopes with Bulgarian we did not measure — try it on your own examples (step 10).The service
A small FastAPI service puts it all together: it takes an event, computes the floor, asks the model, takes the higher value and stores it. It listens only on
127.0.0.1; the key is long and random. Startup and shutdown of the resources are inlifespan— the way the FastAPI documentation recommends.python · app.pyimport hmac import os from contextlib import asynccontextmanager from datetime import datetime, time, timezone from typing import Optional import asyncpg from fastapi import FastAPI, Header, HTTPException from pydantic import BaseModel, Field from rules import at_least, bump, floor_for, outside_hours from triage import ask_model DB_DSN = os.environ["DB_DSN"] # postgresql://<user>:<password>@localhost/alarms API_KEY = os.environ["API_KEY"] # a long random string @asynccontextmanager async def lifespan(app: FastAPI): app.state.pool = await asyncpg.create_pool(DB_DSN, min_size=1, max_size=5) yield await app.state.pool.close() app = FastAPI(title="Alarm triage", lifespan=lifespan) def check_key(key: Optional[str]) -> None: if not key or not hmac.compare_digest(key, API_KEY): raise HTTPException(status_code=401, detail="bad key") class EventIn(BaseModel): site_ref: str = Field(min_length=1, max_length=64) event_code: str = Field(min_length=1, max_length=8) qualifier: Optional[str] = Field(default=None, max_length=1) zone: Optional[str] = Field(default=None, max_length=64) device_type: Optional[str] = Field(default=None, max_length=64) source: str = Field(default="test", max_length=32) occurred_at: Optional[datetime] = None class AckIn(BaseModel): operator: str = Field(min_length=1, max_length=64) @app.post("/events") async def add_event(ev: EventIn, x_api_key: Optional[str] = Header(default=None)): check_key(x_api_key) when = ev.occurred_at or datetime.now(timezone.utc) if when.tzinfo is None: when = when.replace(tzinfo=timezone.utc) async with app.state.pool.acquire() as con: site = await con.fetchrow( "SELECT tz, open_time, close_time FROM sites WHERE site_ref = $1", ev.site_ref) recent = await con.fetchval( "SELECT count(*) FROM alarm_events " "WHERE site_ref = $1 AND received_at > now() - interval '15 minutes'", ev.site_ref) tz = site["tz"] if site else "Europe/Sofia" opens = site["open_time"] if site else time(8, 0) closes = site["close_time"] if site else time(20, 0) # 1) rules first: they set the lowest allowed priority floor = floor_for(ev.event_code) after_hours = outside_hours(when, tz, opens, closes) if after_hours and ev.event_code != "602": # 602 = routine test report floor = bump(floor) # 2) the model may only raise the priority, never lower it ctx = { "event_code": ev.event_code, "qualifier": ev.qualifier, "zone": ev.zone, "device_type": ev.device_type, "outside_business_hours": after_hours, "events_from_this_site_last_15_min": recent, } ai = await ask_model(ctx) model_pri = ai["priority"] if ai else None final = at_least(floor, model_pri) if model_pri else at_least(floor, "MEDIUM") row_id = await con.fetchval( "INSERT INTO alarm_events (occurred_at, site_ref, source, event_code, qualifier, " "zone, device_type, rule_floor, model_pri, priority, ai_reason) " "VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11) RETURNING id", when, ev.site_ref, ev.source, ev.event_code, ev.qualifier, ev.zone, ev.device_type, floor, model_pri, final, ai["reason"] if ai else None) return {"id": row_id, "priority": final, "rule_floor": floor, "model_priority": model_pri, "reason": ai["reason"] if ai else None, "model_available": ai is not None} @app.get("/events/open") async def open_events(x_api_key: Optional[str] = Header(default=None)): check_key(x_api_key) async with app.state.pool.acquire() as con: rows = await con.fetch( "SELECT id, received_at, site_ref, event_code, priority, ai_reason " "FROM alarm_events WHERE status = 'new' " "ORDER BY CASE priority WHEN 'CRITICAL' THEN 1 WHEN 'HIGH' THEN 2 " "WHEN 'MEDIUM' THEN 3 ELSE 4 END, received_at DESC LIMIT 100") return [dict(r) for r in rows] @app.post("/events/{event_id}/ack") async def ack(event_id: int, body: AckIn, x_api_key: Optional[str] = Header(default=None)): check_key(x_api_key) async with app.state.pool.acquire() as con: n = await con.execute( "UPDATE alarm_events SET status='acknowledged', handled_by=$2, handled_at=now() " "WHERE id=$1 AND status='new'", event_id, body.operator) if n != "UPDATE 1": raise HTTPException(status_code=404, detail="not found or already handled") return {"ok": True}bashpython3 -m venv .venv && . .venv/bin/activate pip install fastapi "uvicorn[standard]" asyncpg httpx pydantic psql "postgresql://<user>:<password>@localhost/alarms" -f schema.sql export DB_DSN="postgresql://<user>:<password>@localhost/alarms" export API_KEY="$(openssl rand -hex 32)" uvicorn app:app --host 127.0.0.1 --port 8001First create an empty database
alarmsand a user in your usual way. Replace the placeholders in angle brackets with your own values.Try it with invented events
From the same terminal send four invented events: a burglary alarm, a low battery, a periodic test and an unknown code.
bashfor body in \ '{"site_ref":"site-001","event_code":"130","zone":"north entrance","device_type":"motion detector"}' \ '{"site_ref":"site-001","event_code":"384","device_type":"door sensor"}' \ '{"site_ref":"site-002","event_code":"602"}' \ '{"site_ref":"site-002","event_code":"999"}' do curl -s -X POST http://127.0.0.1:8001/events \ -H "X-API-Key: $API_KEY" -H "Content-Type: application/json" -d "$body" echo doneFor each event you expect JSON with
priority,rule_floor,model_priority,reasonandmodel_available. The priority is never belowrule_floor. Stop Ollama and repeat:model_availablebecomesfalseand the priority does not fall below MEDIUM. What exactly the model will suggest we do not promise — we have not run it.n8n: notifying a human
n8n takes no decisions; it only carries the message to the human. The workflow:
- a Webhook node (or a schedule) receives an event from your source;
- an HTTP Request node sends it with POST to
/events, with the key as a credential (not in the text of the workflow); - an If node: if
priorityis HIGH or CRITICAL, continue; - a message to the duty operator (email or chat) that starts with the word "SUGGESTION" and contains the priority, the reason and the event number.
If n8n runs in a container (lesson 04-01),
localhostis the container itself: put the service in the same Compose network and use its name. The operator confirms withPOST /events/{id}/ack.The human decides
Who What it does Rules set the lowest priority; they do not get confused or tired Model suggests a priority and a short reason; it may only raise it Human decides whether to call, send a patrol or alert an authority ✅What we do not doWe do not automatically call the police, a guard or a customer, and we do not close an event without a human. The model gives a recommendation; the action has a real effect and so a human approves it.How often it is wrong
Do not trust a feeling. Measure.
- Collect 30–50 of your own past events (no names) and feed them to the service.
- Have two people independently say what the correct priority was.
- Count the most important thing: how many times the final priority was lower than the correct one. Those are the misses — and they cost the most.
- Repeat after every change of model, rules or prompt; do not trust a single number.
Security — the minimum
- The key is long and random, not in Git, and in n8n it sits as a credential.
- The service listens only on
127.0.0.1; if you need access from outside, put it behind a reverse proxy with HTTPS. - There are no names, addresses or frames in the events — only internal numbers.
- You back up the database and keep the retention period agreed with the lawyer.
- The rules and the model are under version control: you know what was running on the day of the event.
04Check
- You know by which route events leave your system and whether you have access to it.
rules.pyreturns MEDIUM for an unknown code and HIGH for 130.- An event sent while Ollama is stopped gets a priority of at least MEDIUM.
- Nobody is called automatically; the message to the operator is only a suggestion.
- You have at least 30 examples of your own and you count the misses.
Quiz
1. Why do the rules come before the model?
2. What happens if Ollama is down?
3. Where is the Enterprise API documentation?
4. Who decides whether to call a guard or the police?
05What's next
06Sources
- Ajax: connecting the intrusion alarm to monitoring software — routes, protocols, Translator, Cloud Signaling, direct connection.
- Ajax: Enterprise API — who it is for and how access is requested.
- Ajax: system integrations — which integrations are publicly described.
- Ollama: mistral — size, context, version 0.3 🔒 local.
- Ollama: chat API — the
formatparameter (JSON or schema) andoptions🔒 local. - FastAPI: lifespan — startup and shutdown of resources.
- PostgreSQL: documentation — the current version, 18.