Skip to main content

Getting connected

1. Get the current endpoint​

Current state (2026-10-29): wss:// comes on with the next deploy. The TCP server's wsGatewayWss flag is now true for dev, but not yet deployed, so the dev gateway is still plain ws://<ingest-host-elastic-ip>:8090/ws until then. The rest of this section describes the wss:// setup. Either way, the WsGatewayUrl stack output below always prints the URL that is live.

At that deploy, the plain ws:// address stops working at once (the port then admits only CloudFront). Every client, the mobile app included, has to move to the wss:// URL in the same release. The URL is a new *.cloudfront.net name, known only once the deploy prints it.

The deployed gateway is reached over wss:// through a CloudFront distribution, which terminates TLS with AWS's *.cloudfront.net certificate (no custom domain yet). The connection URL is:

wss://<ws-gateway-host>/ws

where <ws-gateway-host> is the distribution's dxxxxxxxxxxxxx.cloudfront.net name. It isn't published here because the gateway has no client authentication yet. Ask whoever manages the infrastructure for it, or, with AWS CLI access, read the cse-tcp-be-dev-ws-gateway stack's WsGatewayUrl output (see the "Dev-tier pipeline" section of Infrastructure):

aws cloudformation describe-stacks --stack-name cse-tcp-be-dev-ws-gateway --region us-east-1 \
--query "Stacks[0].Outputs[?OutputKey=='WsGatewayUrl'].OutputValue" --output text

The address is stable across redeploys, restarts and host replacement. It changes only if the CloudFront distribution is deleted and recreated (for example a cdk destroy of the ws-gateway stack).

Use wss:// only: the edge rejects plain ws://, and the gateway's port on the host's IP is closed to everything except CloudFront. A local npm run dev gateway is unchanged and still plain ws://<lan-ip>:8090/ws.

TLS protects the connection between the client and CloudFront. Authenticate the connection with a realtime ticket next: see Authentication.

Check the endpoint before writing code​

Replace <ws-gateway-host> with the host from WsGatewayUrl.

  1. Health. This should print ok (HTTP 200):
    curl -s https://<ws-gateway-host>/healthz
  2. From a browser. Open your frontend (its origin must already be on the allowlist, see step 2 below), open the developer console (F12) and paste:
    const ws = new WebSocket("wss://<ws-gateway-host>/ws");
    ws.onopen = () => { console.log("connected"); ws.send(JSON.stringify({ type: "watch", deviceKey: "<device id>" })); };
    ws.onmessage = (e) => console.log("<-", e.data.slice(0, 300));
    ws.onclose = (e) => console.log("closed", e.code);
    You should see connected, then a watch_ack and telemetry. If it closes straight away with code 1006, your page's origin is not on the allowlist. The gateway logs that as websocket upgrade failed ... origin not allowed.
  3. From a terminal, using the repo's reference client (see Reference implementation):
    cd server
    WS_URL=wss://<ws-gateway-host>/ws DEVICE_KEY=<device id> WATCH=1 DURATION=30s go run ./cmd/ws-test-client

2. Get your origin whitelisted (web only)​

The gateway checks the WebSocket handshake's Origin header against an explicit allowlist (ALLOWED_ORIGINS, comma-separated scheme://host[:port] entries) and rejects every browser connection whose origin isn't on it — there is no open wildcard. Ask the infra owner to add your dev, staging and prod origins before you start. They live per environment in the TCP server's cdk/cdk.json:

"allowedOrigins": {
"dev": "http://localhost:5173,https://console-dev.example.com",
"staging": "https://console-staging.example.com",
"prod": "https://console.example.com"
}

An entry may wildcard one whole leftmost label (https://*.console.example.com), never a shared host such as *.vercel.app. The web console's local dev server, http://localhost:5173, is on the dev list.

Native apps (Flutter, or any non-browser WebSocket client) typically send no Origin header at all — the gateway's origin check passes anything with an absent origin (real browsers always set one, so this can't be used to bypass the check from an actual browser context). In practice: this check protects web clients, not the API itself — see Known gaps.

3. Connect and watch a device​

// → client sends
{"type": "watch", "deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7"}

