# Sending telemetry: the local socket

The publishing process does not need an SDK, credential, or network client. The
installed Fleet Agent still requires a Constellation API token and outbound
network access. Your application needs one line of text and a Unix socket.

For a validated one-shot write, the installed agent provides:

```bash
constellation-agent emit \
  --ground-station-id GS-001 \
  --ground-antenna-id GS-001-ANT-1 \
  --satellite-id SAT-9 \
  --field elevation_deg=22.8 \
  --field c_n0_dbhz=71.4 \
  --field carrier_locked=true
```

Use `--dry-run` to print without sending, or `--json` to read the JSON record
shape from standard input. High-rate applications should use the socket
directly and keep the connection open.

The CLI uses the same scalar spellings as line protocol: `2i` is an integer,
`2` is a float, `true` is a Boolean, and ordinary text is a string. Preserve a
numeric-looking string with quotes, for example `--field 'uplink_status="001"'`.

```bash
printf '%s %s\n' \
  'link,ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9 elevation_deg=22.8,c_n0_dbhz=71.4,carrier_locked=true' \
  "$(date +%s)000000000" \
  | socat - UNIX-CONNECT:/run/constellation-agent/telemetry.sock
```

That's the whole interface. The rest of this document explains why it works and
the ways to get it wrong.

## Why a socket

A collector (stock Telegraf) runs on the machine and owns everything hard about
delivery:

```
your process ──line protocol──▶ Unix socket ──▶ collector buffer ──▶ Constellation API
   no credential                 always on        survives outages      credential lives here
```

What that means for your process:

- **Your process never holds the API token.** It lives root-only in
  `/etc/constellation/agent.env`. Application code that cannot read a secret
  cannot leak one.
- **Writes do not block on the network.** You write to a local socket. If the
  API is down, the collector queues to disk and drains later.
- **Do not add remote retries to the publishing process.** Retry, backoff, and
  batching belong to the Fleet Agent. Reconnect only when the local socket
  connection itself closes or fails.
