# Pulsync agent reference

Library **0.3.5**. Hosted app and API: `https://pulsync.dev`. This file: `https://pulsync.dev/docs/agent.md`. Human docs: `https://pulsync.dev/docs`. `pulsync.in` is the marketing site, not the API.

Use this file to write firmware, call the hosted external API, or run a self-hosted server. Do not invent routes. Portal and dashboard cookie routes are not an external API.

## Library (ESP32)

Arduino (PlatformIO or Arduino IDE) and native ESP-IDF. Global object `Pulsync`.

Install (PlatformIO):

```ini
lib_deps = https://github.com/pulsync/pulsync-arduino.git
```

Arduino IDE: latest zip from `https://github.com/Pulsync/pulsync-arduino/releases`, then Sketch → Include Library → Add .ZIP Library. Builds on arduino-esp32 3.x and 2.x. OTA needs two app partitions (`partitions/pulsync_ota.csv`, or PlatformIO `board_build.partitions = min_spiffs.csv`).

### Init order

Call these **before** `begin()`. `begin()` returns `false` if NVS is unavailable. Call `Pulsync.loop()` from `loop()` every time. It does not block.

```cpp
#include <Pulsync.h>

void setup() {
  Pulsync.setWiFi("SSID", "password");          // optional password
  Pulsync.setServer("https://pulsync.dev");     // omit to auto-discover
  Pulsync.setVersion("1.2.3");                   // before begin; default 0.0.0
  Pulsync.begin("PUL-A7K9X2");                   // pairing code from the portal
}

void loop() { Pulsync.loop(); }
```

`setServer("pulsync.local:3456")` or `setServer("http://192.168.1.50:3456")` points at a self-hosted server. With no server set, the library probes the LAN for 5 seconds, then the hosted cloud. If neither answers, it retries every 15 seconds. An enrolled device stores the server and skips discovery.

A pairing code is exchanged once for a device token stored in NVS. Later boots reuse the token. HTTP `401` or an MQTT auth refusal starts re-enrollment. If enroll returns FAILED, the next try waits 60 seconds. HTTP calls time out at 10 seconds. A token probe before MQTT retries every 5 seconds.

### Scheduler

Up to 32 tasks (`PULSYNC_MAX_TASKS`).

```cpp
uint16_t setInterval(std::function<void()> cb, uint32_t interval_ms);
uint16_t setTimeout(std::function<void()> cb, uint32_t delay_ms);
bool clearInterval(uint16_t id);
bool clearTimeout(uint16_t id);
```

Do not use `delay()` in handlers.

### Send telemetry

```cpp
void send(const char *key, float value);   // also int, bool, const char*
void beginPayload();
void add(const char *key, float value);    // also int, bool, const char*
void endPayload();
```

`send` publishes one key. `beginPayload` / `add` / `endPayload` publishes one object. Keys are top-level names a dashboard subscribes to (`temperature`, not nested paths).

### Commands

The device receives `{"command":"name","payload":{"value":X}}`.

```cpp
void onInt(const char *command, std::function<void(int)> handler);
void onFloat(const char *command, std::function<void(float)> handler);
void onBool(const char *command, std::function<void(bool)> handler);
void onString(const char *command, std::function<void(const char *)> handler);
void on(const char *command, std::function<void()> handler);
void on(const char *command, std::function<void(Payload &)> handler);
```

`reboot` is built in. About one second after the command, `loop()` calls `esp_restart()`. A user `on("reboot")` handler is optional and runs first. Do not add `ESP.restart()` unless you need extra work before that restart.

### Remote config

```cpp
void onConfig(const char *key, std::function<void(int)> cb, int default_val = 0);
// also float, bool, const char*
int   config(const char *key, int default_val);
float config(const char *key, float default_val);
bool  config(const char *key, bool default_val);
```

### SoftAP (shared)

One SoftAP for the config portal (port **80**) and optional sketch HTTP on **another port**.

