Skip to main content

Server behavior (server/)

cmd/tcpserver, per connection:

  1. Ask who it is — AT+DTUPN?, answered by the DTU itself with no Modbus profile needed, then one read-only database lookup that returns what is already remembered about that logger (its model and Modbus batch limit).
  2. Resolve the Modbus profile: TELEMETRY_MODEL env var (forced, still health-checked) → the remembered model (health-checked, never trusted blindly) → fresh detection. A profile is confirmed only by reading the inverter serial back with it: under the wrong register map the serial register decodes to non-text or to a serial that isn't the bound one. A plausible probe value alone isn't proof — real hardware returned an impossible ~1976V for the wrong profile, and an idle Aotai passes the IP20 probe outright (its register is unitless). See Profile confirmation. When no Modbus profile confirms and one got no usable answer, the server then asks the ASCII rating query F: a rating reply identifies an IP20 3K6/5K, which speaks text commands and ignores Modbus frames.
  3. Read the inverter's serial from the profile's identity_register and resolve the device with both identifiers — this is what verifies the logger/inverter pairing. See Connect flow.
  4. Heartbeat every PollInterval (30s), server-driven — the device never initiates anything. A failed heartbeat closes the connection; the device's own firmware reconnects.
  5. Telemetry only when it is due: every DEFAULT_TELEMETRY_INTERVAL (5 min) normally, every WATCHED_TELEMETRY_INTERVAL (30s) while a ws-gateway client is watching the device, and never for a connection that is not a registered device. Requests are batched via modbus.CoalesceRegisters, capped at the device's own batch limit (below). Each cycle is logged as one "telemetry snapshot" JSON object keyed by register address and name (some specs have duplicate names at different addresses, and some have duplicate addresses carrying different model-variant names — see the Aotai Hybrid reference for an example), and published to NATS. An IP20 3K6/5K has no batches: each distinct text query is sent once per cycle (about 15, ~9 s), and its batch limit is fixed at 1 without a search.

The batch size cap is measured on the real device (DiscoverMaxBatchQuantity, a binary search over 1..125, ~7 round trips) rather than assumed at the protocol's 125-register maximum: blindly batching to 125 once silently dropped 338 of 353 registers on the IP20 device. It is measured once and remembered in devices.max_batch_quantity, so later connections skip the search. See DiscoverMaxBatchQuantity's caveat before treating a measured value as a hardware property: the original evidence predates the frame-reassembly fix and may have been read-path timing rather than a device limit.

For the exact request/response validation performed on every round trip (including how a late/stale response is caught and discarded instead of being silently misattributed), see Connection lifecycle.

Binaries and configuration​

Every binary lives under server/cmd/ and is configured by environment variables only — none takes command-line flags except deviceadmin's subcommands. All of them read LOG_LEVEL (debug, info, warn, error; default info) and log structured JSON to stdout.

Database access uses one shared env shape (internal/pgconn.DSNFromEnv): either POSTGRES_DSN, or all of POSTGRES_HOST/POSTGRES_DB/ POSTGRES_USER/POSTGRES_PASSWORD plus optional POSTGRES_PORT (default 5432) and POSTGRES_SSLMODE (default disable — database and consumers share one private network). Deployed tasks use the discrete form so the password is injected by ECS from the cse-tcp-be-dev-telemetry-db-credentials Secrets Manager secret at container start and never appears in a task definition.