// ← server replies
{"type": "watch_ack", "deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "ok": true, "model": "Yorker", "registersVersion": "3f9a1c4e2b7d0a55"}

// ← back to back with no unnecessary delay:
{"type": "telemetry", "deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "record": {"deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "model": "Yorker", "cadence": "watched", "readings": { /* see "The telemetry record shape" */ }, ...}}
{"type": "presence", "deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "lastSeen": "2026-08-24T06:53:43Z"}

// ← then, while you keep watching, every ~30s:
{"type": "telemetry", "deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "record": { ... }}
{"type": "presence", "deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "lastSeen": "..."}

deviceKey in every reply is the server's canonical, lowercase spelling — see Identifiers are normalised before keying any client state on it.

A watch can be refused​

watch_ack comes back with ok:false and a code when the device may not be watched at all. Check ok — do not assume a watch_ack means the stream started. A refused watch opens nothing and sends nothing after this; a client that ignores ok waits forever for a reading that is never coming.

{"type": "watch_ack", "deviceKey": "7c9e6679-7425-40de-944b-e07fc1f90ae7", "ok": false,
"code": "DEVICE_NOT_FOUND", "error": "no such device; register it from the app first"}
codeMeaningWhat to show
DEVICE_NOT_FOUNDNo such device — never registered, or deletedOffer registration
DEVICE_REVOKEDAn operator took it out of service"This device is no longer in service" — registering again will not help

Only these two are refused; the gateway allows exactly what tcpserver will serve. In particular a device in pending_connection ("waiting for device") is watchable, so a client can sit on that screen and see it come alive the moment the hardware first connects. A device that is simply offline is not refused either — that is not an error; show it from how old presence's lastSeen is (see presence has no status).

If the gateway has no device database configured (a supported local-dev mode) or the lookup itself fails, the watch is allowed rather than refused: a database blip must not make a working fleet unwatchable.

Every watch gets a snapshot, regardless of whether anyone else was already watching that device. ws-gateway asks tcpserver for an out-of-band telemetry pull; if the device's last reading is already current for its active cadence, tcpserver skips the device entirely and the gateway replays the reading it already holds, so you get an answer either way. So you typically get telemetry and presence a few seconds after watch_ack (however long one telemetry read takes over the device's link), not up to the device's 5-minute idle cadence later.

This is a per-client guarantee, not a per-device one — it does not depend on your connection happening to be that device's only watcher. (It used to, which broke browser refreshes: the refreshed page's new WebSocket routinely watches before the server has finished processing the old socket's close, so the device still had a watcher and the new connection got nothing but watch_ack.)

If ws-gateway already has a recent reading for the device — which is exactly the page-refresh case — it replays that immediately after watch_ack rather than making you wait on the device at all, with the freshly-pulled record arriving right behind it. A reading older than about a minute is not replayed: a device silent that long is offline, not live with a stale value.

watch_ack carries model and registersVersion whenever the gateway knows the model: from the last telemetry record it relayed for the device, or else from the device's stored record. They are empty only for a device that has never connected (or a gateway running without a database). In that case the next telemetry message carries the model. Before 2026-10-06 the first watch of a device on a gateway always acked without a model, because only relayed telemetry was consulted. Use them to decide whether you need the register catalog at all; see Getting the register catalog.

all_registers is the server's own authoritative register list for this specific device's detected model, sourced from the same static, embedded protocol data tcpserver validates writes against — use it instead of hardcoding or copying a register name from another model's reference page. Sending a write for a register that doesn't appear in your device's own all_registers response will always be rejected (see Writing to a device).

Multiple clients watching the same device still share one upstream subscription and one raised cadence — that part is refcounted per device, and the device only reverts to its slow default cadence once the last watcher leaves. What is deliberately not refcounted is the snapshot: each new watcher gets its own watch_ack and telemetry. Pull requests are throttled per device (a couple of seconds), so a crowd opening the same device at once doesn't turn into a crowd of Modbus round trips — clients arriving inside that window are served from the reading the pull already in flight produces, or from the cached one.

If this gateway process has no recent reading for that device (e.g. it just restarted) and the device either isn't reachable or tcpserver decides its last reading is still current, you get nothing after watch_ack until the next scheduled telemetry record — at most one watched interval (~30s) for a connected device. presence still arrives on every ~30s heartbeat.