```cpp
bool enableAP(const char *ssid, const char *password = nullptr);
void disableAP();
bool isAPEnabled();
const char *getAPIP();   // typically "192.168.4.1"
```

Need-based: AP is on while the portal and/or `enableAP` holds a need; otherwise STA-only. Portal priority: while the captive portal is open it keeps SSID `Pulsync-XXXX` (open) and DNS; `enableAP` only registers the sketch need and re-applies the sketch SSID after the portal closes. Do not bind port 80 in the sketch. Do not start a second SoftAP with `WiFi.softAP` alongside Pulsync.

### Status and timing

```cpp
void setHeartbeatInterval(uint32_t interval_ms);  // floor 30s
void setResetPin(int pin);                        // hold 3s → config portal
bool isConnected();
bool isWiFiConnected();
const char *getTransportName();  // "mqtt" or "none"
const char *getIP();             // STA IP
int queuedCount();
int queueCapacity();             // 20
```

| Behavior | Value |
|----------|--------|
| Heartbeat default and minimum | 30s |
| Wi-Fi profiles stored | 3 |
| Wi-Fi tries per profile | 2 |
| Wi-Fi reconnect backoff | 1s, doubles, caps at 60s |
| MQTT keepalive | 30s |
| MQTT publish QoS | 1 |
| Offline queue | 20 messages |
| OTA HTTP timeout | 30s, then reboot 2s after a verified image |
| Config button | hold 3s opens the captive portal |
| SoftAP | shared; portal port 80; sketch uses another port |

Holding the pin does **not** factory-reset or erase NVS. Factory reset is a separate action inside the portal. If Wi-Fi is missing, `begin()` opens that portal so a phone can enter credentials.

`getTransportName()` is `"mqtt"` when the live link is up. Enrollment and OTA use HTTP(S). The server returns `mqtt_url` at enroll and can change it on heartbeat. Local MQTT is plaintext. Hosted MQTT is TLS. Network I/O is a FreeRTOS task. `queuedCount()` grows while the link is down.

### OTA versions

`setVersion("1.2.3")` before `begin()`, or `-D PULSYNC_FW_VERSION=\"1.2.3\"`. Runtime wins. Format is `x.y.z` or `x.y.z-label` with **at most one number** in the label (`1.2.3-dev3` is valid, `1.2.3-dev3.2` is rejected). Order is numeric: `1.2.3 < 1.2.3-dev1 < 1.2.3-dev2`, and `1.2.4 > 1.2.3-dev9`. The string the device reports must equal the `.bin` you uploaded. A mismatch offers the same build forever. The device verifies signature and checksum, applies, reboots, and rolls back if the new image does not confirm.

Human pages: `https://pulsync.dev/docs/library/api`, `https://pulsync.dev/docs/library/ota`, `https://pulsync.dev/docs/quick-start`.

## Hosted external API

For a custom dashboard. Create the key in the portal at `https://pulsync.dev`. It is shown once, looks like `psk_` plus 40 hex characters, and is the whole workspace. Revoke it in the portal. A revoked key stops immediately.

```
Authorization: Bearer psk_…
```

API keys may call only `/api/v1` and `/api/v1/…`. Any other path, including portal routes and `/api/live`, returns `403` `{"error":"API keys can only use /api/v1"}`. A cookie session on `/api/v1` returns `401` `{"error":"API key required"}`. A bad or revoked key is `401` `{"error":"Invalid API key"}`.

The key cannot create pairing codes, upload firmware, rename devices, or read config-portal passwords.

### Snapshot

`online` is true when `last_seen` is within 2 minutes. `data` is the latest telemetry object, or `null`. Only enrolled devices are listed. No pairing code, token, or password is returned.

`GET https://pulsync.dev/api/v1/devices`

```json
{
  "devices": [
    {
      "id": "DEVICE_ID",
      "name": "Kitchen",
      "last_seen": "2026-10-12T18:00:00.000Z",
      "online": true,
      "data": { "temperature": 25.3, "humidity": 60 },
      "timestamp": "2026-10-12T18:00:00.000Z"
    }
  ]
}
```