- **Delivery is not acknowledged.** The socket accepts your bytes and returns
  nothing. This is the trade for the three points above — see
  [Knowing it worked](#knowing-it-worked).

## Finding the socket

The installer writes the path to a world-readable env file:

```bash
. /etc/constellation/socket.env      # sets CONSTELLATION_SOCKET_PATH
echo "$CONSTELLATION_SOCKET_PATH"    # /run/constellation-agent/telemetry.sock
```

Read it from there rather than hardcoding.

Access is group-gated in two places. The directory `/run/constellation-agent`
is mode `2770`, owned `telegraf:constellation` — the setgid bit is what makes
the socket inherit group `constellation` — and the socket itself is `0660`. A
non-member cannot even traverse into the directory, so the failure arrives as
`Permission denied` or `No such file or directory` depending on which check
trips first. Neither means the collector is down.

Your service account must be in the group:

```bash
sudo usermod -aG constellation "$(whoami)"   # log out and back in to take effect
id -nG | tr ' ' '\n' | grep -x constellation # confirm before debugging further
```

## The line format

One record is one line, terminated by `\n`: one ground antenna tracking one
satellite at one instant. Four parts, in this order:

```
link,ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9 elevation_deg=22.8,carrier_locked=true 1753900862000000000
└┬─┘ └──────────────────────────────┬─────────────────────────────────────┘ └──────────────┬─────────────────┘ └────────┬────────┘
 measurement                       tags                                                 fields                   timestamp
 (ignored)          (comma-separated, no spaces around =)                  (comma-separated)          (nanoseconds since epoch)
```

Separators are positional and unforgiving:

- A **comma** separates the measurement from tags, and tags from each other.
- A **single space** separates tags from fields, and fields from the timestamp.
- Everything after the second space is the timestamp.

That is why an unescaped space inside a tag value silently reinterprets the rest
of your line as fields.

The agent sends each line to the platform as a `constellation.ingest.v2`
record (`POST /v2/telemetry` on HTTP egress). The platform checks every record
in a batch, writes the ones that pass, and reports each problem with the rest
by record index, field and reason. Only a batch in which no record passes is
refused. One exception on HTTP egress: a record that breaks the record schema
(a malformed id, a `contact_id` over 128 characters) fails the whole request
with 422, where gRPC rejects that record alone.

### Measurement

Line protocol needs one; the platform does not read it. Use `link`.

### Tags — the three ids

Tags carry the record's ids, as your **network config** names them:

| Tag | Required | Must be |
|---|---|---|
| `ground_station_id` | yes | a ground station in the network config |
| `ground_antenna_id` | yes | an antenna of **that** ground station |
| `satellite_id` | yes | a satellite in the network config |
| `radio_id` | no | a radio of that satellite in the network config |
| `contact_id` | no | 1-128 characters naming the contact (pass) |

The three ids are 1-64 characters of letters, digits, `.`, `_` and `-`. Any
other tag is dropped by the agent.

Send `radio_id` on all of a link's records or on none: a link with both is two
series. Use it when one satellite has two carriers measured at the same instant,
such as a GNSS satellite's L1 and L5.

Two ways an id goes wrong, and they fail differently:

- **A missing id tag.** The agent drops the line before sending it, and says so
  in `constellation-agent logs` on gRPC egress. On HTTP egress it is dropped
  with no log line.
- **An id the network config does not have** (or an antenna under a different
  station). The platform rejects that record (`not_in_network_config`) and
  writes the rest of the batch. On gRPC egress the agent logs the counts and
  the first five rejections; on HTTP egress they are in the 202 response, which
  Telegraf does not log.
- **No network config at all.** Nothing can be accepted, so every batch is
  dropped: logged once per batch on gRPC egress, rejected with 409 on HTTP.

```
✅ link,ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9 elevation_deg=22.8
❌ link,ground_station_id=GS-001,satellite_id=SAT-9 elevation_deg=22.8              no antenna: dropped
```

Station positions and satellite orbits are not telemetry. They come from the
network config (satellites carry their TLEs there), so do not publish them here.

### Fields — a closed list, typed

Fields are the measured values, and only these are accepted:

| Field | Type | Notes |
|---|---|---|
| `azimuth_deg` | float | antenna pointing |
| `elevation_deg` | float | |
| `tracking_error_az_deg` | float | |
| `tracking_error_el_deg` | float | |
| `track_mode` | string | |
| `range_m` | float | one-way |
| `range_rate_m_s` | float | |
| `carrier_locked` | boolean | |
| `subcarrier_locked` | boolean | |
| `symbol_locked` | boolean | |
| `frame_locked` | boolean | |
| `c_n0_dbhz` | float | |
| `es_n0_db` | float | |
| `rx_power_dbm` | float | on an optical link, the power at the receiver input, after the antenna gain the network config gives (`antenna_diameter_m`, `antenna_efficiency`); the SNR model learns and forecasts this value |
| `frequency_ghz` | float | the carrier's centre frequency |
| `carrier_offset_hz` | float | |
| `frames_delivered` | integer | cumulative since the pass started |
| `frames_good` | integer | cumulative since the pass started |
| `uplink_status` | string | |
| `modcod` | string | the carrier's current MODCOD as the modem names it, e.g. `QPSK 1/4` |
| `tx_power_dbm` | float | |
| `ber` | float | bit errors / bits over the reporting interval, not a cumulative count |
| `per` | float | packet errors / packets over the reporting interval, not a cumulative count |
| `system_noise_temp_k` | float | system noise temperature in kelvin; at least one sample per 5 s for the rfi noise channel |
| `noise_power_dbm` | float | noise power in dBm in a fixed bandwidth; at least one sample per 5 s for the rfi noise channel |
| `noise_diode_on` | boolean | calibration diode state; at least one sample per 5 s for the rfi noise channel |
| `bytes_delivered` | integer | a flown pass's outcome: bytes it delivered (a pass log record, timed at AOS) |
| `contact_status` | string | a flown pass's outcome: `ok`, `failed` or `missed` |
| `los_utc` | string | a flown pass's end (RFC 3339); the record's time is its start |

The list is the platform's (`FIELD_TYPES` in `constellation/core/telemetry/v2.py`). An unknown field is dropped and
reported (`unknown_field`) and the rest of its record is written; a record left
with no known field is rejected. A wrong type (`wrong_type`), or a value line
protocol cannot carry (`invalid`), rejects the record, as an unknown id does.
A pass outcome field is checked for its value too and a bad one rejects the
record, naming the field: `bytes_delivered` below 0 (`must_be_at_least_0`), a
`contact_status` not `ok`, `failed` or `missed` (`unknown_contact_status`), a
`los_utc` that is not RFC 3339 (`not_iso_8601`), has no offset
(`needs_a_utc_offset`) or is not after the record's time
(`must_be_after_the_record_time`). Over HTTP such a record refuses the whole
batch with a 422 (`detail[].ctx` holds `field` and `reason`, `loc` the row). A
whole number sent as a float is a valid `bytes_delivered`.

A modem reports bit and packet errors as cumulative counters. Difference them
in your collector and publish `ber` and `per` as the ratio for the interval
since the last report.

**The syntax you use decides the type**, which is why a bare `1` and `1i` are
different things:

| Type    | Write it as       | Example                   |
|---------|-------------------|---------------------------|
| Float   | bare number       | `elevation_deg=22.8`, `es_n0_db=1` |
| Integer | trailing `i`      | `frames_good=4820i`       |
| Boolean | `true` / `false`  | `carrier_locked=true`     |
| String  | double quotes     | `track_mode="program"`    |

A float field also accepts an integer. An integer field does not accept a float,
and a boolean field does not accept `1`/`0`.

Numeric fields are stored as floats on both egress paths, so `4820i` reads back
as `4820.0` and values above 2^53 lose exactness. Write the `i` suffix anyway:
it is what the platform checks.

At least one field is required. A line with tags and no fields is a parse error.

Boolean fields cannot be aggregated in Flux: `mean` fails with
`unsupported input type`, `min`/`max` panic. Cast with `toFloat()` first.

### Timestamp

Nanoseconds since the Unix epoch. Not seconds, not milliseconds.

```bash
date +%s%N                      # GNU coreutils
python3 -c 'import time;print(time.time_ns())'
```

The timestamp is optional — omit it and the collector stamps arrival time. Send
it explicitly if the sample has a real observation time, which is almost always.

The platform rejects a record stamped before 2000-01-01 or more than 5 minutes
ahead of its clock (`implausible_timestamp`) and writes the rest of the batch.
A series whose newest stamp is ahead of the platform clock by less than that is
shifted back as a whole, so its newest record lands on the platform's now.

## What your records become

`GET /v2/topology` returns the newest value of **each field** per
`(ground_station_id, ground_antenna_id, satellite_id)` seen in its freshness
window (`freshness_seconds`, default 300), stamped with the newest record's
time. `contact_id` comes back among the fields. Fields are merged across
records, so an antenna field published at 1 Hz and a carrier field published
every 10 s both appear in the same row.

Republish inside the freshness window: a link nobody has written to for longer
than that is absent from topology, not shown as stale. `GET /v2/telemetry`
returns the raw records (or windowed aggregates) for a time range.

## The five rules that kill a metric

The collector **discards a malformed line and reports it only in its own log**.
Your write succeeds. The data never appears. These five were verified against
the collector's parser, and they come before the platform's own checks above:

1. **No newlines anywhere — including inside quoted strings.** The socket splits
   the stream on `\n` before parsing, so an embedded newline destroys the metric
   carrying it *and* turns its tail into a second parse error.
2. **No backslashes** in the measurement, tag keys, tag values, or field keys.
   The parser treats `\` + escapable as an escape but leaves `\` + ordinary as
   two literal characters, so `C:\dir` round-trips as `C:\\dir`, and a tag value
   *ending* in a backslash cannot be represented at any escaping depth.
   Backslashes are fine inside quoted string *field values*.
3. **No empty tag values.** `contact_id=` is a hard parse error ("expected tag")
   that kills the whole metric. Omit the tag instead.
4. **Integers are int64.** Anything wider is a "value out of range" parse error.
5. **Floats must be finite.** `NaN` and `Inf` are not representable.

Escape — with a backslash — any comma, space, or `=` inside a measurement, tag
key, tag value, or field key. Inside a quoted string field value, escape `"` and
`\` only.

## Writing it, with no dependencies

Every example below is stdlib-only and complete.

**Shell.** Bash cannot open an `AF_UNIX` socket itself — its `/dev/tcp`
redirection has no Unix-domain equivalent — so pipe through `socat`:

```bash
. /etc/constellation/socket.env
printf 'link,ground_station_id=%s,ground_antenna_id=%s,satellite_id=%s elevation_deg=%s,c_n0_dbhz=%s %s\n' \
  "GS-001" "GS-001-ANT-1" "SAT-9" "22.8" "71.4" "$(date +%s%N)" \
  | socat - "UNIX-CONNECT:$CONSTELLATION_SOCKET_PATH"
```

For a stream of samples, pipe the whole stream into one `socat` rather than
invoking it per line.

**Python** (stdlib, no package to install)

```python
import os, socket, time

path = os.environ["CONSTELLATION_SOCKET_PATH"]
IDS = "ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9"

def emit(fields, time_ns=None):
    body = ",".join(f"{k}={v}" for k, v in sorted(fields.items()))
    line = f"link,{IDS} {body} {time_ns or time.time_ns()}\n"
    with socket.socket(socket.AF_UNIX) as s:
        s.connect(path)
        s.sendall(line.encode())

emit({"elevation_deg": 22.8, "c_n0_dbhz": 71.4, "carrier_locked": "true", "frames_good": "4820i"})
```

Keep one connection open if you emit often — reconnecting per sample caps you
well below the collector's throughput.

**Go**

```go
c, _ := net.Dial("unix", os.Getenv("CONSTELLATION_SOCKET_PATH"))
defer c.Close()
fmt.Fprintf(c, "link,ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9 elevation_deg=%.1f %d\n",
	22.8, time.Now().UnixNano())
```

**Node.js**

```javascript
const net = require("node:net");
const socket = net.createConnection(process.env.CONSTELLATION_SOCKET_PATH);
socket.on("connect", () => {
  socket.end(`link,ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9 elevation_deg=22.8 ${BigInt(Date.now()) * 1000000n}\n`);
});
```

**Rust** (standard library)

```rust
use std::io::Write;
use std::os::unix::net::UnixStream;
use std::time::{SystemTime, UNIX_EPOCH};

let mut socket = UnixStream::connect(std::env::var("CONSTELLATION_SOCKET_PATH").unwrap()).unwrap();
let timestamp = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_nanos();
writeln!(socket, "link,ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9 elevation_deg=22.8 {}", timestamp).unwrap();
```

**C**

```c
#include <sys/socket.h>
#include <sys/un.h>
#include <unistd.h>
#include <string.h>

int fd = socket(AF_UNIX, SOCK_STREAM, 0);
struct sockaddr_un address = {.sun_family = AF_UNIX};
strncpy(address.sun_path, "/run/constellation-agent/telemetry.sock",
        sizeof(address.sun_path) - 1);
connect(fd, (struct sockaddr *)&address, sizeof(address));
const char line[] = "link,ground_station_id=GS-001,ground_antenna_id=GS-001-ANT-1,satellite_id=SAT-9 elevation_deg=22.8\n";
write(fd, line, sizeof(line) - 1);
close(fd);
```

Constrained firmware should emit line protocol directly rather than model any
of the platform API.

## Knowing it worked

The socket does not acknowledge. Two checks, cheapest first:

```bash
sudo constellation-agent verify --ground-station-id GS-001 \
  --ground-antenna-id GS-001-ANT-1 --satellite-id SAT-9   # writes a proof record, reads it back
sudo constellation-agent logs        # parse errors and rejections surface here and nowhere else
```

`verify` writes a real record for that link (`contact_id=verify-<nonce>`,
`track_mode="constellation-agent-verify"`), which shows as the link's newest
values until real telemetry replaces them.

Then confirm it landed:

```bash
curl -s -H "x-api-key: $CONSTELLATION_API_TOKEN" \
  "https://api.constellation.space/v2/topology?satellite_id=SAT-9" | jq '.[] | .tags, .time'
```

With the installed one-second default, budget roughly **0.8 seconds on
average** from socket write to `GET /v2/topology` (half the flush interval,
plus the historically observed ~0.3 seconds for transit and projection). This
is a planning estimate, not a latency objective; buffering, network conditions,
and platform load can increase it.

If a record is missing, work down this list — it is ordered by how often each
one is the cause:

1. An id not in the network config, or an antenna under the wrong station →
   the record is rejected; `constellation-agent logs` names the id on gRPC.
2. A missing id tag, or a field off the list → the line or field is dropped;
   same log.
3. Parse error → `constellation-agent logs` names the line.
4. Wrong timestamp unit → the sample landed outside the freshness window.
5. Collector buffering → the API was unreachable; it drains on recovery.

## Limits

| Limit | Value | Notes |
|---|---|---|
| Sustained rate, disk buffer | **~300 records/s** | fsyncs per metric; batch size does not raise it |
| Sustained rate, memory buffer | ~596,000 metrics/s | set `CONSTELLATION_BUFFER_STRATEGY=memory`; loses the buffer on restart |
| Buffer depth | 100,000 metrics | ~12 MB, ~2h at 13 metrics/s |
| Flush interval | 1s | configurable at install time with `CONSTELLATION_FLUSH_INTERVAL` |
| API request body | 1 MB | the collector batches to fit; not your concern |

Those rates were measured on NVMe. **Expect materially less on eMMC or
SD-backed edge hardware — benchmark before provisioning a fast sensor.** If you
need more than ~300/s durably, that is a firehose path, not this socket.