BinaryRoleEnvironment (default)
tcpserverDevice-facing ingest: accepts DTU connections, resolves identity, heartbeats, polls, executes writes/reads, publishes telemetry and presence. Runs schema migrations on startup.DEVICE_PORT (9000), NATS_URL (nats://127.0.0.1:4222), TELEMETRY_MODEL (unset = detect), MODBUS_TRANSPORT (rtu), MAX_CONCURRENT_CONNECTIONS (1000), DEFAULT_TELEMETRY_INTERVAL (5m), WATCHED_TELEMETRY_INTERVAL (30s), POSTGRES_* (optional — see below), POWER_CONTROL_ENABLED (unset = off: a blocked plant's shutdown/start is queued, never sent; see Plant block)
ws-gatewayWebSocket API for web/mobile clients (/ws, health at /healthz). Registration, watch, writes, register catalog, device list, Activity Trail, device deletion, Analytics (get_analytics) and Historical Data (get_param_catalog, get_param_history; see Historical Data). Never runs migrations.WS_GATEWAY_PORT (8090), NATS_URL, ALLOWED_ORIGINS (empty = every browser origin rejected), CLIENT_ADDR_HEADER (optional; a header to log as the client address instead of the TCP peer, set to CloudFront-Viewer-Address when deployed behind CloudFront; only safe when the port is reachable solely through that proxy), POSTGRES_* (optional; without it registration, writes and deletion fail closed), ANALYTICS_CO2_KG_PER_KWH / ANALYTICS_CO2_KG_PER_TREE (optional Operation Statistics factors; defaults 0.784 and 21.77, an invalid value is logged and ignored), GROUP_MAX_INVERTERS (50; the per-plant inverter limit for combined data and for adding devices to a plant), GROUP_STALE_AFTER (90s) / GROUP_OFFLINE_AFTER (15m) (combined-watch member freshness), ANALYTICS_PARALLEL_DEDUPE (off stops counting paralleled IP20 sets once in plant analytics) — see Parallel inverters
persistence-workerDurable JetStream consumer: telemetry.> → telemetry table, activity.> → activity_events, alertscan.> → alerts_active/alert_history (publishing alertevt.> after each commit), and a second telemetry.> consumer (persistence-worker-param-history) → telemetry_params, the Historical Data parameter history, batched and independent of the raw write (see Historical Data). Also runs the Analytics energy rollup (telemetry_15m → energy_daily, every 5 minutes, one replica at a time under an advisory lock — see Analytics), the web console's fleet rollups (every 5 minutes), the push-notification sender (Android, iOS and browsers), and, when the HTTP server's bus is configured, its consumer (plant projection, access revocations, plant blocks, the notification projection), the power-intent wake sweeper and device.block-state.v1 relay, the sender of the pushes the HTTP server requests, and the plant eraser (see Plant deletion). Runs schema migrations on startup.POSTGRES_* (required — exits without it), NATS_URL, PUSH_ENABLED (optional), FCM_SERVICE_ACCOUNT_JSON / FCM_SERVICE_ACCOUNT_FILE (with push), WEB_CONSOLE_ORIGIN (optional; makes web push links absolute), HTTP_BUS_QUEUE_URL (optional; unset = bus consumer, plant eraser and HTTP-requested pushes off), TCP_EVENTS_TOPIC_ARN (optional; unset = deleted plants are erased but not reported, and dead push tokens are not reported back)
report-rendererAWS Lambda, not a long-running service: renders the HTTP server's reports (PDF, XLSX, PNG preview) from report.render.requested.v1 and answers report.render.status.v1. See Report renderer.POSTGRES_HOST/PORT/DB/USER, POSTGRES_SECRET_ID (secret name; the password is read at start), REPORTS_BUCKET, TCP_EVENTS_TOPIC_ARN, ANALYTICS_CO2_KG_PER_KWH (0.5), CHROMIUM_PATH
deviceadminOperator CLI: status, revoke, restore, delete --yes, history, history --since 30d, resume, keep-device, backfill-energy [--days N] --yes (rebuild Analytics' energy_daily for the last N plant-local days, default 4, max 120, fleet-wide; idempotent), backfill-params --yes (fill the Historical Data parameter history, telemetry_params, from the raw telemetry still held, the last 5 days, fleet-wide; insert-only, rows already there are kept, so safe to re-run; run once after the deploy that adds it, and only after persistence-worker or tcpserver from that build has started, since deviceadmin never applies migrations: before 0049–0053 have run it refuses with "no telemetry_params table yet"). Run as npm run device -- <cmd> <loggerId>, which loads the repo's .env; against the deployed database, use npm run device:aws -- <cmd> <device> instead (see Against the deployed dev database).POSTGRES_* (required), NATS_URL (optional; used to close the device's live session)
seed-analyticsDev only. Fills one device (by device id or logger id) with synthetic history (default 90 days, max 1100). Simulates one reading per 15 minutes, computes each plant-local day with the rollup's own ComputeDay, and writes energy_daily, for days before the logger's earliest real data. --full also writes every reading at the 5-minute cadence to raw telemetry (marked _seeded) and telemetry_params, and refreshes telemetry_15m over that range, so the Day chart and Historical Data parameters have data too (15-minute series up to 4 months back, parameters up to 90 days); it refuses a range where another logger has 15-minute history whose raw readings are gone, since a refresh would erase it. --overwrite --yes first deletes everything stored for the logger before its first real reading (the first unmarked raw reading, or --real-from), replacing earlier seeded history. Only the fields the unit's own recent readings carry are seeded. After --full --overwrite, run npm run device -- backfill-energy --yes to recompute the day real data starts on. Refuses a non-local database unless --allow-remote. Run as npm run seed:analytics -- <loggerId> [--days N] [--model M] [--full] [--overwrite --yes] [--real-from T].POSTGRES_* (required)
live-viewerDebug: prints telemetry.> (or one device's) and presence.> traffic to the terminal.NATS_URL, DEVICE_KEY (unset = every device; lowercased like every logger id)
probeDev tool that dials out to a device on your LAN and runs one detect → batch-discovery → telemetry cycle. No NATS, no database.TARGET_ADDR (required), MODBUS_TRANSPORT (tcp), TELEMETRY_MODEL
device-simDev QA tool: a simulated logger + Modbus inverter that dials the ingest port like a real DTU. See Simulated device. No database, no NATS.flags: -addr, -model, -serial, -logger, -set addr=value, -v
ws-test-clientScriptable WebSocket client for exercising ws-gateway.WS_URL (ws://127.0.0.1:8090/ws), DEVICE_KEY, WATCH=1, DURATION (30s), UNWATCH_BEFORE, SEND (newline-separated raw JSON messages)

An invalid DEVICE_PORT, MAX_CONCURRENT_CONNECTIONS or interval value is logged and replaced by its default rather than failing startup. An unknown TELEMETRY_MODEL is fatal, because a typo there would otherwise fail every connection's health check.

MAX_CONCURRENT_CONNECTIONS is admission control, not a connection limit: a slot is taken before Accept, so once the cap is reached new connections wait in the kernel's accept backlog instead of all starting profile detection at once during a reconnect storm.

Publishing to NATS​

Every decoded telemetry snapshot is published to telemetry.<deviceKey> on the TELEMETRY JetStream stream, and every liveness change to presence.<deviceKey> (plain core NATS, not persisted — see Messaging for why). Each session subscribes to command.<deviceKey> so cmd/ws-gateway can raise/lower its poll cadence while someone is watching, send register writes and reads, and so an operator can close it (disconnect / reresolve, see session-control commands).

Presence and telemetry are published only for registered devices. An unidentified connection's subject would be presence.<IP:port>, which no client can name, so publishing it would be traffic with no reader.

Set via NATS_URL (defaults to nats.DefaultURL, i.e. nats://127.0.0.1:4222 — the CDK stacks always set it explicitly to the NATS instance's private IP, see Infrastructure).

Hard requirement at startup, soft dependency after that. tcpserver's nats.Connect call uses nats.go's plain defaults (unlike cmd/ws-gateway, which sets MaxReconnects(-1)) and os.Exit(1)s if that initial connection fails, or if the TELEMETRY stream cannot be ensured — NATS being unreachable at tcpserver boot means the whole ingest process refuses to start, so no device can connect at all. Deploy order matters: NATS must be up before tcpserver starts (the CDK dev-tier pipeline's cross-stack dependency on NatsStack's private IP already enforces this at deploy time — see Infrastructure).

The two KV buckets are softer still: if WATCHED_DEVICES (reconnect recovery of the watched cadence) or DEVICE_SESSIONS (the one-session- per-device lease) cannot be set up, tcpserver logs a warning and runs without that protection rather than taking every device offline over it.

Once running, NATSConn/JS are used nil-safely everywhere they're touched and every Publish/Subscribe error is just logged, not fatal. So a NATS outage after startup degrades gracefully — device polling keeps running, telemetry/presence/command side-effects stop until NATS (and nats.go's own reconnect logic) recovers — it does not crash the process the way a startup failure does. A failed lease refresh is likewise logged and ignored: dropping healthy connections over a NATS blip would turn it into a fleet-wide reconnect storm.

Device registration and identity (database-backed)​

A device reports its own identity — when asked. It volunteers nothing: the DTU sends no frame at all before Modbus starts (confirmed against real hardware), so every exchange on the connection is one the server started.

Asked, it answers two things. AT+DTUPN? returns the logger's own part number, which is devices.logger_id — the logger fitted to the device now — and the value the app scans off the QR label. The device itself is keyed by devices.id, a UUID generated at registration (migration 0072): the deviceKey of every NATS subject and WebSocket message, and the key of all of its history. A Modbus read of the profile's declared identity_register returns the inverter's serial. Both were captured from a real unit — see Protocol messages's AT command reference.

Resolution runs against the devices table (migrations 0015_device_identity_sn, 0016_devices_inverter_sn_index, 0019_logger_id_case_index and 0031_device_identifier_case; 0014_device_registration introduced the IP-correlation scheme these replaced, and 0018 retired its indexes). The SQL lives in internal/storage/postgres/identity.go (Registrar), shared by tcpserver and ws-gateway so the rules exist in one place.

Registration. A mobile app scans the logger's QR-printed logger_id and sends {"type":"register","loggerId":"…","userId":"…","plantId":"…"} to cmd/ws-gateway.

inverterSn is accepted but optional, and normally omitted: the server reads the inverter's serial from the hardware on the device's first connection and records the pairing itself, so nobody has to find a second label on the inverter.

plantId is required: the HTTP Server plant the device is being added to, stored in devices.plant_id (migration 0032_devices_plant_id). The column is nullable because devices registered before it have no plant; an operator backfills those. It has no index, because get_devices filters on it only after the owner_user_id index has narrowed to one owner's devices. It is stored in canonical uppercase (internal/deviceid.PlantID, enforced by the devices_plant_id_chk constraint), matching the HTTP Server's ULIDs, because its DynamoDB keys are case-sensitive. It is a client-supplied grouping, not an authorization input: plant membership lives only in the HTTP Server's DynamoDB, and owner_user_id remains the ownership gate for write, get_devices and delete_device.

ws-gateway checks at startup that devices.plant_id exists and logs an error if it doesn't. It never runs migrations itself, so a failed or rolled-back 0032 leaves register, get_devices and delete_device failing until the schema catches up. Roll back ws-gateway before ever running 0032's down migration.

A constraint requiring every owned device to have a plant is written but staged in internal/storage/postgres/pending_migrations/, outside the auto-applied set. Moving it into migrations/ before the backfill is finished would stop telemetry being stored for every plant-less device, since even an unrelated update to such a row would violate it.

Backfilling plants for existing devices is an operator task. Nothing in this service knows which plant an existing device belongs to: that mapping is the HTTP Server's (PLANT#<id> / DEVICE#<serial> in its DynamoDB). Don't ask the app to re-register them instead, because a successful register closes the device's live connection and moves a device that isn't active back to pending_connection.

  1. Deploy (npm run deploy) so tcpserver applies 0032. Until step 3 is done, existing devices are missing from every single-plant get_devices and delete_device refuses them, so plan to backfill straight after.

  2. List what needs a plant — revoked devices included, since the staged constraint covers them:

    SELECT id, logger_id, inverter_sn, owner_user_id, status
    FROM devices
    WHERE owner_user_id IS NOT NULL AND plant_id IS NULL
    ORDER BY owner_user_id, logger_id;
  3. Set each one's plant, using the plant id exactly as the HTTP Server stores it (an uppercase ULID; devices_plant_id_chk rejects any other case). The plant_id IS NULL guard makes a rerun harmless:

    UPDATE devices SET plant_id = '<PLANT_ULID>', updated_at = now()
    WHERE id = '<device id>' AND plant_id IS NULL;
  4. When step 2's query returns no rows, activate the staged constraint by following pending_migrations/README.md.

For the deployed database, run these through the SSM tunnel (see Against the deployed dev database).

The logger is validated first, then the inverter. Either already being another account's rejects the request with the stable code NOT_AUTHORIZED, which names nothing of that account's, overwrites nothing, and creates no row at all. Either already being the caller's own device in a different plant rejects it with DEVICE_IN_ANOTHER_PLANT, carrying existingPlantId and existingDeviceKey so the app can send the user to that plant. Between the same owner's devices a logger is reusable, and where it reports being plugged in decides the outcome — see Reusing a logger on your own devices and Device identity.

The inverter check needs a serial, and when the caller supplied none it uses the one the hardware itself reported: every connection that could not be served records what it said it was plugged into, in logger_sightings. In the ordinary Add-device flow the dongle is powered and dialling in while the installer scans its QR code, so that evidence is seconds old — which is what lets a logger plugged into another account's inverter be refused at registration rather than accepted as a claim and refused later, on a connection nobody is watching, and lets a logger on the owner's own inverter be fitted to that device.

A sighting is evidence and never a binding: it decides what the registration does, but is never written into devices.inverter_sn. Only a connection that was actually served records a pairing. A logger that has never connected has no sighting, so its registration is accepted and any conflict is caught at connect instead.

The same unserved connection also reads the model's spec-code register once (Nexus model_code, register 32; Yorker protocol_id_code_b) with a 3 s limit, and keeps it in logger_sightings.model_code (migration 0148). Plant admission compares it: a plant that already has an inverter takes another only as a confirmed-parallel, identical Nexus (same model code and rated kW), so a logger nobody has registered yet has to be checked before it is ever polled. A failed read leaves it NULL, and a parallel add is refused as PARALLEL_SPEC_UNKNOWN until a later sighting reads it. A logger that has never connected has no sighting at all, so registering it into a plant that already has an inverter is refused. See Parallel inverters.

Both checks and the write run in one transaction, with the matched rows locked (SELECT … FOR UPDATE) and the partial unique index devices_inverter_sn_uidx (WHERE inverter_sn IS NOT NULL AND status <> 'revoked') as the real backstop — so two installers claiming one inverter seconds apart cannot both succeed. The row lands in status='pending_connection', which means only "claimed by a user, not yet seen on the wire": no network key, no TTL, nothing to expire. The same transaction cancels any disposal still pending for that logger (see disposal below): registering it is the unambiguous "I want this device back" signal.

A successful register is followed by a reresolve command on the logger's subject, so a device already connected unregistered drops and reconnects immediately and is served, instead of waiting for its next natural reconnect.

An existing device is changed with update_device (see Updating a device): a plant move is applied in one transaction that also moves its open alerts and records the move in both plants' Activity Trail and alert history; a logger change is recorded as pending and completes on connect (see "Logger swaps" below). The earlier bind_new_logger request was removed; it only queued rows in logger_bind_requests that nothing ever acted on, and migration 0085 dropped that table.

Connect flow​

Identity first. AT+DTUPN? is answered by the DTU itself and needs no Modbus profile, so asking who this is costs one round trip and then unlocks everything already known about the device.

TCP connect
│
├─ 1. LOGGER Session.ReadLoggerID() → AT+DTUPN?
│ plain text; no profile required
│ → "I30000252761006466" → lowercased → "i3000…"
│ (skipped entirely when no device database is configured)
│
├─ 2. LOOK UP Registrar.LookupForConnect(logger) — READ-ONLY
│ the device this logger is fitted to (devices.logger_id),
│ else the device waiting for it in a pending swap;
│ ONE database round trip, returns:
│ • remembered model → skips DetectProfile
│ • remembered max_batch_quantity → skips the binary search
│
├─ 3. PROFILE TELEMETRY_MODEL set? → health-check it
│ remembered model + loaded? → health-check it (retried
│ on no answer or a desynchronised stream; a dead link
│ closes, never re-detects),
│ then confirm it reads the bound serial
│ otherwise / answered implausibly → detect, confirmed by serial
│
├─ 4. INVERTER Modbus read of identity_register (model-specific,
│ which is why it cannot come earlier) → "Y24C16070610"
│
├─ 5. RESOLVE Registrar.ResolveOnConnect(logger, serial)
│ │ THIS is what verifies the pairing; step 2 could not.
│ │
│ ├─ serial bound to another → inverter_taken REFUSED, except:
│ │ · row is a never-connected claim, the device is the
│ │ registrant's (same owner, or their Business's idle
│ │ stock with no owner) and in the same plant
│ │ → logger_replaced, served AS THAT DEVICE; claim removed
│ │ · row has a serial, the device is the SAME owner's and has
│ │ no logger (logger plugged back into its old inverter)
│ │ → logger_replaced, served AS THAT DEVICE; the row's
│ │ device is deactivated
│ │ · row has no serial, the device is someone else's and has
│ │ no logger → its inverter is released to this row:
│ │ claimed_pending, served
│ ├─ serial unreadable → unverified served
│ ├─ row's serial DIFFERS → logger_moved REFUSED
│ ├─ row has no serial yet → claimed_pending served (pairing recorded)
│ ├─ row's serial matches → bound served (the reconnect)
│ ├─ no row; a device awaits
│ │ this logger (pending swap):
│ │ its serial matches → logger_replaced served AS THAT DEVICE
│ │ (devices.logger_id := this logger)
│ │ differs / unreadable → logger_swap_refused REFUSED (stays pending)
│ └─ no row for this logger → unknown not served
│ │
│ └─ every not-served outcome
│ records the serial it reported
│ in logger_sightings, so the next
│ `register` for that logger can
│ refuse immediately
│
├─ 6. DISPOSE? unknown only: was this logger erased? → overwrite its
│ WiFi association and close (see below)
│
├─ 7. LEASE served outcomes only: AcquireSessionLease() in the
│ DEVICE_SESSIONS KV — before any command subscription
│
├─ 8. SUBSCRIBE command.<deviceKey> (the device id); an `unknown` logger
│ additionally listens on command.<loggerId> for its own
│ registration
│
└─ 9. BATCH LIMIT served only: remembered, or measured once and stored

Outcomes are checked in the order shown: a serial owned by another logger is refused even when this logger's row has no serial of its own yet.

Logger swaps. A device's key is devices.id, and every history table references it; devices.logger_id is only the logger fitted now. When the logger is replaced (update_device), the swap waits in pending_logger_id (unique while set) for at most 7 days, and completes in ResolveOnConnect when the new logger reports the device's own inverter serial (so only a device whose serial the hardware has already reported, sn_verification = 'verified', can change logger) — in one transaction that rewrites devices.logger_id to the new logger, clears the cached max_batch_quantity (it is the logger's, not the device's), and records the swap in the Activity Trail and alert history. Nothing else moves: no history row names the device by its logger. The trigger devices_track_logger marks the old logger's loggers row deleted and adds an active one for the new logger. A still-connected old logger then loses the device's session lease (keyed by device id) to the new one and closes; if it connects again it resolves to nothing, and it is free to be registered as a new device. Deleting a swapped device disposes of its current logger only: the deletion audit record is keyed by that logger's hash.

Before migration 0072 a swap kept logger_id as the device's permanent key and stored the new logger in current_logger_id (0059-0061); 0072 folded each swapped device's current logger into logger_id and dropped that column.

postgres.Refused(outcome) is the single place that says which outcomes must not be served, so a future refusal cannot be handled at one call site and missed at another.

:::warning Step 2 must not write It runs before the pairing has been checked — it has to, because the cached model it returns is what makes the serial readable at all. A connection that is about to be refused must not have already flipped the device to active or stamped its address on the way there.

An earlier version reused ResolveOnConnect here with an empty serial and did exactly that. LookupForConnect is strictly read-only. :::

A missing serial (a read that failed, or an IP20 3K6/5K whose factory never programmed one) costs verification of the pairing, not service: the device resolves as unverified and is served. The IP20 3K6/5K answers its serial query with a placeholder (27 repeated 2s on the bench unit), which modbus.PlaceholderSerial treats as no serial, so it is never stored or matched; a serial given at registration is kept but never verified. See IP20 3K6/5K.

Unidentified connections​

A connection that did not answer AT+DTUPN, resolved unknown, was refused, or hit a database error is left unidentified: it carries deviceKey(conn) (IP:port) and is never polled — the connection is held open with heartbeats only, and no batch-limit discovery, presence or telemetry happens. Nothing is guessed, and no row is invented; creating one would mean inventing a device for a logger nobody owns, which no account can see and whose readings no one could ever be attributed.

Polling such a connection would produce readings nobody can receive: they carry the unstable IP:port key, so persistence-worker discards them on registered=false and no ws-gateway client can subscribe to a subject it cannot name. Each cycle is a full Modbus request run over a WiFi-to-serial bridge, so this is spent on the device and its serial bus for nothing. It was most visible after revoking a device: it reconnected and kept being polled, indefinitely, for nobody.

The heartbeat (AT+HTBT) continues, because it is the DTU firmware's own mandated keep-alive — dropping it would close the connection and put the device into a reconnect loop, which costs more than the polling it saves. Closing instead of heartbeating is the more expensive option, not the cheaper one: a reconnect is profile detection plus AT+DTUPN? plus a serial read, measured at ~950ms against real hardware, versus ~33ms for a heartbeat.

A connection whose logger is unclaimed (the unknown outcome), or that was refused as logger_moved / inverter_taken, additionally subscribes to command.<loggerId>, and honours only reresolve/disconnect there, so that registering it from the app can reach it — see session-control commands. Registering resolves those two refusals when the logger and inverter are the same owner's (Reusing a logger).

Disposal. One thing does happen to an unidentified connection: if its logger belongs to a device that was erased, its WiFi association is overwritten with a network that does not exist (AT+WFLKAP=, see Protocol messages), and the connection is dropped rather than served. Erasing a device removes every record of it but leaves the hardware dialling in forever, so disposal is completed here, on whichever connection the logger next makes — which may be weeks after the erasure, since a device that is powered off cannot be told anything.

Checked only for the unknown outcome, so a registered device never pays for the lookup, and bounded by an attempt limit (postgres.MaxDisposeAttempts, 3): a logger that keeps returning after three disposals means the command has stopped doing what it was measured to do, and that surfaces as a log line instead of a fleet-wide loop. npm run device -- keep-device <loggerId> cancels a pending disposal; so does registering the logger again.

AT+RESTORE was the original choice and turned out to only reboot the device — back in 1.9 seconds with every setting intact. See the README's disposal section for what each candidate command actually did.

Registration cannot take over a claimed device​

A logger id is printed on a label anyone with physical — or photographic — access can read. If registering that id could reassign owner_user_id, knowing the label would be enough to take another customer's device.

So a logger that already has an owner is refused with NOT_AUTHORIZED unless the request comes from that current owner — whether or not the device has connected yet. The pending window, between an installer registering a device and its first connection, is when the label is most exposed, so it gets the same protection as a bound, reporting device. A row with no owner (unclaimed) can still be registered, but only while it is not yet paired with an inverter: an ownerless row that is already paired is a reporting device with history, and is refused like any other bound one.

The same rule is repeated inside the write itself, not only in the check before it: two users registering the same brand-new logger at the same moment both find no row, and without that guard whichever wrote second would end up owning it. Exactly one of them succeeds.

For the owner, re-registering is idempotent only — a retry, never a move:

  • a live, active device is never pushed back to pending_connection;
  • a plantId different from the device's current plant is refused (ErrLoggerInAnotherPlant, wire code DEVICE_IN_ANOTHER_PLANT with that plant in existingPlantId) and the device is left where it is. Registration used to move the device instead, so "adding" an in-use logger as a new device silently took it out of its original plant. Moving between plants is not a registration;
  • naming a different inverter in inverterSn is refused (LOGGER_ALREADY_BOUND); a typed serial never moves a logger.
  • if the logger's most recent logger_sightings row reports a different inverter than the one it is bound to, the logger has been moved, and the registration is not a retry: the logger becomes the device of the inverter it is on now, and the device it left is deactivated (see Reusing a logger). A sighting only counts if it is newer than the device's last_seen_at — sightings are never cleared, so an older one is history, not evidence. The plant rule above applies only while the logger has not moved.

A revoked device is refused for everyone, its former owner included, with DEVICE_REVOKED. Revoking is an operator decision that keeps the device's history so it can be restored; if registration could lift it, any user could undo it — and a different user would inherit the previous owner's telemetry and lifetime totals with the row. The way back is an operator: restore to return it, or delete to erase it so the hardware registers as a new device.

What a reconnect costs​

Devices hold long-lived connections, so every deploy reconnects them and the connect path's cost is multiplied by the fleet.

BeforeNow
Profile detection1-2 round trips0 (remembered, health-checked)
Batch-limit discovery~7 (binary search 1..125)0 (remembered)
Device round trips~10-11~3
Database4 round trips, always a write2 reads (lookup, resolve), and no write when nothing changed

ResolveOnConnect is a single CTE: it reads the row, detects a conflicting binding, applies the update and reports what was there before — atomically, because the read and the UPDATE touch the same row in the same statement, so the UPDATE takes the lock itself.

Its UPDATE is skipped entirely when the device is already active, already has its model and pairing, and was seen within the last minute. That is the common case at fleet scale, which turns most reconnects into a pure read — the shape a read replica could serve.

Only the profile cache is self-correcting. A remembered model is health-checked and serial-confirmed before it is trusted; one that cannot read the bound serial is replaced by a profile that can. See Profile confirmation.

Profile confirmation​

The device's register-map key, COALESCE(devices.profile, devices.model) (since migration 0149 model holds the public name and profile the key where they differ; see IP20 3K6/5K), decides which register map every reading is decoded with and every write is addressed to, so replacing it wrongly is silent and harmful. On 2026-09-26 an Aotai on a flaky link (logger i30000252761006466) was relabelled IP20: one probe timeout triggered re-detection, the Aotai probe timed out again, and the IP20 probe accepted the idle Aotai's zero. The persistence-worker then wrote IP20 into devices.model from the next reading, and every later connection trusted it. The rules now are:

SituationOutcome
Remembered profile gets no answer, or the stream is out of step (a stray text line, a torn frame)Retried up to 3×. Still nothing → other profiles are tried, and one replaces it only if it reads the bound serial (a new inverter model may ignore the old probe register), or, for a remembered Modbus model, if the device answers the ASCII rating query F (an IP20 3K6/5K; no Modbus inverter answers it). Otherwise the connection is closed for the DTU to redial. Never replaced by a guess, since silence says nothing about the model.
Remembered profile answers and reads the bound serialKept. The serial read is reused for pairing, so this costs no extra round trip.
Remembered profile answers but cannot read the bound serialOther profiles are tried; one replaces it only if it reads the bound serial. Otherwise the remembered one stays (the logger has probably moved; pairing refuses it).
Remembered probe answered with an implausible valueFull detection.
Detection: a candidate reads the serialChosen.
Detection: nothing confirms and a candidate got no usable answer (timeout, reset, or a desynchronised stream)The ASCII rating query F is tried; a rating reply makes it an IP20 3K6/5K. Otherwise the connection is closed, no guess.
Detection, device already bound to an inverter: nothing confirms and no candidate read any serialConnection closed, no guess. A profile that cannot read a serial from a paired device is the wrong one.
Detection, bound device: a candidate reads a serial that is not the bound oneReturned. This is the right profile on a different inverter; pairing refuses the connection and records the sighting.
Detection, unbound device (first registration): every candidate answered, none confirmsFirst plausible, logged as unconfirmed and not remembered.

The DTU's stray AT+TBT:R001 line (2026-10-01, 10-02)​

The same logger was relabelled IP20 again on 2026-10-01 16:20 and 2026-10-02 03:49, this time with the 09-26 rules in place. devices.model stayed Aotai, because an unconfirmed guess is never remembered, while that connection's telemetry was decoded against the IP20 map for hours.

What the logs show: the DTU's reply to AT+DTUPN? is sometimes followed by a second line, AT+TBT:R001 (R001 is the firmware's "unrecognised command").

  • When it arrived in the same read as the reply, the whole text was taken as the part number and the connection ran unidentified (03:28, ~20 minutes).
  • When it arrived after the reply, it sat in the socket. The remembered Aotai probe read its first three bytes (AT+) as a Modbus header and failed on "function code" 0x54. That error was classed as the device answering wrongly, so detection ran from scratch: the Aotai candidate hit the same line, which the "a candidate got no answer" guard did not count because it was not a timeout, and the IP20 candidate's probe (unitless, any value passes) won. Its serial read failed (no printable ASCII), and it was served anyway.

Why the DTU sends it is not known. What the server does now does not depend on that:

LayerBehaviour
AT+DTUPN? replyOnly the first line is the part number.
AT replies (AT+DTUPN, AT+HTBT)Read by expected prefix: a complete line that is not the answer is skipped, within the same read deadline.
Modbus readsA frame starting AT+ is a text line, not a frame (0x54 is not a function code). It is read through its LF and skipped, up to 3 lines and 64 bytes each, by content, not by waiting.
Any other desyncA transport error, like a timeout: retried, never a reason to re-detect, and it blocks guessing.
Bound device, nothing confirmsClosed rather than served (table above).

Every skipped line is logged at WARN as skipped a text line the DTU sent where a Modbus response was expected, with its text, hex and after_request_ms, the offset from the request it followed. That offset is the evidence for when the line arrives, and the way to learn whether it is ever late. A candidate that could not be tried is logged at WARN too (it was Debug, which is why the 10-02 record lacked it).

Only ResolveOnConnect changes a stored model, and only on a connection that read the serial matching the binding. Without a serial it just fills a NULL. The persistence-worker writes model only when it is NULL. ws-gateway follows a model change seen in telemetry instead of keeping the first one.

The batch-limit cache is not. A stale limit makes batch reads fail and, if the cycle decodes nothing, closes the connection — but nothing clears devices.max_batch_quantity, so the next connection reuses the same value and fails the same way. Until that is fixed, recovering such a device means clearing the column by hand so the next connection re-measures.

:::danger One spelling per identifier, converted where it enters The DTU reports its own part number as I30000252761006466 while the same device's row, registered from the app's QR scan, holds i30000252761006466. Same 18 characters, one character of case apart — confirmed on the bench unit.

A plain WHERE logger_id = $1 against the device-reported value matched nothing, and every device silently resolved as unregistered. The first fix (migration 0019) made database lookups match on lower(logger_id) — but that protected only the database. NATS subjects are case-sensitive, so a client watching I3000… subscribed to telemetry.I3000… while the device published to telemetry.i3000…, and got ok: true followed by nothing.

Now every identifier is converted once, where it enters (internal/deviceid): logger ids to lowercase, inverter serials to uppercase, surrounding whitespace trimmed, nothing else touched. The entry points are the WebSocket gateway (every client message), the TCP connect path (the DTU's AT+DTUPN reply and the Modbus serial read), the registrar that writes them, and live-viewer's DEVICE_KEY. Exact matching is then correct everywhere downstream — SQL, NATS subjects, the watch KV — including anywhere nobody thought to make case-insensitive.

Migration 0031 enforces it with CHECK constraints (devices_logger_id_lowercase, devices_inverter_sn_uppercase), added NOT VALID — enforced on every insert and update, with no scan of existing rows — because a failed migration would start tcpserver without its device database. Migration 0072 lowercased every stored logger_id (no longer a key anything references) and validated the logger-id constraint, so connect-path lookups now match logger_id exactly, through devices_logger_uidx.

During a deploy, the old ws-gateway can briefly outlive the new constraints (CDK deploys the ingest stack first), so a registration sent in uppercase in that window fails with REGISTRATION_FAILED — refused, never mis-stored, and fine on retry. :::

The refusal outcomes are the security property. A logger unplugged from its inverter and connected to a different one does not silently start reporting the wrong device's data — moving it legitimately goes through update_device, whose swap completes only when the new logger reports the device's own inverter serial. A refused connection is left completely unmodified; nothing is half-applied.

sn_verification moving from unverified to verified is self-verifying evidence the path ran: only ResolveOnConnect sets it, and only after the hardware itself reported the serial.

Telemetry flow and cadence​

Identity is resolved once per connection, not per telemetry message. A Modbus response carries register values and nothing else — no envelope, no header, nowhere to put a serial — so the serial is asked for explicitly at connect and never re-read on the polling loop.

Session is already resolved → no serial re-read per cycle
│
├─ every 30s: AT+HTBT, lease refresh, presence.<device id>
│
├─ when due: telemetry.<device id> ← the device, not the logger or serial
│ cadence "default" | "watched"
│
└─ cmd/persistence-worker
→ telemetry table, "default" records only

Polling and storing are paced separately. An unwatched device is polled every DEFAULT_TELEMETRY_INTERVAL and every record is labelled default. A watched device is polled every WATCHED_TELEMETRY_INTERVAL for the live view, and most of those records are labelled watched and not stored — but once per DEFAULT_TELEMETRY_INTERVAL one of them is labelled default instead. So stored history has the same 5-minute density whether or not anyone is looking, without an extra Modbus request. (They used to be the same thing, and a device being viewed in the app stored nothing for as long as it was open — 17h40m of unbroken polling that wrote zero rows.)

A watch_start also pulls a reading immediately, unless the last one is still current for the watched cadence, and never with a heartbeat older than 10s — a full telemetry cycle was measured at 19-26s on real hardware, long enough to outlast the DTU's ~30s watchdog if started late. The watched state is also written to the WATCHED_DEVICES KV bucket, so a device that reconnects while still being watched picks the fast cadence back up at once.

Writes and reads from ws-gateway (device_write, read_registers) are handed to the poll loop's goroutine — the only one allowed to touch the socket — and executed within about one round trip of arriving, not on the next 30s tick. One of each can be in flight per device; a second is refused as busy rather than queued. An IP20 3K6/5K's telemetry cycle is ~15 one-by-one text queries (about 9 s), most of a write's ~10 s budget, so for that model a waiting write or read is also run between two queries of the cycle (details); a Modbus cycle is a few batched reads and is not interrupted. A write reads the register's value before and after writing it (when the register is readable), because a function-16 write echoes only address and quantity, so the read-back is the only confirmation of the new value. Those values, the frame bytes, attempt count and duration are returned in the CommandResult that feeds the Activity Trail. A failed read-back never fails a write the device already acknowledged.

The inverter serial is a binding attribute, not a key, and so is the logger: devices.id is the devices primary key, every history table's foreign key and every NATS subject component, so neither a logger swap nor anything else about a device's hardware moves its data. A verified serial cannot change at all (trigger devices_freeze_verified_sn): a replaced inverter is a new device.

Telemetry from a connection whose registered is false is also discarded by Store.StoreTelemetry, as defence in depth — an unidentified device would otherwise accumulate rows under a key that could never be merged into the real device once someone registered it.

Why source IP is gone. Identity previously came from devices.pending_conn_key and devices.last_known_ip. Behind carrier NAT that permitted one pending registration per public address globally, and LookupByLastKnownIP could resolve a connection to a different tenant's device when two units shared an egress address — delivering one customer's Modbus writes to another customer's inverter. Migrations 0015–0018 replaced it; last_known_ip is still written as connection diagnostics only. See Device identity options.

Running without a device database​

If Config.Devices is nil (no POSTGRES_DSN/POSTGRES_HOST configured, or the startup connect/migration failed within its 30s timeout), tcpserver still starts, but no device is ever registered, so none is polled for telemetry. AT+DTUPN is not even asked; every connection runs full DetectProfile, gets the unstable IP:port identity, and is held open on heartbeats only. That is a deliberate choice — refusing to start would take every device offline — but it is not a "degraded but still ingesting" mode.

It is easy to miss. The only dedicated signal is one startup line: "no device database configured, running without device registration/reconnect matching" (Warn, no DSN) or "failed to connect to device database, running without device registration/reconnect matching" (Error, DSN set but unreachable or migration failed), plus device_store_configured: false on the "tcp server listening" line. After that, each connection logs only the generic "connection is not tied to a registered device, skipping batch-limit discovery and telemetry polling" — the same line an unregistered device produces, but without the "no registered device for this logger; register it from the app…" warning that names a logger id. This is exactly the failure a torn-down-and-redeployed dev environment hit in practice, indistinguishable from "the app just hasn't sent register yet" without checking the startup log.

If devices stays empty and telemetry never lands, check tcpserver's startup logs for those lines before assuming a client-side problem. ws-gateway fails more visibly: with no database it answers each register with "registration unavailable (device database not configured)" — see register_result codes.

Deleting or disabling a device​

Use revoke. It is what status = 'revoked''s enum value is for: the device stops being served, its history is kept, and restore undoes it.

npm run device -- revoke <device> # stop serving; keep everything
npm run device -- restore <device> # back to pending_connection
npm run device -- delete <device> --yes # permanent erasure + disposal

<device> is the device's id or the logger fitted to it now. A logger on more than one device row (a revoked device keeps its logger while the hardware is fitted elsewhere) is refused, naming the devices: pass the id. restore of a revoked device whose logger is now another live device's is refused too (devices_logger_uidx).

revoke, restore and delete all also close the device's live session over NATS (disconnect, or reresolve for restore), so the change takes effect within one poll cycle rather than whenever the device next reconnects — identity is resolved once per connection and nothing re-checks it mid-session. The DTU reconnects within seconds and picks up the new state. If NATS is unreachable the database change is still saved and applies on the device's next connection; the CLI says so.

Against the deployed dev database​

npm run device always uses the repo's .env: scripts/device.sh sources it after your shell environment, so its POSTGRES_* values override anything you export. To act on the deployed database, use npm run device:aws (scripts/device-aws.sh), which takes the same commands:

npm run device:aws -- status <device>
npm run device:aws -- delete <device> --yes
npm run device:aws -- keep-device <loggerId>

It never reads .env. If an SSM tunnel is already listening on localhost:15432 (cd cdk && npm run db:tunnel) it reuses it; if the port is free it opens one for the run (about 5 seconds) and closes it on exit, including on Ctrl+C or a failed command; if anything else holds the port (the local migtest-tsdb container uses 15432 too) it refuses without connecting. If the tunnel can't be opened (no running telemetry-db instance, no SSM access), it prints why, waits at most 30 seconds, and changes nothing. A POSTGRES_DSN exported in your shell is ignored, since it would otherwise override the tunnel address. The exit code is deviceadmin's. The password is read from the cse-tcp-be-dev-telemetry-db-credentials secret at runtime and never lands in a file. AWS_REGION (default us-east-1) and LOCAL_PORT (default 15432) override the defaults. It needs aws, jq, lsof and session-manager-plugin on PATH.

The equivalent by hand: open the tunnel in one terminal and run deviceadmin directly in another:

cd server && POSTGRES_HOST=localhost POSTGRES_PORT=15432 POSTGRES_DB=dev_telemetry_db POSTGRES_USER=postgres \
POSTGRES_PASSWORD="$(aws secretsmanager get-secret-value --region us-east-1 \
--secret-id cse-tcp-be-dev-telemetry-db-credentials --query SecretString --output text | jq -r .password)" \
go run ./cmd/deviceadmin status <device>

Replace status <device> with any other command. Always run status first: its owner_user_id, last_seen_at and last_known_ip tell you that you're on the database you meant. A device connected to AWS shows a public IP here; one on your LAN shows a 192.168.x.x address in your local database.

The deployed NATS is not reachable through this tunnel. deviceadmin falls back to nats://localhost:4222, so "sent disconnect" reaches your local broker, if one is running, not the deployed one. The database change is saved either way. The device's current session on the deployed tcpserver just keeps running until it next reconnects, and the change applies then. For delete, disposal of the logger happens on that reconnect too: run keep-device straight after if you want to keep the hardware.

A connection refused on localhost:15432 means the tunnel isn't running; no change was made.

A new logger refused because "this inverter is already bound to a different logger"​

The device the new logger was registered as stays pending_connection because another device still holds the inverter's serial. delete <the new logger> does not help: it erases the new logger's own device, never the holder. The refusal log line names the holder as held_by_device_id / held_by_logger_id (see the binding rules, B5). status also accepts an inverter serial:

npm run device:aws -- status <inverterSn>

It lists the devices holding the serial (or that released it, or were revoked with it) and the loggers seen reporting it while refused or unregistered, each with the device it is registered to. A connection that is served records nothing there, so that list's last= is the last refused or unregistered connection, not the logger's last connection. Times are UTC, to match the ingest logs. It then names the device to act on: revoke <held_by_device_id> frees the inverter and keeps the holder's history, and delete <held_by_device_id> --yes erases it. Unbinding its logger in the web console also frees it. The refused logger is served on its next connection; one that is still connected from before stays unregistered until it reconnects. Read-only, like status <device>. status tries the argument as a device id or logger id first, and as a serial only when it matches neither.

A restored device goes to pending_connection, not active: active means "seen on the wire". It becomes active on its next stored reading (a stored reading promotes any non-revoked status), or on its next connection.

Erasure (delete, or the app's delete_device → confirm_delete_device flow in ws-gateway, which requires a server-issued confirmation token) is one shared implementation, internal/erasure; deviceadmin is a thin CLI wrapper around it. In order:

  1. Begin — one transaction sets the device revoked, supersedes any earlier open disposal for the same logger, and opens a device_deletions audit row. A partial unique index (migrations 0029/0030) rejects a second concurrent erasure of the same logger.
  2. Close the live session (disconnect), so the ingest path is not still writing rows for a device being deleted.
  3. Delete telemetry in 30-day windows, each its own short transaction, then an unconditional sweep for any reading that arrived meanwhile.
  4. Finish — one transaction deletes daily_financials, tariff_rates, energy_daily, loggers, the remaining telemetry_params, activity_events, alert state and history, the logger_sightings of every logger the device has had (from loggers; for a logger a swap has since moved to another device, only a sighting naming this device's inverter serial — otherwise it describes that device), the continuous-aggregate rows (looked up from TimescaleDB's catalog, deleted after the raw readings), and the devices row, then closes the audit record keeping only a SHA-256 hash of the logger fitted at erasure time. The audit record holds the device id until then, which is what resume finds the device by.

An interrupted erasure is resumable (npm run device -- resume): the device is already out of service, so a half-erased device is an unfinished job, not a half-served device. The logger itself is disposed of on its next connection (see Disposal).

A plant deletion from the HTTP server uses the same deletes without taking the device away (erasure.EraseDeviceHistory): readings, parameter history, aggregates, energy and financial days, Activity Trail and alerts go; the devices row, its loggers, its logger_sightings and its command audit stay, the device is not revoked, no device_deletions record is opened, and the logger is not disposed of. The device keeps reporting as a free device (no plant, org or owner). See Plant deletion.

Deleting rows by hand does not do what it looks like:

ActionWhat actually happens
DELETE FROM devices aloneRefused. telemetry, telemetry_params, alert_history, activity_events, tariff_rates and daily_financials carry a foreign key to devices(id), with no ON DELETE CASCADE
Delete the telemetry, then the deviceSucceeds — but leaves the aggregates, Activity Trail and sightings behind, the live session keeps polling until the device reconnects, and any reading already in flight arrives for a row that no longer exists

A reading that arrives for a deleted device is discarded as a permanent failure, with an audit line naming the device, cadence, model and timestamp. It is not retried.

:::danger Deleting a device used to silently undo itself StoreTelemetry upserted the devices row before inserting a reading — a leftover from when identity was guessed from the network and first contact legitimately created the row. The effect was that a deleted device was recreated by the next reading, as unclaimed with no owner: it reappeared, kept recording, and had quietly lost the customer it belonged to.

It is an UPDATE now. A missing row is a permanent failure, not an invitation to create one. :::

Permanent versus transient write failures​

cmd/persistence-worker deliberately leaves a failed reading unacked so JetStream redelivers it once the database recovers. That is right for an outage and wrong for a reading that can never be written — a deleted device's row is not coming back, so it would be redelivered every 30 seconds indefinitely while each new poll added another one.

Failures are therefore classified. A small allowlist of SQLSTATEs is treated as permanent (foreign-key, not-null and check violations, invalid values, schema drift); those are logged and Term()d. Everything else stays retryable — misclassifying a transient failure discards a customer's reading, which is far worse than retrying one that will not succeed. The activity.> consumer uses the same split; an unparseable Activity Trail record is permanent too, since it would otherwise block every record behind it.

MaxDeliver (250, over two hours at a 30s ack wait) is applied to all four durable consumers (persistence-worker, persistence-worker-activity, persistence-worker-alerts and persistence-worker-param-history) and backstops the failures the classifier cannot recognise, so nothing can be redelivered forever whatever the cause. The worker creates these consumers itself and binds to them, so a restart resumes where it left off instead of replaying the streams — see Durable consumers are created explicitly. Both inserts are idempotent (ON CONFLICT DO NOTHING on (device_id, time) and (id, time)), so at-least-once redelivery never double-counts.

:::note Status is read at connect, and corrected by readings ResolveOnConnect runs once per connection and excludes only revoked; inactive and unclaimed resolve normally and are set back to active. A stored reading also promotes any non-revoked status to active, so a stale status self-corrects within one telemetry interval. Revoking a connected device relies on the disconnect command above to take effect immediately — a revoke done by hand in SQL does not send one, and the device keeps being served until it reconnects. :::

Database schema​

Migrations are embedded in the binaries (internal/storage/postgres/migrations/*.sql) and applied by golang-migrate when tcpserver or persistence-worker starts, under its advisory lock, so concurrent starts are safe. ws-gateway and deviceadmin never migrate.

MigrationsWhat they establish
0001TimescaleDB extension, device_status enum (unclaimed, pending_connection, active, inactive, revoked), devices (primary key logger_id until 0072, then id, owner, status, last_readings, lifetime totals), tariff_rates
0002–0004telemetry hypertable (1-day chunks, primary key (logger_id, time) until 0072, canonical generated columns), 5-day raw retention
0005–0007telemetry_daily continuous aggregate (hourly refresh, 4-month retention), daily_financials
0008–0011telemetry_monthly and telemetry_yearly aggregates, no retention
0012drops the redundant raw_readings column
0013ws_gateway_readonly role with SELECT on devices
0014, 0018IP-correlation registration columns/indexes, and their removal
0015–0016inverter_sn, sn_verification, unique devices_inverter_sn_uidx (non-revoked rows)
0017logger_bind_requests, one open request per (inverter_sn, requested_logger_id). Dropped by 0085: nothing wrote it after bind_new_logger was removed
0019devices_logger_id_lower_uidx — case-insensitive lookups, no two ids differing only by case
0020max_batch_quantity (1..125) — the connect-path cache
0021–0022device_deletions audit table and its disposal-attempt columns
0023logger_sightings — what an unserved logger reported it was plugged into
0024–0028activity_events (Activity Trail) as a 1-day-chunk hypertable with 730-day retention; initiated_by renamed user_id; per-device index on lower(logger_id), time DESC (replaced by (device_id, time DESC) in 0072)
0058activity_events: register columns nullable, plant_id and details added — for device_update entries (a device moving between plants, or its logger being swapped)
0059–0061Logger swaps: devices.current_logger_id (dropped by 0072), pending_logger_id, pending_logger_since; unique devices_physical_logger_uidx (dropped by 0072) and devices_pending_logger_uidx, both built CONCURRENTLY
0029–0030one open erasure per logger (device_deletions_one_open_per_logger_uidx, excluding completed and superseded rows)
0031CHECK constraints for canonical case (NOT VALID), see above
0032devices.plant_id (uppercase cse-http-be plant ULID, NOT VALID check, no index)
0033–0037Device alerts: device_alert_state, alerts_active, alert_history (7-day-chunk hypertable, compressed after 14 days, 365-day retention, 400 days since 0111–0112), read-state tables
0038–0042telemetry_15m: UTC 15-minute continuous aggregate for Analytics (real-time; per-flow power split into import/export and charge/discharge, max of each lifetime and daily energy counter, peak PV power), refreshed every 15 minutes over a 4-day window, compressed after 7 days, 4-month retention
0043plants — plant timezone as TCP knows it (tz_source default/client/http_projection)
0044energy_daily — finalised plant-local-day energy per logger (lifetime-counter deltas, daily-counter fallback, end counters carried forward), kept indefinitely
0045energy_rollup_runs — which (timezone, local day, pass) the rollup has done
0046–0047plants_timezone_idx, and devices_plant_id_idx (partial, built CONCURRENTLY) — the rollup's per-timezone logger lookup
0048energy_daily_source_check widened to allow source = 'power_integral'
0049–0053telemetry_params: Historical Data parameter history, one nullable REAL column per internal/histparams parameter, primary key (logger_id, time) until 0072, no foreign key to devices until 0072 (the writer also joins on devices); 1-day-chunk hypertable, compressed after 2 days, 94-day retention. See Historical Data.
0062–0065Drop telemetry_yearly, telemetry_monthly, telemetry_daily (UTC-bucketed, unread) and telemetry_15m: none can be re-keyed in place. Irreversible: 15-minute buckets older than raw telemetry's 5 days are lost once
0066–0071Turn compression off on telemetry_params and alert_history (policy removed, chunks decompressed) so 0072 can re-key them
0072Device-id re-key, one transaction: devices.id (UUID, gen_random_uuid()) becomes the primary key; every history table gets device_id (back-filled, foreign key, new primary keys/indexes; orphan rows with no device are deleted); logger_id is dropped from telemetry, telemetry_params, energy_daily, device_alert_state, tariff_rates, daily_financials and kept as a snapshot on alerts_active, alert_history, activity_events; current_logger_id folded into logger_id and dropped; devices_logger_uidx (non-revoked); canonical-case constraints validated; loggers table and the devices_track_logger triggers; devices_freeze_verified_sn trigger; device_deletions.device_id. Irreversible — its down migration refuses. Preconditions are in its header
0073–0076Compression back on: telemetry_params segmented by device_id (2-day policy), alert_history unchanged (14-day policy)
0077–0082telemetry_15m recreated grouped by device_id, with 0039–0042's refresh, compression and retention policies, then filled once from every raw reading (0082)
0083device_status gains deactivated: a device kept with its history but with no logger (its owner registered the logger on another inverter). Alone in its file because a new enum value cannot be used in the transaction that adds it. The down migration is a no-op (enum values cannot be dropped)
0084devices.logger_id nullable, allowed NULL only on a deactivated or revoked device (devices_logger_required_chk, added NOT VALID then validated); devices_track_logger opens no loggers row for a NULL logger. Unique indexes unchanged. The down migration refuses while any device has no logger. See Device identity
0085Drop logger_bind_requests (0017): unused since bind_new_logger was removed, and its rows held logger ids, inverter serials and requesting users. Its header lists the check to run first; the down migration recreates the empty table only
0111–0112alert_history retention 365 → 400 days: an annual performance certificate reads a whole calendar year of alerts and is generated in the first days of the next one
0113report_renders — one row per report render attempt (report-renderer): a finished attempt is never rendered again, a crashed one continues its status seq; pruned after 120 days by the renderer
0114Plant availability per local day on plant_energy_daily (daylight_device_slots, outage_device_slots, producing_device_slots, daylight_basis, availability_pass) and their monthly sums on plant_energy_monthly: availability = producing ÷ (daylight − grid outage), see Fleet analytics
0129plant_energy_daily.nodata_device_slots: daylight device-slots with no 15-minute reading and no offline/critical alert open, behind get_plant_kpis availability.noDataHours and its no_data notice (see Fleet analytics). Nullable, catalog-only; days stored before it are re-measured by the availability history pass back to the first 15-minute bucket
0130devices_freeze_verified_sn lets exactly one change to a verified inverter_sn through: releasing it (inverter_sn to NULL, the old value into released_inverter_sn) on a deactivated or revoked device with no logger. Before it, unbind_logger with releaseInverter failed on every device that had ever connected. Trigger replace only, catalog-only; the down migration restores 0072's trigger
0131devices.parallel_role (standalone, master, slave, misconfigured), parallel_address, parallel_count: where a Nexus sits in a paralleled set, copied by persistence-worker from each stored reading (a reading without them keeps the last values) and returned by get_devices. tcpserver reads the two settings (1162/1163) at connect and every 15 minutes. Nullable, unindexed, catalog-only
0132alert_workflow.acknowledged_via_platform, assigned_via_platform, resolved_via_platform, assignee_via_platform and alert_events.actor_via_platform: an alert action Crown staff took through platform access, so the console shows them to non-Crown readers as "Crown Support". Rows written before it read false until scripts/sql/2026-11-12_alert_actor_via_platform_backfill.sql is run. Boolean, default false, catalog-only. (Written as a second 0131 on another branch; renumbered after the merge crash-looped persistence-worker on 2026-11-12)
0148logger_sightings.model_code (nullable INTEGER, metadata-only): the spec-code register an unserved logger's inverter reported, read by plant admission. Must be applied before the ws-gateway build that checks plant admission takes registrations — see below
0159devices_freeze_verified_sn also lets a released serial come back: inverter_sn from NULL to the row's own released_inverter_sn, which becomes NULL. Registration and connect use it so a released inverter re-added by its own owner or Business returns to the old device instead of becoming a new one. Trigger replace only; the down migration restores 0130's
0160devices_released_inverter_sn_idx, partial (released rows only), CONCURRENTLY: the released-serial lookup in registration and ResolveOnConnect

:::caution Migration 0148 before the plant-admission ws-gateway Plant admission (owner decision 2026-11-23) reads logger_sightings.model_code. ws-gateway never migrates, so until tcpserver or persistence-worker has started on a build that includes 0148 and applied it, every registration into a plant (register, register_device_web, import_devices) fails with a database error (REGISTRATION_FAILED on mobile). On dev, let tcpserver (or persistence-worker) start on the new build and confirm 0148 applied in its log before the new ws-gateway takes traffic. npm run deploy deploys pilot-ecs-tcp-ingest before ws-gateway (a stack dependency), which normally covers it; a ws-gateway-only deploy, or a tcpserver whose startup migration failed, does not. :::

telemetry_daily, telemetry_monthly and telemetry_yearly (0005–0011) bucketed on UTC days and nothing read them; they were dropped by the device-id re-key (0062–0064). Analytics uses telemetry_15m and energy_daily.

Every per-device table is keyed by device_id since 0072; read the table rows above for the shape each had before.

activity_events has no rollup behind it, so a row past 730 days is gone for good; the window is a placeholder pending a product/compliance decision. logger_sightings has no foreign key to devices (it is per logger, and most of its rows are for loggers nobody owns), which is why erasure deletes it explicitly; activity_events has had one since 0072.

Transport​

MODBUS_TRANSPORT=rtu (default for tcpserver, CRC-framed — matches a serial-to-Ethernet bridge) or tcp (default for probe, MBAP-framed). Not knowable from the vendor docs — test against the real device, or try both transports in the Sandbox to see how the framing differs.

Running locally​

The whole local stack — NATS and TimescaleDB in Docker, plus tcpserver, ws-gateway and persistence-worker — comes up with one command from the repo root:

npm run dev # start everything (reuses existing containers)
npm run dev:stop # stop the Go services, leave the containers up
npm run dev:down # stop the nats/timescaledb containers

Locally tcpserver listens on DEVICE_PORT=8443 (set by scripts/dev.sh, not the binary's 9000 default) and ws-gateway on 8090.

:::caution go run never reloads Each service is compiled once when npm run dev starts. Editing Go source does not change what is running — an old binary keeps serving happily while the source on disk says something else. After any change to server/, run npm run dev:stop && npm run dev.

dev:stop exists because Ctrl-C isn't always available (the stack is often left running detached) and because killing go run does not kill the binary it compiled and exec'd into the go-build cache — a survivor there keeps holding :8090/:8443 and makes the next npm run dev fail on a port already in use. dev:stop signals both, then reports anything still listening. :::

To run a single service by hand instead:

cd server
DEVICE_PORT=9000 go run ./cmd/tcpserver

Only accepts connections (matches production: devices dial out to a configured server). Build the same image CDK deploys:

docker build -t tcp-ingest:local .

To inspect the deployed dev database, cd cdk && npm run db:tunnel opens an SSM port-forward from localhost:15432 to the telemetry-db host (it has no public address). The script prints the command to fetch the password from the cse-tcp-be-dev-telemetry-db-credentials secret rather than printing the password itself.

Simulated device (cmd/device-sim)​

cmd/device-sim stands in for a logger + inverter, so the console and app can be tested end to end on dev without hardware. It dials out to the ingest server, as a real DTU does, and:

  • answers AT+DTUPN? with -logger, AT+HTBT? with AT+HTBT:, any other AT command with R001 (refused), and AT+RESTORE by dropping the link and dialling back;
  • serves Modbus RTU functions 3, 4, 6 and 16 from one in-memory register map. Every register reads 0 except the profile's identity register, which holds -serial. Writes are kept for the life of the process, across reconnects, so a written setting reads back. Function 6 is acknowledged by echo, function 16 with the standard acknowledgement. Other functions get exception 01, a read over 125 registers exception 03, a bad CRC no answer.

Only Modbus profiles are supported (Nexus, Yorker); the ASCII IP20 3K6/5K is not. Telemetry is all zeros unless seeded with -set (raw 16-bit words, decimal or 0x hex, repeatable).

cd server
go run ./cmd/device-sim -addr <tcp-ingest-nlb-dns>:8443 \
-model Nexus -serial SIMNEXUS0001 -logger SIMLOGGER0001

8443 is dev's devicePort (cdk/cdk.json); the NLB DNS name is in the cse-tcp-be-dev-pilot-ecs-tcp-ingest stack's resources. Stop with Ctrl-C. It retries with backoff (1 s doubling to 1 min, plus jitter) when the link drops.

Binding it to a test plant. The simulator writes nothing to any database. A person registers it like a real device, with an account allowed to add devices to the test plant:

  1. Start the simulator (above) and leave it running. In the tcpserver logs it shows as an unidentified connection with the logger id you chose (stored lower case).
  2. In the web console, register a device on the test plant with logger ID = -logger and inverter serial = -serial (or leave the serial empty to have it read from the "hardware"). Over the WebSocket this is register_device_web with loggerId, inverterSn, plantId.
  3. On its next connection the server reads the serial back and confirms the device. Settings writes from the console then go to the simulator, and its log prints each register written line.

Use made-up ids that cannot collide with a real logger (e.g. a SIM prefix). When done, delete the device from the console as for any other.

The tests in cmd/device-sim drive the simulator with tcpserver's own session code (detection, AT+DTUPN, heartbeat, serial read, write and read back), so a protocol change in the server breaks them rather than dev QA.

Database integration tests​

The Postgres integration tests (the *_integration_test.go files in server/internal/storage/postgres, server/internal/erasure and server/cmd/ws-gateway) need a database and write to it: they apply every migration and insert devices, telemetry and rollups. Without POSTGRES_TEST_DSN they skip. Run them with:

npm run test:db # every integration test
npm run test:db -- 'ParamHistory|Total' # only tests matching a go test -run regexp

scripts/test-db.sh starts a fresh timescale/timescaledb:latest-pg16 container on 127.0.0.1:5544 (override with TEST_DB_PORT) with a random password that only exists in the script's environment. It runs the storage package first, because its tests apply the migrations, then the erasure and gateway packages, and removes the container on exit, pass or fail. A pass also proves every migration applies to an empty database.

Never point POSTGRES_TEST_DSN at the dev stack's timescaledb container or at the SSM tunnel (localhost:15432, the deployed dev database).

Testing against a real device (cmd/probe)​

A WiFi logger reachable on your LAN is usually the opposite direction — it's the Modbus server, waiting to be polled. cmd/probe dials in:

cd server
TARGET_ADDR=192.168.1.50:502 TELEMETRY_MODEL="Nexus" go run ./cmd/probe
  • TARGET_ADDR — logger's LAN IP:port (502 is standard; cheap dongles sometimes use 8899/4196 — check the logger's manual).
  • It runs one profile health check (or detection), batch-limit discovery and one telemetry cycle, then exits. No AT+DTUPN, no database, no NATS.
  • If neither MODBUS_TRANSPORT value gets a clean health check: confirm the port is open (nc -zv <ip> <port>), try a different slave address (edit connection.slave_address in the relevant server/internal/modbus/specs/*.json), or capture traffic (tcpdump -i en0 host <ip> -X) to see what's actually being sent back.

:::tip Not ready to point this at real hardware yet? The Sandbox builds the exact same request frame bytes cmd/probe would send, and shows a simulated decoded response, entirely in your browser — no device or network connection required. :::