`GET https://pulsync.dev/api/v1/devices/DEVICE_ID` returns that object, not wrapped in `devices`. Unknown ids and other workspaces are `404` `{"error":"Device not found"}`.

### Action

`POST https://pulsync.dev/api/v1/devices/DEVICE_ID/actions`

```json
{ "command": "set_led", "payload": { "value": true } }
```

`payload` defaults to `{}`. `command` is required. Success body includes `success`, `commandId`, and `pushed` (true when MQTT accepted it). Missing command name is `400`. The device must be connected to receive it immediately. `reboot` restarts the board. Other names must match a sketch handler.

### Live socket

`wss://pulsync.dev/api/v1/live`

Browsers cannot set `Authorization` on a WebSocket. Pass `?access_token=psk_…`. A backend may send the Bearer header instead. The socket stays quiet until you subscribe. A bad key closes with `4401`.

```json
{ "type": "subscribe", "devices": ["DEVICE_ID"], "fields": ["temperature"] }
```

`devices` is required (max 100 ids). `fields` is optional (max 50 top-level keys). Omit `fields` to get the whole telemetry object. A later `subscribe` replaces the previous one. `{ "type": "unsubscribe" }` clears it. Ids you do not own are dropped. The server replies `{ "type": "subscribed", "devices": [...], "fields": [...] }`. Invalid JSON or a subscribe without `devices` is `{ "type": "error", "error": "..." }`.

| `type` | When |
|--------|------|
| `connected` | Once, on connect. Body is `{ "type": "connected", "tenantsScoped": true }`. No `clients` field. |
| `subscribed` | After subscribe or unsubscribe |
| `device_data` | `{ deviceId, data, timestamp }` for a subscribed device. With `fields`, `data` keeps only those keys. The event is dropped if none match. |
| `heartbeat` | `{ deviceId, status, timestamp }` for a subscribed device |
| `error` | Bad subscribe message |

`enrolled`, `ota_status`, `command_sent`, and any other type are **not** sent on this socket. Pushes on an open socket are not rate-limited.

### Limits (per key, fixed 60s window)

| Call | Limit | Over the limit |
|------|-------|----------------|
| `GET` snapshots | 60 | HTTP `429`, `Retry-After`, body `{ "error": "Too many requests", "retryAfter": N }` |
| `POST` actions | 30 | same |
| Socket opens | 10, and at most 5 open at once | close code `4429` |

Human page: `https://pulsync.dev/docs/server/api-access`.

## Device wire protocol

The ESP32 uses these. A dashboard must not. Auth after enroll is `X-Device-Token`. Hosted enroll is 30 requests per 60 seconds per IP. Hosted heartbeat and data share the workspace plan's messages-per-minute bucket.

| Call | Body | Result |
|------|------|--------|
| `POST /api/device/enroll` | `{ pairing_code, fw_version, mac_address, device_name }` | `{ token, device_id, mqtt_url?, config_pw_hash? }` |
| `POST /api/device/heartbeat` | status, including `fw_version` | heartbeat reply, possibly a new `mqtt_url` or OTA offer |
| `POST /api/device/data` | telemetry object | stored and fanned out to live sockets |

Hosted base is `https://pulsync.dev`. Self-hosted base is `http://pulsync.local:3456`. Firmware bytes are downloaded from `/api/device/fw-bin/…`, not from the admin upload route.

## Self-hosted server

Node.js 20+. SQLite and an in-process MQTT broker. No API keys.

```bash
git clone https://github.com/Pulsync/pulsync-server.git
cd pulsync-server
npm install
npm start
```

Dashboard: `http://localhost:3456/`. LAN name: `pulsync.local`. Docker Compose is optional and exposes HTTP `3456` and MQTT `1883`.

| Variable | Default | Purpose |
|----------|---------|---------|
| `PORT` | `3456` | HTTP |
| `MQTT_PORT` | `1883` | Embedded broker |
| `DATABASE_URL` | unset → SQLite | `postgresql://` to use Postgres |
| `ADMIN_PASSWORD` | empty → open | Gates dashboard and `/api/device` admin routes |
| `JWT_SECRET` | random each run | Set `openssl rand -hex 32` so admin sessions survive restart |

Device routes (`/api/device/enroll`, `/heartbeat`, `/data`) stay open and use the device token. If `ADMIN_PASSWORD` is unset, admin routes are open. If it is set:

```bash
curl -c jar.txt -X POST http://pulsync.local:3456/api/device/admin/login \
  -H "Content-Type: application/json" \
  -d '{"password":"your-admin-password"}'
curl -b jar.txt http://pulsync.local:3456/api/device/devices
```

Login stores a `ps_admin` cookie. Send that cookie on later admin calls.

| Action | Method and path |
|--------|-----------------|
| Login / logout | `POST /api/device/admin/login`, `POST /api/device/admin/logout` |
| List devices | `GET /api/device/devices` → `{ devices, ws_connections }` |
| Create pairing code | `POST /api/device/devices` body `{ name? }` |
| Device details | `GET /api/device/devices/:id` |
| Delete device | `DELETE /api/device/devices/:id` |
| Telemetry history | `GET /api/device/devices/:id/data?limit=100&since=ISO8601` |
| Telemetry count | `GET /api/device/devices/:id/data/count` |
| Send command | `POST /api/device/devices/:id/command` body `{ command, payload }` |
| Get / push config | `GET` or `PUT /api/device/devices/:id/config` — PUT body is `{ key: value }` |
| Attach firmware | `PUT /api/device/devices/:id/firmware` body `{ firmware_id }` or `null` to detach |
| List firmware | `GET /api/device/firmware` |
| Upload `.bin` | `POST /api/device/firmware?version=x.y.z` raw body, max 16MB |
| Activate a build | `POST /api/device/firmware/:id/activate` |
| Health | `GET /api/health` |

History is newest-first: `{ "data": [ { "data": { }, "timestamp": "" } ] }`. Default `limit` is 100. There is no hosted-style `/api/v1` on this server.

### Self-hosted live socket

`ws://pulsync.local:3456/api/live`

Not gated by `ADMIN_PASSWORD`. It is a firehose for every device, with no subscribe filter. No history on connect. Welcome frame is `{ "type": "connected", "tenantsScoped": false }`.

| `type` | Fields |
|--------|--------|
| `device_data` | `deviceId`, `data`, `timestamp` |
| `heartbeat` | `deviceId`, `status`, `timestamp` |
| `enrolled` | `deviceId`, `pairingCode` |
| `ota_status` | `deviceId`, `status`, `version` |
| `command_sent` | `deviceId`, `command`, `payload` |

The embedded broker does not rate-limit publishes. The hosted broker allows 120 publishes per 60 seconds per device and rejects the rest with `Publish rate exceeded`.

Human page: `https://pulsync.dev/docs/server/self-hosting`.

## Do not

- Do not use a device token (`X-Device-Token`) or the server MQTT secret as a dashboard credential. The device token can publish as that device. The server secret can see every tenant. Browsers cannot open raw MQTTS. Use `/api/v1` on hosted, or the admin cookie and `/api/live` on self-hosted.
- Do not point an API key at `/api/live`, `/api/devices`, or `/api/keys`. Those are cookie routes.
- Do not show a pairing code or an API key in a frontend bundle. Keys are shown once.
- Do not register `reboot` with `ESP.restart()` unless you need work before the built-in restart.
- Do not document or call `setResetPin` as a factory reset. Three seconds opens the config portal only.
- Do not bind port 80 for a sketch HTTP server while using Pulsync — it is reserved for the config portal. Use `enableAP` and another port (for example 8080). Do not call `WiFi.softAP` for a second SoftAP.
