Skip to content

TwiistOff REST bridge — complete protocol reference

Audience: humans and agents who want to drive the TwiistOff bench app (and, through it, a Twiist pump on an off-body saline bench) over HTTP.

This document is canonical for the bridge. It lists every route the debug app serves, with parameters, example request/response bodies, the error shapes, and which routes are safe reads versus dangerous writes. If the code and this document disagree, the code wins — fix this document in the same change.

Implementation: app/src/main/kotlin/com/infusionset/twiistoff/bridge/RestBridge.kt (plus pump/PumpLink.kt for session operations and ble/PumpBleManager.kt for BLE).


1. What this is, and what it is not

  • The bridge is a debug-build-only loopback HTTP server inside TwiistOff. It listens on 127.0.0.1:8090; the phone's adb forwards it to the host: adb forward tcp:8090 tcp:8090. Release builds do not start it at all.
  • It drives real hardware. It is not a simulator, not a medical API, and not stable: routes and fields can change with the app.
  • BENCH ONLY. Never point this at a pump connected to a human being. Saline/water only. See docs home and Bench testing.
  • The protocol it speaks is an independently derived, unofficial understanding of the pump. See What a driver needs for the wire protocol behind these routes.
  • Every route is "dev-only" in the sense that it exists only in debug builds. The dangerous subset is called out per-route and summarised in §4.
  • Release the pump when you stop: POST /disconnect and confirm "state": "DISCONNECTED". Never leave a session armed.

Verification states and the TBD convention

The route reference carries a Danger class (§4) and a verification state. States use the same legend as What a driver needs and the README status board:

Tag Meaning
✅ Verified The route was exercised live against the bench pump (off-body saline) with the expected result.
🟡 Partial Works, but a variant / range / durable effect is not yet confirmed.
🧪 Identified The underlying opcode and payload shape are known but not yet accepted on the bench (the route sends it; verifiedLive:false).
⛔ TBD Not solved; the note says what is missing.

The one thing this bridge cannot do for you (⛔ TBD): it consumes an LTSS you supply to POST /pump/arm; it cannot obtain one. An LTSS is issued at pump registration, which only the vendor's app and service do. Likewise TwiistOff's replacement-blob write follows the pump's framed format but has not yet been bench-tested (§5.9). Everything else below — status, settings, delivery, cassette/prime, clock, history — is driveable once a valid LTSS is armed.


2. Conventions

Request

  • Protocol: HTTP/1.1, one request per connection (Connection: close). No keep-alive.
  • Paths and parameters are case-sensitive. Query values are URL-decoded.
  • POST with a body: input is the raw request body bytes, not form-encoded. A body is only read when Content-Length is present.
  • Hex parameters accept upper- or lowercase digits. Most accept spaces, commas, colons and _ or - separators for readability; continuous hex (e.g. 0000B65A or AA BB 01) is normal. 0x prefixes are tolerated in the parser. Invalid/odd-length hex is a 400 or a routed {"ok": false} depending on the route (documented per route).
  • Characteristic keys (key=): three forms are accepted —
  • the full composite key from GET /gatt, e.g. e5331fe0.../0/e5332018.../0;
  • the full 128-bit UUID, e.g. e5332024-977c-11e5-a837-0800200c9a66;
  • the 8-hex short suffix, e.g. e5332024 (expanded to <suffix>-977c-11e5-a837-0800200c9a66).

Response

  • Always JSON, Content-Type: application/json.
  • HTTP 200 means the request was routed and executed — it does not always mean the operation succeeded. Many operations that reached the pump but failed answer 200 with {"ok": false, "error": "..."}. Always check ok when present.
  • HTTP status codes used: | Code | Meaning | |---|---| | 200 | Routed and executed (check ok/error in the body). | | 400 | Malformed request: missing/unknown parameter, bad hex, unknown characteristic key. | | 404 | No such route. | | 409 | A confirmation is required (/pump/raw-wire without confirm=true) or prerequisite state is missing (e.g. /pump/events before any pumpStatus). | | 410 | POST /command is retired (unsealed pre-crypto frame builder). |
  • Error body shape: {"ok": false, "error": "<human-readable reason>"}. A few routes add context fields (requires, docs, blob, use, …) which are documented per route.
  • Byte fields are uppercase hex strings without 0x (e.g. "B482168D"); opcode fields are "0x"-prefixed lowercase hex (e.g. "0x800b"); *Utc fields are ISO-8601 UTC strings.

Session model (read this before the pump routes)

The pump command channel is sealed (HKDF-SHA256 keys from the per-pump LTSS + session salt, AES-CCM, HMAC auth, CRC — Crypto and transport §3). A session is established with POST /pump/arm (LTSS body required; you must own the pump). Consequences:

  • /pump/command, /pump/command-token, /pump/time, /pump/temp-basal, /pump/temp-basal/stop, /pump/raw-wire, /pump/replacement, the settings writes (/settings/set, /settings/write, /settings/configure, /settings/verify) and the recovery commands (§5.12) require an armed session. Without it they return {"ok": false, "error": "not armed"} or a "saved in the app; not written (not armed)" note (raw-wire: "not armed - raw wire bytes are sealed with the session keys"). The settings reads, export, import and presets work without a pump: they touch only the app's copy.
  • Arming requires ATT MTU 247; arm requests it and fails with a clear error when the granted MTU is not 247. POST /mtu?value=247 requests MTU 247 explicitly.
  • A link drop invalidates the session; reconnect, then arm again.
  • Session state is cleared at every lifecycle boundary. connect, disconnect, reconnect, a link transition and the start of every arm all drop the cached channel/keys, packet counter, message sequence, therapy token and armed flag. A session can therefore never be carried over a link change, and the success response of an arm can never describe a previous session.
  • An arm is only successful once the pump streams a frame sealed with the new session keys. If none decrypts within 8 s the route returns armed:false with "arm handshake not confirmed …" instead of a false positive (this is the fix for a live failure where an app reinstall left the previous BLE link alive and the pump kept serving the old session salt).
  • Connect recycles an inherited link on the first connection after the app process starts. An adb install -r update restarts the process while the pump link is up; the new process can attach to that inherited link, and the pump would keep serving its OLD session (same e5332024 salt). POST /connect therefore establishes, tears down and re-establishes the link once after a process start, so the pump issues a new salt. Later connects in the same process are plain connects. See BLE and session §2 for the bench evidence.
  • "Succeeded" means the pump answered. Confirm the effect in the next pumpStatus broadcast (GET /pump/state.pumpTimeUtc, GET /pump/history, etc.).

3. Quick start

adb forward tcp:8090 tcp:8090
BASE=http://127.0.0.1:8090

curl -s -X POST $BASE/scan/start
sleep 6
curl -s $BASE/devices                       # pick a device with isPumpCandidate == true
curl -s -X POST $BASE/scan/stop
curl -s -X POST "$BASE/connect?address=AA:BB:CC:DD:EE:FF"
# first-time pairing (see pairing.md): the pump refuses a protected operation until bonded, so
#   POST /subscribe-all  (or POST /bond/start) starts pairing, then supply the label PIN:
# curl -s -X POST "$BASE/pin?value=NNNNNN"
curl -s -X POST "$BASE/mtu?value=247"       # must report granted 247
curl -s -X POST --data "$LTSS" "$BASE/pump/arm?respond=false"
curl -s $BASE/setup                         # read-only checklist + next action
curl -s $BASE/pump/ready                    # confirm live status decode
curl -s -X POST $BASE/disconnect            # ALWAYS release the pump when done

LTSS is the per-unit registration secret (hex, 16 or 32 bytes). Do not put it in a script, a log or a commit; pass it from the environment.


4. Route index and danger classification

All routes are debug-only. The Danger column is about what the route can do to a connected pump:

Danger Meaning
READ Read-only for the pump/link; no pump command is sent (subscribing changes CCCDs only).
LOW Changes host/BLE state, not pump state.
MED Sends sealed commands that change pump settings/clock, or can disturb the link.
HIGH Can start/stop delivery, rewrite provisioning data, or write arbitrary sealed bytes.
Route Danger Notes
GET / READ Route index (also lists retired routes).
GET /status READ Link state, address, MTU, subscriptions, the automatic reconnect (reconnect), the Android permissions still missing (permissionsMissing) and the untested-firmware warning (firmwareWarning).
GET /permissions READ Each Android permission the app needs, granted or not, and how the app fixes it; the data folder. No pump I/O.
POST /permissions/test-notification LOW Posts a test notification.
GET /files, GET /files/get?path=&tailBytes= READ The data folder's files (logs/, exports/) and one file's text.
POST /files/copy LOW Copies logs/ and exports/ to the folder chosen in the app.
GET /devices READ Scan results.
GET /setup[?blob=] READ Live pairing/setup snapshot: stages + ordering gates + next action + live pump fields + last driver (same state machine as the Connect page and cassette set-up wizard); optional blob review. Never returns the blob/LTSS.
POST /setup/reconnect[?wait=true\|cancel=true] MED Reconnect and re-arm the remembered pump with the stored key: the start-up reconnect, on demand. Link set-up only; nothing that changes delivery or settings. cancel=true stops a run or a pending retry.
POST /setup/auto-reconnect?enabled=, POST /setup/forget-pump LOW Turn the start-up reconnect on or off; forget the remembered pump (the key and the bond stay). App only.
POST /setup/scan, /setup/connect?address=, /setup/bond?pin=, /setup/arm[?ltss=] LOW/MED Stage actions: scan, connect, bond with the label PIN, arm with the LTSS. Return the new snapshot; refuse out of order (409).
POST /setup/blob?blob=&confirm= LOW Validates and (with confirm=true) persists the operator's replacement blob in the app; no pump I/O.
POST /setup/write-blob?confirm=true HIGH Writes the stored provisioning blob to e5332027; needs an armed session + two-step confirm.
POST /setup/selfcheck, /setup/fill?units=, /setup/prime, /setup/stop-prime, /setup/prime-complete, /setup/configure, /setup/verify, /setup/basal[?rate=&setPattern=], /setup/cannula-fill?units=, /setup/stop-cannula-fill MED–HIGH Cassette set-up stages (passive self-test; fill; prime; stop + complete; configure all 20 settings; verify; verify + start basal; optional cannula fill/stop). Identical semantics to the cassette set-up wizard; ordering enforced server-side. prime, basal and cannula-fill are delivery-affecting.
POST /setup/new-cassette LOW Starts a new-cassette set-up in the app (fill and prime required again); no pump I/O.
GET /settings, GET /settings/export READ The app's stored therapy settings (all 20, value + wire bytes + "unwritten" flag + whether the pump is known to hold it, the verify record, last writes); the export JSON. No pump I/O.
POST /settings/import, POST /settings/preset?name= LOW Replace the app's settings from an export or a preset (defaults, bench-replay). App only; nothing is written to the pump.
POST /settings/set, POST /settings/write?setting=\|all=true, POST /settings/configure MED Store and write changed settings / write stored ones / write all 20 (Configure), then re-verify. Settings include the basal pattern and the closed loop. While basal runs the delivery limits are not sent (see below).
POST /settings/write-limits MED Change delivery limits: with basal stopped, write the delivery limits and every unwritten setting, then re-verify. Refused while basal runs.
POST /settings/verify (= /setup/verify) READ verifyTherapySettings 0x800F with the app's record (read-only for the pump).
GET /pump/conditions READ Active pump conditions and, per kind of command, allowed or the refusal (the delivery gate's table).
GET /recovery[?kind=], POST /recovery/begin?kind=, POST /recovery/choice READ / LOW A recovery wizard's plan from the live state; start a wizard; record "same cassette?" / "line fixed?". App only.
POST /pump/stop-basal, POST /pump/resume-basal HIGH stopBasal 0x8103 (also ends a running temp basal, and stops a running bolus with alert 409-0003 Interrupted Bolus); verify + startBasal 0x8100 from the stored settings (the pattern; a stopped temp basal does not come back).
POST /pump/silence, POST /pump/clear-alert?mask=, POST /pump/clear-notice?mask= MED silenceAlarms 0x0700 (not yet sent on the bench); clearPumpAlert 0x0400 / clearPumpNotice 0x0402 with a bit mask.
POST /pump/battery-change, POST /pump/cassette-change HIGH batteryChange 0x8805 (refused, nothing sent, below RIS messages 13.54) / cassetteChange 0x8804; refused while basal runs.
POST /pump/cassette-volume?units= MED adjustStartingCassetteVolume 0x8002.
POST /pump/rearm MED Re-arm on the existing link with the stored key, then prove the command path.
POST /pump/calculator-bolus?units=&bg=&carbs= HIGH Bench: a calculator bolus with an optional BG (mg/dL) and carbs (g), sent once: 0x8400 with a BG, 0x8401 when carbs are given. The pump sets the bolus category (BG only 3, carbs only 2, both 4) and logs 0x0082 / 0x007E; these also feed the pump's own loop. Gated like a bolus; the amount must be at least 0.05 U (the pump's smallest bolus) and not above the stored max bolus. UI: Advanced → Pump tools.
POST /scan/start LOW Starts a BLE scan.
POST /scan/stop LOW Stops scanning.
POST /connect?address= LOW Connects; bonding may start.
POST /connect-pump LOW Scan-and-connect convenience.
POST /disconnect LOW Releases the link. Do this when you stop.
POST /reconnect LOW Reconnect to the same address.
POST /mtu?value=N LOW Requests ATT MTU; returns the granted value. 247 required by the pump.
GET /gatt READ Services and characteristics.
GET /read?key= READ GATT read. Some characteristics (e.g. e5332027) are refused by the pump.
POST /write?key= HIGH Raw GATT write to any writable characteristic. Can write arbitrary sealed bytes or provisioning data.
POST /subscribe?key= / POST /unsubscribe?key= / POST /subscribe-all LOW CCCD changes; may trigger bonding.
GET /bond READ Bond state and stored-PIN flag.
POST /pin?value= LOW Supplies the pump label PIN to Android (secret — do not log).
POST /bond/start?address= / POST /bond/forget?address= MED Pairing / bond removal. Forget can strand a pump until re-paired.
GET /notifications?limit= READ Ring buffer of received notifications.
GET /pump/observed?limit=&pushes= READ Observe-first log: per-characteristic / per-opcode counts and intervals, labelled frames (response, NACK, mismatch, unsolicited, undecryptable), status transitions, decoded loopStatus/cgmStatus. No pump I/O.
POST /pump/observed/clear LOW Clears the observation rings and counters (host state only).
GET /pump/state READ Session state — contains sessionSalt (secret material for the session log).
GET /pump/ready READ Fresh status summary; canDeliver (0x0040, configured, no alarm, path ok) vs isDelivering (basal running, from therapyState); firmwareWarning on untested firmware.
GET /pump/activity READ The app's activity line: commands running now, recent results, and the last failure in plain words (the alert the phone shows). No pump I/O.
POST /pump/arm MED Establishes the crypto session; LTSS in the body or, empty body, the stored one; MTU 247.
POST /pump/command HIGH Sealed arbitrary opcode/payload, no therapy prefix. Delivery opcodes are reachable.
POST /pump/command-token HIGH Same, with the therapy number prefixed (settings/delivery family). Sent once; never auto-resent.
POST /pump/alarm-reset HIGH alarmReset 0x0D00 + therapy number; only while status byte 90 = 1. Reboots the pump; the session re-arms automatically.
POST /pump/stop-cannula-fill HIGH Sends 0x8202 stopCannulaFillBolus (Therapy) to stop a running cannula fill. Not yet bench-verified.
POST /pump/temp-basal?rate=&duration= / ?percent=&duration= HIGH temporaryOverrideBasal 0x8102: absolute U/h temporary basal for N minutes, or temporaryModifyBasal 0x8101: 0–200 % of the basal pattern. Both verified live. Delivery-affecting.
POST /pump/temp-basal/stop HIGH stopTempBasal 0x8104: cancels a running temp basal. Verified live 2026-11-30. The safety stop for the route above.
POST /pump/time MED setTime 0x800B: changes the pump clock.
POST /pump/replacement HIGH Provisioning credential write (608-610-byte blob). Can de-provision. Two-step confirm.
POST /pump/registration-handshake HIGH Pairing-mode registration sequence in one call (read SRI → read the stored blob → write → read back) on one notify subscription, after a settled bond. Body = blob hex. Two-step confirm.
GET /pump/replacement/readback LOW Read-only readback of the stored blob via e5332027 notifications; compares vs the written/reviewed blob, shows size, SHA-256 and expiry.
POST /pump/raw-wire HIGH Writes fully pre-sealed wire bytes verbatim (counter replay / transport experiments). Two-step confirm.
GET /pump/events?start=&count= READ Reads pump log records (getLogRecord 0x0502) — sends a read command.
GET /pump/history?limit= READ Locally cached status samples (no pump traffic).
POST /command RETIRED Returns HTTP 410. Built an unsealed pre-crypto frame.

5. Route reference

Each entry gives: method + path, parameters, what it does, example request, example response, and error behaviour. Example values use a placeholder pump; hex is illustrative.

5.1 Meta

GET /

Route index. Includes a note pointing here and the current route list (including the retired POST /command marked [410 Gone]).

curl -s http://127.0.0.1:8090/
{
  "service": "twiistoff-rest",
  "note": "Debug-build-only loopback bridge. Full request/response reference: docs/rest-api.md",
  "routes": ["GET /", "GET /status", "...", "POST /command  [410 Gone - unsealed pre-crypto frame]"]
}

Errors: none.

GET /status

Current BLE link state and subscription set. mtu is the last negotiated value (or null until requested).

curl -s http://127.0.0.1:8090/status
{
  "state": "CONNECTED",
  "address": "AA:BB:CC:DD:EE:FF",
  "name": "00000000M",
  "mtu": 247,
  "error": null,
  "subscribed": ["e5331fe0.../0/e5332018.../0", "e5331fe0.../0/e533201c.../0"],
  "reconnect": { "enabled": true, "phase": "READY", "...": "see POST /setup/reconnect" },
  "permissionsMissing": [],
  "firmwareWarning": null
}

firmwareWarning is null on the tested pump firmware (RIS messages 13.76 / events 14.32) and while the version is not yet read; on any other firmware it reads e.g. "untested pump firmware 13.53 / 14.09 (tested: 13.76 / 14.32)". It blocks nothing.

state ∈ DISCONNECTED, CONNECTING, CONNECTED, DISCONNECTING. reconnect is the automatic reconnect's state, the same object GET /setup and POST /setup/reconnect return. permissionsMissing names the Android permissions still missing (§5.14); empty when all are allowed.

GET /devices

All scan results seen since POST /scan/start, strongest signal first. isPumpCandidate is the app's detection heuristic (serial-shaped name like 00000000M and/or manufacturer data under company ID 0x026B). mfg is the raw manufacturer payload after the company ID, hex.

{
  "devices": [
    {"address": "AA:BB:CC:DD:EE:FF", "name": "00000000M", "rssi": -54,
     "isPumpCandidate": true, "mfg": "01140200"}
  ]
}

POST /scan/start, POST /scan/stop

Start/stop the BLE scan. start clears the previous device list. A scan is for pairing: a connected pump does not advertise, and a bonded pump needs no scan (connect to its remembered address, or POST /setup/reconnect). An empty scan during pairing usually means the pump is not in pairing mode yet.

{"ok": true}

POST /connect?address=AA:BB:CC:DD:EE:FF

Connect and wait until the link is CONNECTED. Responds with the GET /status body plus ok (true when connected) and a note. It first clears every piece of cached session material (a new connection is a new protocol session), and on the first connection after the app process started it recycles the inherited BLE link (establish → tear down → establish): an adb install -r update restarts the process under a live pump link, and attaching to that inherited link would let the pump keep serving the previous session (same salt). Bonding (LE Secure Connections Passkey Entry) is handled by BondManager; use POST /pin or Android's system dialog for the label PIN.

{"state": "CONNECTED", "address": "AA:BB:CC:DD:EE:FF", "name": "00000000M", "mtu": null,
 "error": null, "subscribed": [], "ok": true,
 "note": "CONNECTED; the first connect after an app restart recycles any BLE link inherited from the previous process so the pump issues fresh session material - arm next"}
  • 400 {"ok":false,"error":"address required"} when the parameter is missing.
  • Returns only after the link reports CONNECTED (or ok:false after a timeout); GATT discovery continues in the background, so an immediate arm may still answer "GATT not ready" for a moment.
  • If a reconnect after a link drop fails, the route re-resolves the pump's rotating private address with one scan and retries that address once.

POST /connect-pump

Convenience for scripts: starts a scan, waits up to 12 s for the first isPumpCandidate, stops the scan, resets session state, connects (with the same inherited-link recycle as /connect).

{"ok": true, "address": "AA:BB:CC:DD:EE:FF", "name": "00000000M"}

Error: {"ok": false, "error": "no pump found in scan"}.

POST /disconnect, POST /reconnect

Release the link / reconnect to the last address. disconnect clears subscriptions and all cached session state (channel/keys, counters, token, armed), then tears the link down. Call /disconnect when you finish; confirm GET /status.state == "DISCONNECTED".

reconnect needs a current address, resets session state, then reconnects with the same fresh-link handling as /connect and answers the status body plus ok. It only reconnects the link; to reconnect and re-arm the remembered pump, use POST /setup/reconnect.

disconnect also stops a running automatic reconnect and any pending retry.

{"ok": true}

POST /mtu?value=N

Requests ATT MTU N (valid range 23–517) from the connected device and returns the granted value. The pump command channel requires 247: at a lower MTU the arm write is ignored and the pump never streams.

curl -s -X POST "http://127.0.0.1:8090/mtu?value=247"
{"ok": true, "requested": 247, "granted": 247, "requiredForPump": 247, "commandChannelUsable": true}

On failure the request still answers 200 with the reason:

{"ok": false, "requested": 247, "granted": null,
 "error": "MTU request failed: not connected",
 "hint": "connect first; Android can refuse or lower the request (the pump link needs 247)"}
  • 400 when value is missing, not an integer, or outside 23–517.
  • PumpLink.arm also requests MTU 247 itself and fails loudly unless 247 is granted; this route is the explicit request, for a client that wants the MTU settled before arming.

GET /setup[?blob=HEX]

Live pairing/setup snapshot — the machine-readable twin of the Connect page and the cassette set-up wizard. One pure state machine (pump/PairingFlow.kt, unit-tested by PairingFlowTest) produces the stage order, states, next action and per-action ordering gates for both the UI and this bridge, so they can never disagree. Read-only; works disconnected; safe to poll in an automation loop.

The stages, in order (see Pairing and setup §3):

PUMP_PAIRING_MODE -> CONNECT -> BOND -> REGISTRATION (external: the vendor's app and service)
  -> ARM -> SELF_CHECK -> DECLARE_FILL -> PRIME -> STOP_PRIME -> CONFIGURE -> START_BASAL
  -> CANNULA_FILL (optional) -> READY

Per stage: state = DONE / NEXT (the operator's next action) / BLOCKED (a required input or external step is missing; reason in detail/blockedReason) / TODO. optional steps never block completion; external steps (only REGISTRATION) cannot be executed here and never block the BLE stages — the reason points at the vendor's registration. Nothing secret is returned: only ltssStored/ltssValid/blobStored and blob metadata.

The cassette stages read the pump's own state, so the snapshot shows where the pump actually is after an app restart or a re-arm: a primed cassette (pumpState bit 0x0010) counts as filled and primed, and configurationState 0x1FFF with no 00 verify counts as configured. A new-cassette set-up (POST /setup/new-cassette) switches that off, so fill and prime are required again.

actions is the ordering authority: each drivable action with allowed, alreadyDone, its stage, and the reason. A caller can check actions.SCAN.allowed etc. instead of guessing.

curl -s "http://127.0.0.1:8090/setup"                          # metadata for the stored blob, if any
curl -s "http://127.0.0.1:8090/setup?blob=$(cat blob.hex)"     # review a candidate blob, still read-only
{
  "connected": false, "address": null, "name": null,
  "bondState": null, "bonded": false, "bonding": false, "mtu": null,
  "armed": false, "pumpStatusSeen": false,
  "ltssStored": true, "ltssValid": true, "blobStored": false,
  "stage": "PUMP_PAIRING_MODE", "stageIndex": 0, "stageCount": 13,
  "progress": "0/11",
  "complete": false,
  "blockedReason": null,
  "nextAction": "Put the pump into pairing mode (physical reset): remove the cassette, then remove/reinsert the battery …",
  "stages": [
    {"id": "PUMP_PAIRING_MODE", "title": "Physically reset the pump into pairing mode", "state": "NEXT", "detail": "…", "optional": false, "external": false},
    {"id": "CONNECT", "title": "Scan for the pump and connect", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "BOND", "title": "Bond with the label PIN", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "REGISTRATION", "title": "Registration / replacement blob (…)", "state": "BLOCKED", "detail": "External step — cannot be done by TwiistOff …", "optional": false, "external": true},
    {"id": "ARM", "title": "Arm the channel with the pump's LTSS", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "SELF_CHECK", "title": "Attach the cassette (pump self-test)", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "DECLARE_FILL", "title": "Fill: declare the cassette volume", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "PRIME", "title": "Prime", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "STOP_PRIME", "title": "Drops - stop, then prime complete", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "CONFIGURE", "title": "Configure pump", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "START_BASAL", "title": "Verify and start basal", "state": "TODO", "detail": "…", "optional": false, "external": false},
    {"id": "CANNULA_FILL", "title": "Fill Cannula (optional)", "state": "TODO", "detail": "…", "optional": true, "external": false},
    {"id": "READY", "title": "Ready", "state": "TODO", "detail": "…", "optional": false, "external": false}
  ],
  "actions": {
    "SCAN": {"stage": "CONNECT", "allowed": true, "alreadyDone": false, "reason": "…"},
    "ARM": {"stage": "ARM", "allowed": false, "alreadyDone": false, "reason": "blocked by earlier stage CONNECT: …"},
    "REGISTRATION": {"stage": "REGISTRATION", "allowed": false, "alreadyDone": false, "reason": "external step: …"},
    "SELF_CHECK": {"stage": "SELF_CHECK", "allowed": false, "alreadyDone": false, "reason": "not armed - self-check is observed from the sealed status stream"},
    "WRITE_BLOB": {"stage": "ARM", "allowed": false, "alreadyDone": false, "reason": "no valid blob stored - POST /setup/blob?confirm=true first"}
  },
  "pump": {
    "pumpState": null, "pumpStateHex": null,
    "selfTestPercent": null, "primingStatus": null, "primingName": null,
    "basalRateUe2": null, "cassetteVolumeUe2": null, "battery": null,
    "latestTherapyEvent": null, "armed": false, "sessionSaltPresent": false, "pumpStatusSeen": false
  },
  "bond": {"pendingPasskeyRequest": false, "inAppPasskey": true, "hasStoredPin": true},
  "devices": [{"address": "AA:BB:CC:DD:EE:FF", "name": "SERIALXXXXX", "rssi": -55, "isPumpCandidate": true}],
  "driver": {"lastAction": "scan", "lastSource": "rest", "lastResult": "scan started; …", "lastAtMs": 1796089702382},
  "autoReconnectEnabled": true,
  "reconnect": {"enabled": true, "offReason": null, "rememberedPump": null, "phase": "NO_PREVIOUS_SESSION", "…": "see POST /setup/reconnect"},
  "import": {
    "blob": "POST /setup/blob?blob=<608-610-byte hex>&confirm=true",
    "ltss": "POST /setup/arm  (body or ?ltss= = LTSS hex, 16 or 32 bytes)",
    "note": "The blob and the LTSS come from registering the pump, outside TwiistOff. … No route returns either value."
  },
  "provisioning": {
    "readiness": "NO_BLOB",
    "title": "Optional: write a replacement / provisioning blob",
    "detail": "…",
    "canWriteNow": false,
    "steps": ["1. Pump in pairing mode …", "2. Connect and bond …", "3. Write the reviewed 608-610-byte blob …", "4. Arm with the LTSS …", "5. Do not assume adoption …"]
  },
  "note": "snapshot only: this GET never writes. Use the POST /setup/* stage actions, which return this same snapshot after each step; ordering is enforced by the state machine (409 with a \"blocked at <STAGE>\" error)."
}
  • wizardStep / wizardStepCount: the wizard step number the snapshot corresponds to (1..11), so a script can mirror exactly what the phone shows. registration.detectedState / registration.acknowledged: the registration-pause state (from the read-only stored-blob probe). therapyVerifyMismatch: true after a 00 verify (configure or import before starting basal). pump.primeVolumeUe2: live prime volume (pumpStatus bytes 80-81).
  • stage / stageIndex / stageCount / progress: where you are, and how many required stages are done (external/optional stages excluded from the count).
  • driver.lastAction/lastSource: which stage last ran and whether the Setup UI (ui) or the REST bridge (rest) ran it. The UI is a peer driver, not a wrapper.
  • provisioning.blob is present when either ?blob= was passed ("source":"request") or a blob is stored ("source":"stored"); a request blob takes precedence for that call (GET never overwrites the stored blob). readiness is one of NO_BLOB, INVALID_BLOB, NEEDS_BOND, NEEDS_ARM, READY_ARMED, READY_PAIRING_MODE_EXPECTED.

The full procedure (physical pump steps, registration boundary, copy-paste REST script) is Pairing and setup.

POST /setup/blob?blob=HEX[&confirm=true]

Two-step confirm, local only. Validates a replacement/provisioning blob and — with confirm=true — persists it in the app so the Setup screen can review and write it later without the bridge. It does not touch the pump; the pump write is still POST /pump/replacement (armed) or the Setup screen's two-step confirm. The body may carry the hex instead of ?blob=.

Step 1 — preview (nothing stored):

curl -s -X POST "http://127.0.0.1:8090/setup/blob?blob=$(cat blob.hex)"
{
  "ok": true, "stage": "preview", "stored": false, "requires": "confirm=true",
  "blob": {"valid": true, "size": 609, "expectedSize": "608-610",
           "sha256": "<sha256 hex>", "chunks": [244, 244, 128],
           "signatureBytes": 71, "derSignatureOk": true,
           "expirationUtc": "2027-01-01T00:00:00Z"},
  "note": "preview only - repeat with confirm=true to save the blob in the app. Saving does NOT touch the pump; …"
}

Step 2 — store (app-local; response metadata only, the blob is never echoed back):

curl -s -X POST "http://127.0.0.1:8090/setup/blob?blob=$(cat blob.hex)&confirm=true"
# -> {"ok":true,"stage":"stored","stored":true,"blob":{ …same metadata… },"note":"saved locally …"}

Errors:

  • 400 for missing/non-hex input or a size outside 608-610 (the body includes the parsed blob info with the real size).
  • POST /setup/blob with no blob parameter and an empty body → 400 blob required.
  • Clear the stored blob with POST /setup/blob?clear=true (or the Clear saved blob button on the Setup screen):
curl -s -X POST "http://127.0.0.1:8090/setup/blob?clear=true"
# -> {"ok":true,"cleared":true,"blobStored":false}

The stored value is secret-class material: never commit it, never put it in a public issue, and no route returns it.

POST /setup/reconnect[?wait=true|cancel=true] — reconnect and re-arm the remembered pump

The same run the app makes by itself at start-up when it has a previous session (a remembered pump and a stored key), started on demand; the Reconnect button on Connect (Previous session) and the reconnect banner call it too. A run goes through SetupRunner, the path the Connect page and the /setup/* stage routes take, recorded under the driver auto:

  1. Connect to the remembered pump (skipped when already connected): the bonded device with the remembered address, else the bonded device with the remembered name, else the remembered address; a short scan only if that connect fails, taking only a candidate that advertises the remembered name. The connect reports success once the GATT services are discovered.
  2. Registration: records "already registered" for the link (local, no pump I/O).
  3. Arm with the stored key; the arm requests MTU 247 once. When the link is already up and armed, this step is skipped only if the command path is not held: with the path held (a restart, an unanswered command, REARM_FAILED) it re-arms on the same link and proves the path, as POST /pump/rearm does. A link that is up is not "ready" while the pump does not answer commands.
  4. First status: waits up to 10 s for a decoded pumpStatus.
  5. Command path: when no command has been answered on the session yet, one read-only getLogRecord must be answered (unanswered: the app re-arms once more by itself and checks again).
  6. Readiness: the GET /pump/ready verdict, e.g. CAN DELIVER; delivering basal 2.00 U/h.

It sends nothing that changes delivery or settings: a running basal, a temp basal or an alarm is observed, never touched. A failed attempt is followed by a wait of 20 s, 60 s, then 180 s; after 4 attempts the run stops with phase FAILED and the reason. A re-arm or path check that ends with the pump still not answering stops the run at once (phase FAILED, "the pump does not answer commands: …"): another try would only stack arms on the same link. If the first status shows the pump unconfigured or unprimed, needsSetUp is true and the app hands over to the cassette set-up wizard.

Invalid state. A run that finds the pump no longer matching the stored session stops at once with phase STOPPED_INVALID, turns the start-up reconnect off and keeps the reason in reconnect.offReason: Android holds no bond with the pump or the pump asks to pair again (pairing mode, reset, paired elsewhere), a GATT insufficient authentication / encryption refusal, no valid key, or an arm that gets no status sealed with the stored key on two attempts in a row. It also declines a pending pairing request and drops the link, so a fresh pairing can go ahead. Out of range, a connect timeout or a link drop are retried with the back-off and never change the setting.

  • A run already in progress is left alone ("result":"a reconnect is already running (…)"); a pending retry is cut short and a fresh run starts.
  • wait=true answers when the attempt ends (ready, failed, or the first retry wait), at most 120 s.
  • cancel=true stops a run or a pending retry (phase CANCELLED).
  • With no remembered pump or no stored key: 409, phase NO_PREVIOUS_SESSION.
  • The start-up setting does not apply here: an on-demand run works with it off.
  • A manual scan, connect or bond (/setup/scan, /setup/connect, /setup/bond, /scan/start, /connect, /connect-pump, /bond/start) stops a run in progress (phase CANCELLED); the setting is unchanged.
curl -s -X POST "http://127.0.0.1:8090/setup/reconnect?wait=true"
{
  "ok": true,
  "action": "reconnect",
  "result": "reconnect started (rest)",
  "reconnect": {
    "enabled": true,
    "rememberedPump": { "address": "AA:BB:CC:DD:EE:FF", "name": "00000000M" },
    "phase": "READY",
    "phaseLabel": "Reconnected and armed",
    "running": false,
    "trigger": "rest",
    "attempt": 1,
    "maxAttempts": 4,
    "stage": null,
    "stages": [
      { "id": "CONNECT", "title": "Connect to the remembered pump", "state": "DONE" },
      { "id": "REGISTRATION", "title": "Registration: already registered", "state": "DONE" },
      { "id": "ARM", "title": "Arm with the stored key (MTU 247)", "state": "DONE" },
      { "id": "STATUS", "title": "First pump status", "state": "DONE" },
      { "id": "READY", "title": "Readiness", "state": "DONE" }
    ],
    "detail": "Reconnected and armed: CAN DELIVER; delivering basal 2.00 U/h",
    "lastError": null,
    "nextAttemptInMs": null,
    "verdict": "CAN DELIVER; delivering basal 2.00 U/h",
    "needsSetUp": false
  },
  "snapshot": { "...": "GET /setup" }
}

phase ∈ IDLE, OFF (start-up setting off), NO_PREVIOUS_SESSION, CONNECTING, REGISTRATION, ARMING, AWAITING_STATUS, BACKING_OFF (waiting nextAttemptInMs before the next try), READY, FAILED, STOPPED_INVALID (turned itself off; see above), CANCELLED. Stage state ∈ DONE, NOW, PENDING. offReason is why the start-up reconnect turned itself off (null otherwise). The key is never returned.

POST /setup/auto-reconnect?enabled=true|false, POST /setup/forget-pump

auto-reconnect turns the start-up reconnect on or off (on by default; the Reconnect at start-up switch on Connect and on the Menu). Turning it off also stops a running reconnect; either value clears offReason. Use enabled=false before a test that needs the link to stay down after an app restart. GET /setup shows the setting as autoReconnectEnabled (and reconnect.enabled). forget-pump forgets the remembered pump (the Forget this pump button): the app stops reconnecting to it by itself. The stored key and Android's bond stay; arming once (on Connect or POST /setup/arm) remembers the pump again. Both are app-only and answer {"ok":true, …, "reconnect":{…}}.

POST /setup/<stage> — stage actions (identical semantics to the cassette set-up wizard)

Every drivable stage has a bridge action that calls the same SetupRunner method as the Connect page or cassette set-up wizard control (the UI passes source ui, the bridge rest), with the same ordering gates from PairingFlow. Each action responds with the new GET /setup snapshot, so a script can chain steps and inspect state after every one:

{"ok": true, "action": "fill", "result": "fill declared: 300.00 U (0x8003, wire 30 75); …", "snapshot": { … }}

Out-of-order actions are refused server-side with HTTP 409 and the blocked reason (nothing is sent to the pump):

{"ok": false, "action": "fill", "error": "blocked at CONNECT: blocked by earlier stage CONNECT: …", "snapshot": { … }}

Re-running a stage that is already DONE is a safe no-op (200, result: "already …"). Stop actions are the exception to ordering: stop-cannula-fill is allowed whenever the session is armed (safety path, one tap — like the delivery STOP buttons).

Action Request What it sends/does Gate
scan POST /setup/scan starts a BLE scan (async; poll GET /setup.devices) not connected
connect POST /setup/connect?address=AA:BB:CC:DD:EE:FF connect (address optional → first candidate from a scan) not connected
bond POST /setup/bond?pin=NNNNNN (body also accepted) supplies/stores the label PIN and starts/finishes bonding connected, not bonded
registration (detect) POST /setup/registration?detect=true read-only probe of the stored blob on e5332027 (packet-255 status): 0x00 registered, 0x09/0x0A fresh connected + bonded
registration (ack) POST /setup/registration?ack=true&registered=true\|false records the operator choice for the paused registration step (never silently skipped) connected + bonded
arm POST /setup/arm body or ?ltss= = LTSS hex saves LTSS, arms the sealed session (MTU 247, salt/startSeq, handshake) bonded + valid LTSS
blob POST /setup/blob?blob=HEX[&confirm=true] validate (preview) / persist the replacement blob locally (?clear=true clears) always (no pump I/O)
write-blob POST /setup/write-blob?confirm=true writes the stored blob to e5332027 as packet-numbered writes with its CRC32 (two-step confirm) armed + valid blob
selfcheck POST /setup/selfcheck observes pumpStatus byte 15 until 100 % (≤15 s); sends no command armed
fill POST /setup/fill?units=300 (or ?volumeUe2=30000; default 300 U) resetPrime 0x8903 then setStartingCassetteVolume 0x8003; the pump will show 10 U less cassette attached and self-tested
prime POST /setup/prime startCassettePrime 0x8900; after a stop that did not complete the prime, the same route primes more fill declared
stop-prime POST /setup/stop-prime stopPrime 0x8901 (the pump stops priming) the pump is priming (whoever started it)
prime-complete POST /setup/prime-complete primeComplete 0x8902 — send only after the operator confirms drops formed prime stopped at priming state 3 (minimum volume met); refused at state 1 ("prime more")
configure POST /setup/configure (= POST /settings/configure) writes the app's stored settings, all 20, then verifies; response as in §5.11 armed, status seen, not in cassette-change mode, not priming
verify POST /setup/verify (= POST /settings/verify) verifyTherapySettings 0x800F with the app's 42-byte record (read-only) armed
basal POST /setup/basal[?rate=2.0[&setPattern=true]] verifyTherapySettings 0x800F must answer 01, then startBasal 0x8100. A rate that differs from the stored basal pattern is refused unless setPattern=true: then the pattern is first set to that rate all day and written (0x8019), and only then verified and started prime complete, pump configured, verify not 00
cannula-fill POST /setup/cannula-fill?units=0.7 (or volumeUe2=70) startCannulaFill 0x820A (token + u16 volume + reason 0); max 0.70 U (more is refused 0x13EE) basal started
stop-cannula-fill POST /setup/stop-cannula-fill stopCannulaFillBolus 0x8202 armed (safety stop)
new-cassette POST /setup/new-cassette app only: starts a new-cassette set-up, so fill and prime are required even if the pump still reports an old prime always

Besides the ordering gate, fill, prime, configure, basal and cannula-fill are refused with the first blocking pump condition (GET /pump/conditions), for example "start basal refused: The pump's closed loop is ON: … Turn the loop off …".

Notes:

  • units is a decimal U value (units=300, units=0.7); volumeUe2 is hundredths of a unit.
  • selfcheck is passive: the pump-driven self-test starts when the cassette is attached and shows as pumpStatus byte 15 ramping 10→100 % in ~11.5 s with pumpState 0x0009 during and 0x0029 at completion (no separate notification exists).
  • fill/prime/stop-prime/prime-complete and the 20 configure writes were walked end to end from TwiistOff on the bench on 2026-12-02. prime, basal and cannula-fill are delivery-affecting.

curl -s -X POST "http://127.0.0.1:8090/setup/basal?rate=1.5"
# -> 200 {"ok":false,"action":"basal","error":"rate 1.50 U/h is not this app's basal pattern (2.00 U/h all day);
#         confirm setting the pattern to 1.50 U/h all day (setPattern=true), or edit the basal pattern in Settings", …}
curl -s -X POST "http://127.0.0.1:8090/setup/basal?rate=1.5&setPattern=true"
# -> 200 {"ok":true,"action":"basal","result":"verify=01; startBasal accepted (0x8100); confirm the basal rate in the next status", …}
- Registration is not a POST action: it happens in the vendor's app and service and is surfaced as an external BLOCKED stage in the snapshot (see Pairing and setup §7).

A full chained example is in Pairing and setup §6.

5.3 GATT

GET /gatt

Full discovered service/characteristic tree. key is the canonical composite key to use in key= parameters.

{
  "services": [
    {"service": "e5331fe0-977c-11e5-a837-0800200c9a66", "name": "Twiist custom",
     "characteristics": [
       {"key": "e5331fe0-.../0/e5332018-.../0", "uuid": "e5332018-977c-11e5-a837-0800200c9a66",
        "name": "command", "canRead": false, "canWrite": false,
        "canWriteNoResponse": true, "canNotify": false, "canIndicate": false}
     ]}
  ]
}

GET /read?key=K

GATT read, returns {"key": "<composite key>", "hex": "<bytes>"}. Read refusals (e.g. e5332027, or any characteristic needing authentication before bonding) are routed errors:

  • 400 {"ok":false,"error":"unknown key"} — key did not resolve against the GATT tree.
  • 200 {"ok":false,"error":"GATT status 5 (0x05) (insufficient authentication: bonding required) during ReadCharacteristic"}.

POST /write?key=K[&resp=true]

Raw GATT write. Body = hex payload. resp defaults to true (write with response); the body is sent with WRITE_TYPE_NO_RESPONSE when resp=false. Returns the value the stack echoed back:

{"ok": true, "key": "e5331fe0-.../0/e5332018-.../0", "echo": "01"}
  • 400 for unknown key or non-hex body.
  • 200 {"ok":false,"error":"GATT status 133 (0x85) ... during WriteCharacteristic"} for a failed write.
  • DANGER (HIGH): this can write arbitrary bytes to any writable characteristic, including the sealed command channel e5332018 and the provisioning characteristic e5332027. Prefer /pump/command (sealed) or /pump/raw-wire (confirmed, armed-session-gated) for those.

POST /subscribe?key=K, POST /unsubscribe?key=K, POST /subscribe-all

Enable/disable notifications/indications. subscribe-all enables every notify/indicate characteristic the pump exposes (this is also what arming does). Subscribing to protected characteristics can trigger bonding; when the CCCD write returns "insufficient authentication" the app records it and retries once after bonding.

{"ok": true}

5.4 Bonding

GET /bond

{
  "address": "AA:BB:CC:DD:EE:FF",
  "bondState": 12,
  "bondConfirmed": true,
  "hasStoredPin": true,
  "inAppPasskey": true,
  "pendingPasskeyRequest": false,
  "bondedDevices": ["AA:BB:CC:DD:EE:FF"]
}

bondState is Android's BluetoothDevice.BOND_* constant (10 none, 11 bonding, 12 bonded). bondConfirmed is stricter: when this app session started the bond, it is true only after Android's BONDED broadcast (the raw state can read 12 seconds earlier); an existing bond counts as confirmed. hasStoredPin says whether the app remembers the label PIN locally; the PIN itself is never returned by this route.

POST /pin?value=NNNNNN

Stores the 6-digit pump label PIN and, if Android currently has a pending passkey request, submits it. pending reports whether a request was waiting.

{"ok": true, "pending": true}

Secret: do not log or commit PINs.

POST /bond/start?address=A, POST /bond/forget?address=A

Start pairing / remove the bond on the host. address defaults to the connected address. forget deletes Android's link keys for the pump; the pump may then need to be unpaired elsewhere before it will bond again.

{"ok": true}

5.5 Notifications

GET /notifications?limit=N

Ring buffer of the last ≤200 notifications received on subscribed characteristics (limit default 50, clamped 1–200, newest last). decoded is the app's status codec label; for sealed pump frames it is Unknown(<hex>) — use GET /pump/state/GET /pump/ready for decoded status.

{
  "notifications": [
    {"key": "e5331fe0-.../0/e533201c-.../0",
     "uuid": "e533201c-977c-11e5-a837-0800200c9a66",
     "hex": "0A0000000000000017D30C44...",
     "decoded": "Unknown(0A 00 00 00 00 00 00 00 17 D3 0C 44 ...)",
     "timeMs": 1795996800123}
  ]
}

GET /pump/observed?limit=N&pushes=M

Added 2026-12-02. Read-only view of PumpLink.observer: every notification on every characteristic is counted before any routing, every decrypted sealed frame is labelled, and every change between consecutive pumpStatus pushes is recorded as a TRANSITION. Sends nothing to the pump. Counters survive session resets (a MARKER event marks each reset); POST /pump/observed/clear zeroes them before an experiment.

  • channels — keyed by short characteristic id: count, firstMs/lastMs, min/mean/maxIntervalMs, lastLength, lastHex (raw bytes; ciphertext for e533201c).
  • opcodes — same stats per decrypted opcode, plus name.
  • kindCounts — totals per kind.
  • events (last limit, default 100, max 300) — kinds RESPONSE, NACK, RESPONSE_MISMATCH (did not match the in-flight command; dropped, never returned as its response — see reply matching in Crypto and transport), UNSOLICITED (no command in flight; dropped and logged), UNDECRYPTABLE, UNPARSEABLE, RAW_CHANNEL (any characteristic other than e533201c), TRANSITION, MARKER.
  • pushes (last pushes, default 10, max 60) — PUMP_STATUS / LOOP_STATUS / CGM_STATUS / NOT_ARMED frames, kept in their own ring so they cannot evict rare events.
  • pumpState (hex + observed-context label), configurationState, and the decoded loopStatus (provisional fields, see protocol.md §5) / cgmStatus (raw + matchesNoCgmIdlePattern).
{
  "channels": {"e533201c": {"count": 412, "meanIntervalMs": 2010, "minIntervalMs": 4, "maxIntervalMs": 5120, "lastLength": 140, "...": "..."},
               "e5332025": {"count": 0, "...": "..."}},
  "opcodes": {"0x0200": {"name": "pumpStatus", "count": 405, "meanIntervalMs": 2011, "...": "..."}},
  "kindCounts": {"PUMP_STATUS": 405, "RESPONSE": 3, "TRANSITION": 2, "MARKER": 1},
  "configurationState": "0x00001FFF",
  "pumpState": "0x007B (quiet: configured)",
  "loopStatus": null,
  "cgmStatus": null,
  "events": [
    {"timeMs": 1795996800123, "channel": "-", "kind": "TRANSITION", "opcode": "0x0200",
     "note": "alert RAISED: 409-0006 Pump Inactive (pumpIdle)", "...": "..."}
  ],
  "pushes": ["..."]
}

Values above are illustrative, not a capture. Exports contain pump telemetry (no LTSS, salt or keys); still do not commit them with the pump serial.

5.6 Pump session

POST /pump/arm[?respond=false]

Establish the sealed command channel. Body (or ?ltss=) = LTSS hex (16 or 32 bytes, per-unit secret). Sequence: reset all cached session material → request MTU 247 → subscribe all → read e5332024 (salt) and e5332023 (salt+start sequence) → derive keys → write 01 to e5332023 → wait up to 8 s for a pumpStatus frame sealed with the new keys. respond=true additionally answers the pump's pushes with opcode+0x80 and the push's seq (experimental); answer= picks which, as hex opcodes separated by commas (0200, 8304, 8705; default all three). The pump sends one push at a time and resends it about every 5 s until it is answered: with respond=false the status repeats every 5 s and no cgmStatus or loopStatus push arrives; with answer=0200 the cgmStatus push is resent every 5 s and the status stops updating.

A real handshake means the pump starts streaming frames sealed with the session keys. The route only reports armed:true after such a frame decrypts; if none arrives it reports armed:false with an explicit error instead of describing a stale session as fresh.

curl -s -X POST --data "$LTSS" "http://127.0.0.1:8090/pump/arm?respond=false"

Success:

{"armed": true, "sessionSalt": "<32 hex>", "startSeq": 12363, "error": null}

The salt is the pump's current connection salt: it changes when the BLE link is genuinely new and does not change when you merely re-arm on an existing link.

Failure is still 200 and says why:

{"armed": false, "sessionSalt": null, "startSeq": null,
 "error": "granted MTU 185, but the pump command channel requires MTU 247. ..."}

Common failure reasons: "MTU request failed", "LTSS must be 16 or 32 bytes", "GATT not ready", "read e5332024 failed", "e5332023 short read". Two newer ones matter for stale/poor links:

  • "BLE link is DISCONNECTED, not CONNECTED - POST /connect first" — arming never runs without a live link.
  • "arm handshake not confirmed within 8000 ms: no pumpStatus frame sealed with the new session keys arrived. The BLE link may still be serving a previous session - POST /disconnect, reconnect and arm again." — the arm write did not produce a working session; nothing was reported as armed.
  • "BLE link dropped during the arm handshake - reconnect and arm again" — the link went away mid-arm (the exactly observed old failure mode now becomes an explicit error).

After arming, wait for a pumpStatus (poll GET /pump/ready) before commanding.

Empty body = stored LTSS (2026-12-02). With no body and no ?ltss=, the route arms with the LTSS stored in the app (prefs.ltss, saved by every earlier arm or the Setup screen). This is the same-link re-arm that brings the command path back after a pump reboot (the old session keeps decrypting status but stops answering commands; see BLE and session §2.1). The response adds "ltssSource": "request" | "stored" and "commandPath". A successful arm resets only the post-arm setup stages; the registration decision is kept.

curl -s -X POST "http://127.0.0.1:8090/pump/arm"     # re-arm with the stored LTSS

Automatic re-arm on a pump reboot, once. PumpLink watches every pumpStatus: when the frame seq restarts or resetCount (bytes 30–31) changes, it marks commandPath REBOOTED, re-arms once on the existing link with the session's LTSS (3 s after the restart), then sends one read-only getLogRecord of the log head. commandPath goes REBOOTED → REARMING → UNPROVEN_AFTER_REARM → PROVEN; therapy commands are refused (outcome: NOT_SENT) in every held state. Arms are single-flight: another restart signal for the same restart is dropped (logged in GET /pump/observed), and POST /pump/arm while an arm runs answers armed:false with "error":"arm not started: a re-arm is already running (…)".

An unanswered command un-proves the path. Any command left with no answer (a therapy command's OUTCOME_UNKNOWN, or a plain command's timeout) moves commandPath to UNANSWERED and the app re-arms once more by itself. If commands still go unanswered (or the arm fails twice) the state is REARM_FAILED: POST /setup/reconnect, POST /pump/rearm or POST /pump/arm (empty body). GET /pump/ready never reports PROVEN while commands go unanswered.

  • 400 {"ok":false,"error":"ltss required: none in the request and none stored"} when there is no LTSS anywhere; 400 with the reason for a malformed one.
  • Secret: LTSS must not be logged or committed.

GET /pump/state

Session/transport state plus the latest decoded status counters.

{
  "armed": true,
  "sessionSalt": "<32 hex>",
  "startSeq": 12363,
  "nextPacket": 7,
  "lastSeq": 12369,
  "lastStatus": "0x0200 seq 12369",
  "commands": 3,
  "responses": 3,
  "token": "0x6a7a",
  "lastPayloadSent": "7A6A003A9323",
  "pumpTimeUtcSeconds": 596851201,
  "pumpTimeUtc": "2026-11-30T00:00:01Z",
  "mtu": 247,
  "error": null
}

Also reported: pumpState (hex + per-bit working names), pumpStateBits, alarmResetSupported (status byte 90), notificationAudioBitField (byte 91), resetCount (bytes 30–31), therapyState (bytes 26–29, hex), therapyStateText (its bits in words, e.g. basal pattern, bolus) and basalRunning, commandPath / commandPathDetail, lastReboot, lastTherapyOutcome and autoRearmOnReboot, plus messages (below). Firmware: risMessagesVersion and risEventsVersion ("13.76", "14.32"), risOperatingMode (1 = full application, 0 = bootloader), firmwareTested (true only on 13.76 / 14.32; null until read) and firmwareWarning (as in GET /status).

pumpTimeUtcSeconds/pumpTimeUtc come from pumpStatus payload bytes 8–11 (currentTimeDate_UTC, 2008 epoch). lastPayloadSent is the full payload as actually sent, therapy-number prefix included — the cheapest way to prove a command was not sent with an empty payload. sessionSalt is session secret material; treat exports containing it as sensitive.

GET /pump/ready

Waits up to 6 s for a fresh pumpStatus, then reports readiness, separating can deliver from is delivering (after a same-cassette reboot the pump reports 0x007B with basal stopped):

  • pumpReady — pumpState bit 0x0040 therapy-ready set, configurationState 0x1FFF (when reported), no alarm, not in cassette-change mode.
  • canDeliver — pumpReady, armed, and commandPath not held (after a restart, an alarm reset, or a command left unanswered).
  • isDelivering — basal is running: therapyState (status bytes 26–29) has the pattern, temp-basal or loop-override bit, so a pattern in a 0.00 U/h slot counts as delivering. Right after stopBasal it stays true for up to about 10 s, until the pump has finished the stop.
  • blockers — why canDeliver is false (e.g. "pump not configured (configurationState 0x0000) - Configure pump writes this app's settings"); notes — active alerts/notices (informational: a ready, stopped pump raises pumpIdle). On untested pump firmware notes also carries the firmwareWarning text, which is reported on its own too; it never blocks.
  • ready — the one-line verdict: "NOT READY: …", "CAN DELIVER; NOT delivering (…)", "CAN DELIVER; delivering basal 2.00 U/h" (with " (temp basal, N min left)" during a temp basal) or "CAN DELIVER; zero temp basal running, N min left (no insulin until it ends or is stopped)".

For the per-command view (what each condition blocks, and why) use GET /pump/conditions (§5.12). - messages — every active alarm, then alert, then notice, as shown to the user: type (alarm/alert/notice), bit, id (display id: 106-9411, 409-0006, 509-0004), key (pump_alert_pumpIdle), title and message (null where it has no fixed text). The same array is in GET /pump/state; GET /pump/history samples carry it as "<id> <title>" strings. Texts: Alarms, alerts and NACKs.

{
  "ready": "CAN DELIVER; NOT delivering (basal stopped - startBasal to resume) | alerts: 409-0006 Pump Inactive",
  "canDeliver": true, "pumpReady": true, "isDelivering": false, "basalRateUe2": 0,
  "blockers": [], "notes": ["alerts: 409-0006 Pump Inactive"],
  "messages": [{"type": "alert", "bit": 6, "id": "409-0006", "key": "pump_alert_pumpIdle",
                "title": "Pump Inactive", "message": null}],
  "commandPath": "PROVEN", "firmwareWarning": null,
  "status": {"pumpState": 123,
             "pumpStateBits": ["base","configured","cassette attached","prime done","self-test passed","therapy-ready"],
             "alarmBits": 0, "alarmCode": 0, "alarmResetSupported": false, "alertBits": 64,
             "noticeBits": 0, "selfTest": 100, "priming": 0}
}

pumpState bits use the per-bit working names from Status fields: 0x0001 base, 0x0002 configured, 0x0008 cassette attached, 0x0010 prime done, 0x0020 self-test passed, 0x0040 therapy-ready, 0x0400 cassette-change mode, 0x0800 boot.

If no pumpStatus has ever arrived: ready is "NOT READY: no pumpStatus yet" and the status fields are null.

GET /pump/activity

What the app's activity line (under the bottom buttons) and its failure alert show: the commands running now, the recent ones with their results, and the last failure in plain words. Every pump command goes through one path, so commands sent over REST show here (and on the phone) too. No pump I/O.

  • line — the activity line as the app shows it: the running command(s) ("startBasal 0x8100: sent, waiting for the pump"), then the last result for 8 s ("… accepted", "… refused: …", "… no answer: …", "… not sent: …"), then "No command running · last: … (2 min ago)".
  • running, last, recent (newest last, up to 30) — entries with name, opcode, result (RUNNING, ACCEPTED, ANSWERED, REFUSED, NO_ANSWER, NOT_SENT, DONE, FAILED), detail, text, startedAtMs, finishedAtMs. Arms and same-link re-arms are entries too ("re-arm"), including a restart signal that was not repeated ("not repeated (…)").
  • alert — the failure the phone shows as an alert, or null: kind (NACK, NO_ANSWER, NOT_SENT, APP, REARM), title, plain (why, in plain words, and what to do next), pumpMessage (for a refusal: "Pump rejected the command. (5101)", the code in decimal), technical, action (the app action it belongs to, e.g. "basal"), atMs. It stays until OK on the phone.
  • commandPath, commandPathDetail — as in GET /pump/state.
{
  "line": "startBasal 0x8100: refused: The pump does not allow this command in its current state (…)",
  "running": [],
  "last": {"id": 41, "name": "startBasal", "opcode": "0x8100", "result": "REFUSED", "detail": "The pump does not allow …",
           "text": "startBasal 0x8100: refused: …", "startedAtMs": 1764790000000, "finishedAtMs": 1764790000900},
  "recent": ["…"],
  "alert": {"id": 42, "kind": "NACK", "title": "Pump refused startBasal",
            "plain": "The pump does not allow this command in its current state (…). Change the pump's state first; sending it again as it is will not help.",
            "pumpMessage": "Pump rejected the command. (5101)",
            "technical": "pump refused 0x8100: not valid in this state/step (0x13ED NackBadSequence, next therapy number 0x6A7C)",
            "action": "basal", "atMs": 1764790000901},
  "commandPath": "PROVEN", "commandPathDetail": "proven (a command was answered)"
}

5.7 Commands (sealed)

Both command routes require an armed session. They send a real sealed frame and wait up to 4 s for the pump's response. Responses use opcode + 0x80; a NACK arrives as opcode == 0xFF80 with a 26-byte payload. Both routes add a decoded nack object (code, name = app case name, meaning, nextTherapyNumber from payload bytes 4–5, description). /pump/command still answers ok:true for a NACK; /pump/command-token answers ok:false, outcome:"NACKED" (2026-12-02). authOk/crcOk say whether the response frame's HMAC/CRC verified.

Reply matching (2026-12-02). Commands are serialised, and a route returns only the frame that answers its request: opcode == request | 0x80 with the request seq, or a NACK naming the request opcode with the request seq. Any other frame (a late answer to an earlier command, a stray frame) is dropped and logged, never returned as this command's response (Crypto and transport §4).

The parameter trap (do not forget): /pump/command reads payload (raw, no prefix); /pump/command-token reads value (payload after the prefix). Both now also accept the other name as an alias, and both return the authoritative payloadSent so you can prove what went out. A wrong parameter name once sent empty payloads for a week.

POST /pump/command?opcode=HEX&payload=HEX

Send a Simple command: payload is fields only, no therapy-number prefix. Examples: 0x0310 getPumpIdentification (empty), 0x0502 getLogRecord (0000 + event id u32 LE), 0x800F verifyTherapySettings (42-byte record).

curl -s -X POST "http://127.0.0.1:8090/pump/command?opcode=0310&payload="
{"ok": true, "opcode": "0x0390", "seq": 12363, "packet": 1,
 "payloadSent": "", "authOk": true, "crcOk": true,
 "payload": "000000004D"}
  • 400 {"ok":false,"error":"opcode required (hex)"}.
  • 200 {"ok":false,"error":"not armed"} or "no response to opcode 0x0502 within 4000 ms" on failure/timeout.
  • 409 for opcode 0D00 (alarmReset) while status byte 90 alarmResetSupported is not 1 — the same gate as /pump/alarm-reset.
  • DANGER (HIGH): any opcode can be sent, including delivery commands. This is the escape hatch the Dev panel wraps with confirmations.

POST /pump/command-token?opcode=HEX&value=HEX[&therapyNumber=HEX]

Send a Therapy command: the app prefixes the running 2-byte therapy number (from the pump's pumpStatus[12:13], advanced by command responses) before the fields. Examples: settings writes (0x8000–0x801D, 0x8700), delivery (0x8100 startBasal with the 42-byte record, 0x8400 bolus, 0x8103 stopBasal), 0x800B setTime.

curl -s -X POST "http://127.0.0.1:8090/pump/command-token?opcode=8103&value="
{"ok": true, "outcome": "ACCEPTED", "resent": false, "late": false,
 "opcodeSent": "0x8103", "opcodeName": "stopBasal", "therapyNumberSent": "0x6A7A",
 "opcode": "0x8183", "seq": 12364, "packet": 2, "token": "0x6a7b",
 "valueSent": "", "payloadSent": "7A6A", "authOk": true, "crcOk": true,
 "payload": "7A6A7B6A", "commandPath": "PROVEN"}

Sent exactly once — no automatic resend. A resend after a timeout or a NACK carries a fresh, valid therapy number; if the first send was accepted and only its response lost, the pump executes the command twice (seen live on the bench). outcome is one of:

outcome ok Meaning What to do
ACCEPTED true The pump answered (late:true = the answer arrived after the timeout, while the bridge re-read status). Confirm the effect in the next status.
NACKED false Refused. nack.nextTherapyNumber is the pump's next number (every refusal rotates it); the session token already follows it. Fix the cause (see nack.meaning), then send again deliberately — optionally with &therapyNumber=<nack.nextTherapyNumber>.
OUTCOME_UNKNOWN false No answer within the timeout. The bridge re-read pumpStatus and reports freshStatusSeen, therapyNumberAdvanced (the pump processed a command — accepted or refused), pumpLogAdvanced, bolusIdChanged. Do not resend blindly. Read GET /pump/state / GET /pump/events and decide.
NOT_SENT false Not armed, the command path is held after a pump reboot, or the alarmReset gate refused. See error.

therapyNumber=HEX overrides the running number for this one send (a deliberate retry with a NACK's nextTherapyNumber). 0D00 alarmReset is gated on status byte 90 here too.

  • 400 for a missing/invalid opcode or a malformed therapyNumber.
  • NACK decode: the next therapy number is at NACK payload bytes 4–5 (bytes 2–3 are the NACK code).

POST /pump/alarm-reset

alarmReset (0x0D00) with the therapy number as its whole payload (an empty payload is refused 0x1403 invalid length). Allowed only while pumpStatus byte 90 alarmResetSupported = 1 — an alarm the pump can reset is active (baseDetached, occlusion measured). Otherwise the bridge refuses without sending (outcome:"NOT_SENT"); the pump itself would answer 0x13ED and not reboot.

When accepted (0x0D80) the pump reboots: the alarm clears, resetCount +1, status seq restarts, configuration / reservoir / cassetteAge / prime-done are kept, and the attached cassette self-tests by itself (~10 s → 0x007B). commandPath goes to AWAITING_REBOOT at once (therapy held); the bridge re-arms on the existing link once the restart is seen, or after 30 s with no restart (watch commandPath in GET /pump/state). It is sent once per alarm: while the pump restarts it keeps reporting the alarm and byte 90 = 1, but a second alarmReset is refused without sending (outcome:"NOT_SENT", "an alarm reset was already sent … it is sent once per alarm") until the restart is seen or 60 s pass. An alarmReset whose answer was lost counts as sent. Basal is not resumed: verify (0x800F → 01) and startBasal when GET /pump/ready says canDeliver. Details: Setup and recovery §6.2.

curl -s -X POST "http://127.0.0.1:8090/pump/alarm-reset"

Same response shape as /pump/command-token, plus a note. Danger: HIGH (reboots the pump). - DANGER (HIGH): delivery-range opcodes are directly reachable. Know the stop path first (0x8103 stopBasal, 0x8200 stopNormalBolus, 0x8202 stopCannulaFillBolus; physically pulling the battery always stops).

POST /pump/stop-cannula-fill

Stops a running cannula fill: stopCannulaFillBolus (0x8202), a Therapy command whose payload is only the therapy number (no value). Requires an armed session. The app could start a fill (0x820A) but had no stop; this is the safety-relevant missing path.

curl -s -X POST "http://127.0.0.1:8090/pump/stop-cannula-fill"
{
  "ok": true,
  "opcode": "0x8202", "opcodeName": "stopCannulaFillBolus", "responseOpcode": "0x8282",
  "seq": 12370, "packet": 5, "token": "0x6a7c",
  "payloadSent": "7C6A", "authOk": true, "crcOk": true, "payload": "…",
  "verifiedLive": true,
  "note": "the pump log record 0x0060 carries the delivered and requested volume. If the fill continues, remove the pump battery - that always stops delivery."
}
  • 200 {"ok":false,"error":"not armed"} / "no response to opcode 0x8202" when it cannot be sent.
  • Unverified: this opcode has not been accepted on the bench. "Succeeded" means the pump answered; confirm the fill actually stopped in the next status/history, and pull the battery if it did not.
  • DANGER (HIGH): delivery-affecting.
  • Related corrections: 0x8201 is stopExtendedBolus (not "startNormalBolus") and 0x8202 is stopCannulaFillBolus (not "bolusCalculatorResult"); the app's opcode table and ProtocolConstantsTest pin these names.

POST /pump/temp-basal?rate=U_PER_HOUR&duration=MINUTES

Sets a temporary basal using temporaryOverrideBasal (0x8102, a Therapy command): therapyNumber(2) || rate_UE2PerHour(2 LE) || duration_minutes(2 LE). Parameter forms:

Param Meaning
rate absolute rate in U/h, decimal (e.g. 0.5)
rateUe2 absolute rate in 0.01 U/h units (e.g. 50 = 0.50 U/h) — wins over rate if both are present
duration (or minutes) duration in minutes

The route refuses out-of-range requests with 400 before sending anything (measured pump limits: rate 0.10–22.00 U/h; duration 30–1440 minutes), and refuses a second temp-basal command while one is running (409, NACK 0x13ED NackBadSequence) — cancel first, then set the new one. The pump's next status broadcast is decoded and returned as observed; confirmed is true when it shows the requested rate/duration. Verified live 2026-11-30 on the bench pump (saline, off-body): the next pumpStatus showed the absolute rate in bytes 42–43, requested/remaining minutes in 46–51, and tempBasalModifier_percent = 0.

curl -s -X POST "http://127.0.0.1:8090/pump/temp-basal?rate=0.5&duration=30"
{
  "ok": true,
  "opcode": "0x8102", "opcodeName": "temporaryOverrideBasal", "responseOpcode": "0x8182",
  "payloadSent": "A1B2 3200 1E00",
  "responsePayload": "A1B2A1B2",
  "rateUe2PerHour": 50, "rateUPerHour": 0.5, "durationMinutes": 30,
  "observedInNextStatus": true, "confirmed": true,
  "observed": {
    "active": true, "absoluteOverride": true,
    "basalRateUe2": 50, "basalRateUPerHour": 0.5,
    "durationRequestedMin": 30, "durationRemainingMin": 30, "modifierPercent": 0,
    "netBasalRatePercent": -75, "netBasalRateUe2PerHour": -150, "netBasalRateUPerHour": -1.5
  },
  "verifiedLive": true
}
  • 400 {"ok":false,"error":"Temp basal rate must be 0 or 0.10-22.00 U/h …"} / duration error; nothing is sent.
  • 409 when the session is not armed, when the pump's closed loop is enabled (safety refusal), when the pump refuses (NACK), or when a temp basal is already running. The error text carries the pump's NACK name and guidance (e.g. a battery-reset pump answers 0x13ED until its settings are written — configure, see Setup and recovery §6).
  • observedInNextStatus:false means "pump answered, effect not yet seen" — re-check GET /pump/state after a few seconds instead of resending (a resend while it is running is refused).
  • DANGER (HIGH): starts delivery. Know the stop path first: POST /pump/temp-basal/stop, and removing the pump battery always stops delivery.
  • Pinned by protocol/TempBasalPayload.kt + TempBasalPayloadTest.

Percent form — POST /pump/temp-basal?percent=P&duration=MINUTES sends temporaryModifyBasal (0x8101): therapyNumber(2) || adjustmentPercent(2 LE) || duration_minutes(2 LE), a percentage of the programmed basal pattern. percent is a whole number 0–200 (the pump refuses 201 % and above with 0x13EE); 0 % is a zero temp basal. Same app control: Adjust → % of pattern (0x8101).

curl -s -X POST "http://127.0.0.1:8090/pump/temp-basal?percent=50&duration=30"
{
  "ok": true, "opcode": "0x8101", "responseOpcode": "0x8181",
  "payloadSent": "A1B232001E00", "percent": 50, "durationMinutes": 30,
  "observed": {"active": true, "absoluteOverride": false, "basalRateUe2": 100, "basalRateUPerHour": 1.0,
               "durationRequestedMin": 30, "durationRemainingMin": 30, "modifierPercent": 50,
               "netBasalRatePercent": -50, "netBasalRateUe2PerHour": -100}
}
  • 400 for a percent that is not a whole number 0–200, or a missing / out-of-range duration; nothing is sent. 409 when not armed, when the closed loop is enabled, or when the pump refuses.

POST /pump/temp-basal/stop

Cancels a running temp basal with stopTempBasal (0x8104, Therapy, therapy number only). The next status should show the temp-basal fields cleared and the basal rate back to the programmed pattern value. Verified live 2026-11-30 on both the absolute and percent forms (answer 0x8184).

curl -s -X POST "http://127.0.0.1:8090/pump/temp-basal/stop"
{
  "ok": true,
  "opcode": "0x8104", "opcodeName": "stopTempBasal", "responseOpcode": "0x8184",
  "payloadSent": "A1B2", "responsePayload": "A1B2C3D4",
  "observedInNextStatus": true, "confirmed": true,
  "observed": {"active": false, "basalRateUe2": 200, "basalRateUPerHour": 2.0,
               "durationRequestedMin": 0, "durationRemainingMin": 0, "modifierPercent": 0,
               "netBasalRatePercent": 0, "netBasalRateUe2PerHour": 0},
  "verifiedLive": true
}
  • 409 when not armed, when the pump's closed loop is enabled, or when the pump refuses. The command is also accepted when no temp basal is running (a harmless no-op on this firmware).
  • DANGER (HIGH): changes delivery (back to the programmed basal).

POST /pump/time[?epochSeconds=]

setTime (0x800B): writes host UTC (or epochSeconds, a decimal Unix-seconds value for tests/scripts) as a Therapy command. The 6-byte value is u32 LE seconds since 2008-01-01 UTC || i16 LE timezone offset minutes (8-byte payload once the therapy number is prepended). The timezone offset uses the pump's own stored offset from pumpStatus bytes 84-85 when known, else the phone's zone. It then verifies against the pump's next pumpStatus bytes 8-11 — the acknowledgement alone is not trusted.

Payload length matters: a 4-byte time-only payload and a 6-byte token+u32 payload are both refused with 0x1403 invalid message length. The accepted shape is 8 bytes, e.g. 800b 0a0e 320b9223 98fe → therapy number 0a0e, UTC 0x23920B32, offset -360.

curl -s -X POST "http://127.0.0.1:8090/pump/time"
{
  "ok": true,
  "opcode": "0x800b",
  "responseOpcode": "0x808b",
  "targetPumpSeconds": 596932974,
  "targetUtc": "2026-11-30T22:42:54Z",
  "timeZoneOffsetMinutes": -360,
  "oldPumpTimeUtc": "2026-11-30T22:42:22Z",
  "newPumpTimeUtc": "2026-11-30T22:42:54Z",
  "residualSeconds": 0,
  "payloadSent": "…",
  "responsePayload": "…"
}
  • newPumpTimeUtc is null when no fresh status arrived within the timeout (the write still happened — check GET /pump/state.pumpTimeUtc later).
  • residualSeconds = target − pump-reported time; small non-zero values are normal (status freshness).
  • 200 {"ok":false,"error":"not armed"} or "pump refused setTime: pump refused 0x800B: invalid message length (0x1403)" (wrong payload length/offset — see the correction above).
  • 400 for a non-numeric epochSeconds.
  • DANGER (MED): a wrong clock skews history timestamps, reminders and scheduling. A successful sync raises the pump's 509-0004 System Time Updated notice (utcTimeChanged, notice bit 4, noticeBits 0x0010) until cleared.

5.8 Raw wire / counter replay

POST /pump/raw-wire?hex=HEX[&confirm=true][&resp=false]

Writes already-sealed wire bytes (LE64(packet) || AES-CCM(appKey, nonce=packet)(frame)) verbatim to the command characteristic e5332018 (body may carry the hex instead of ?hex=). Nothing is re-sealed, so counter-replay, forged-frame and packet-number-sweep transport experiments run from the phone with the bytes exactly as they were sealed.

  • Requires an armed session (the bytes are sealed with the session keys).
  • Max 255 bytes; empty/odd/invalid hex is a 400.
  • Two-step confirm: without confirm=true it answers HTTP 409 and writes nothing.
  • The bytes are decrypted with the current session keys when possible, purely to report the opcode. A blob that does not decode is still written (that is a legitimate experiment) with decrypted: false.
  • The app's internal packet counter advances only if the frame used exactly the next expected packet number; a replayed/future counter cannot move the live chain (counterAdvanced says which happened). Reset the session (reconnect + arm) to return to normal traffic.
curl -s -X POST "http://127.0.0.1:8090/pump/raw-wire?hex=010000000000000017D30C44...&confirm=true"
{
  "ok": true, "wrote": true, "bytes": 42,
  "hex": "010000000000000017D30C44...",
  "decrypted": true, "opcode": "0x0310", "opcodeName": "getPumpIdentification",
  "seq": 12363, "packet": 1, "payload": "",
  "authOk": true, "crcOk": true,
  "wroteWithResponse": false, "counterAdvanced": true,
  "note": "written verbatim; decoded with the current session keys; packet counter advanced past it"
}

Missing confirmation (409):

{"ok": false, "wrote": false, "requires": "confirm=true", "bytes": 42, "armed": true,
 "error": "raw-wire requires confirm=true: sealed bytes are written verbatim to e5332018"}

Other errors: 200 {"ok":false,"error":"not armed - raw wire bytes are sealed with the session keys; POST /pump/arm first"}; 400 with the over-size/parse reason; 200 {"ok":false,"error":"GATT status ... during WriteCharacteristic"}. - DANGER (HIGH): sealed bytes can carry any opcode.

5.9 Replacement / provisioning data

The replacement blob is the cloud-issued record that provisions the pump's registration material. Its structure (established by bench analysis of the blob's own layout):

info (538 B, big-endian header)
  off  0  u32  recoverVersion              = 0
  off  4  u32  recoverSigVersion           = 1
  off  8  u32  recoverCryptVersion         = 1
  off 12  u64  recoverExpirationDate_UTC   Unix seconds = issue time + exactly 180 days
  off 20  390  recoverBLOB                 opaque, pump-bound material
  off 410 128  reserved                    all zero
then a DER ECDSA P-256 signature (70-72 B) is appended => total 608-610 B, never a fixed 609.

The write splits it into 243-byte BLE writes; the count is derived from the actual length (608 -> 243/243/122, 609 -> 243/243/123, 610 -> 243/243/124). The readback is not a GATT read (that is refused): with the notify CCCD on e5332027 enabled, a write-without-response to e5332027 (the readback trigger; payload 00 by default) makes the pump push [packetNum(1 B) | up to 243 B data], packets 1..N, then packet 255 with a 1-byte status (0 = success). It is read-only.

Do not invent a blob and do not write one that was not issued for this unit. A wrong, stale or foreign blob can de-provision the pump and force a re-pair / re-registration. The write route has been executed live on an armed session (an authentic 609-byte blob; chunk echoes recorded). The pairing-mode write — before any session key exists — is POST /pump/replacement?unarmed=true (MTU 247, fresh bond). The write sends packet-numbered packets [n | up to 243 data], n from 1, over the blob plus its CRC32 (IEEE, little-endian): 244/244/128 bytes for a 609-byte blob. The pump answers with one standalone FF|status after the last packet: FF 00 accepted (a later readback then returns the new blob), FF 02 the transfer failed its check, FF 01 bad signature. The response's adopted, transferResult and ackNote carry that answer. TwiistOff's framed write has not been run on the bench pump yet; its earlier unframed writes, armed and in pairing mode, were never adopted (Pairing and setup §9). Use the write only as a user-approved bench experiment.

POST /pump/replacement?blob=HEX[&confirm=true]

Two-step confirm. Without confirm=true this is a dry run (preview) and writes nothing. The body may carry the blob hex instead of ?blob=.

Step 1 — preview:

curl -s -X POST "http://127.0.0.1:8090/pump/replacement?blob=$(cat blob.hex)"
{
  "ok": true, "stage": "preview", "wrote": false, "requires": "confirm=true",
  "note": "preview only - repeat with confirm=true to write the blob; a stale blob's expiration is at info[12] (issue + 180 days)",
  "blob": {
    "size": 609, "expectedSize": "608-610",
    "infoBytes": 538, "signatureBytes": 71, "derSignatureOk": true,
    "expirationUtc": "2027-01-01T00:00:00Z",
    "sha256": "<sha256 hex>",
    "characteristic": "e5332027",
    "chunkSizes": [244, 244, 128],
    "pumpSerial": "SERIALXXXXX",
    "armed": true,
    "mtu": 247
  }
}

Step 2 — write (each chunk's echo is returned):

curl -s -X POST "http://127.0.0.1:8090/pump/replacement?blob=$(cat blob.hex)&confirm=true"
{
  "ok": true, "stage": "written", "wrote": true,
  "size": 609,
  "sha256": "<sha256 hex>",
  "characteristic": "e5332027",
  "expirationUtc": "2027-01-01T00:00:00Z",
  "pumpSerial": "SERIALXXXXX",
  "mtu": 247,
  "chunks": [
    {"index": 1, "size": 244, "echo": "…", "echoBytes": 244},
    {"index": 2, "size": 244, "echo": "…", "echoBytes": 244},
    {"index": 3, "size": 128, "echo": "…", "echoBytes": 128}
  ],
  "adopted": true, "responseCode": 255, "transferResult": 0, "ackHex": "FF00",
  "ackNote": "FF00 - pump ACCEPTED the transfer (adoption still needs the readback)"
}

Errors:

  • 400 invalid hex, or a blob whose size is outside 608-610 (the body includes the parsed blob info with the real size).
  • 200 {"ok":false,"error":"not armed - replacement data needs an armed session (POST /pump/arm first)"}.
  • 200 {"ok":false,"error":"characteristic e5332027 not discovered (GATT not ready)"}.
  • 200 {"ok":false,"error":"chunk 2/3 failed after 1 chunk(s) were accepted: … The pump may hold a PARTIAL blob - review before retrying."} — a partial write is the dangerous case; do not blindly retry.
  • DANGER (HIGH): provisioning credential write, irreversible from the phone's side.

POST /pump/registration-handshake[?confirm=true]

The pump's registration sequence in one call, on the unarmed pairing-mode connection (pump in pairing mode, bonded, MTU 247, not armed): read the SRI (e5332026) → read the stored blob back → write the blob → read it back. The e5332027 notify subscription is enabled once and held for the whole sequence, and the call first waits (up to 20 s) for a settled bond (bondConfirmed in GET /bond). The body is the blob hex. pauseMs (0-15000, default 0) inserts an optional pause before the write. The Provision screen's "Registration handshake (pairing mode)" card runs the same call.

Step 1 — preview (nothing sent):

curl -s -X POST "http://127.0.0.1:8090/pump/registration-handshake" --data "$(cat blob.hex)"
{"ok": true, "stage": "preview", "wrote": false, "requires": "confirm=true",
 "sha256": "<sha256 hex>", "pauseMs": 0,
 "note": "reads SRI + stored blob, pauses, writes, reads back on the unarmed pairing-mode connection; confirm=true to run"}

Step 2 — run:

curl -s -X POST "http://127.0.0.1:8090/pump/registration-handshake?confirm=true" --data "$(cat blob.hex)"
{
  "ok": true, "stage": "handshake",
  "verdict": "ADOPTED - the stored record is the blob just written", "adopted": true, "pauseMs": 0,
  "sriHex": "<64 hex>",
  "beforeSha256": "<sha256 hex>", "beforeBytes": 609, "beforeExpirationUtc": "2027-01-01T00:00:00Z",
  "writeSha256": "<sha256 hex>", "writeRejected": false, "writeAckCodes": ["FF00"],
  "writePushPackets": 0, "writeResponseCode": 255, "writeTransferResult": 0,
  "writeAckNote": "FF00 - pump ACCEPTED the transfer (adoption still needs the readback)",
  "afterSha256": "<sha256 hex>", "afterBytes": 609, "afterExpirationUtc": "2027-01-01T00:00:00Z"
}

verdict is one of ADOPTED (the readback after the write is the blob written), REJECTED <codes> (a standalone non-zero FF|status), NOT ADOPTED (FF 00 but the stored blob is unchanged) or UNCONFIRMED (no standalone ack). writePushPackets counts stored-blob push packets the pump sent during the write; their FF|status terminators are never taken as the ack. Writing the blob the pump already holds is the safe way to test the write: the registration does not move.

Errors: 400 when the body is not a 608-610-byte blob; 200 {"ok":false,"error":…} when not connected, not bonded within 20 s, armed (the handshake runs unarmed), below MTU 247, or when e5332027 is not discovered or its notify does not enable. DANGER (HIGH): provisioning credential write, irreversible from the phone's side.

GET /pump/replacement/readback[?expectedSha256=HEX]

Reads the pump's stored blob and verifies it. A plain GATT read of e5332027 is refused, so the app enables that characteristic's notify CCCD (read-only) and collects the pump's pushed [packetNum | data] packets, reassembling them until the packet-255 status. It then reports the stored size, SHA-256, expiry and signature sanity, and compares against:

  • expectedSha256 when supplied (e.g. the reviewed blob's SHA-256 from the preview), and
  • the SHA-256 of the blob this session last wrote (matchesLastWrite), if any.
curl -s "http://127.0.0.1:8090/pump/replacement/readback?expectedSha256=<sha256 hex>"
{
  "ok": true, "readback": "notify",
  "bytes": 609,
  "sha256": "<sha256 hex>",
  "chunkSizes": [243, 243, 123],
  "packets": 3,
  "statusCode": 0, "statusSeen": true, "statusOk": true,
  "complete": true,
  "missingPackets": [],
  "infoBytes": 538, "signatureBytes": 71, "derSignatureOk": true,
  "expirationUtc": "2027-01-01T00:00:00Z",
  "expectedSha256": "<sha256 hex>",
  "matchesExpected": true,
  "matchesLastWrite": true,
  "hex": "00000000000000010000000100000000…"
}
  • complete:false + missingPackets lists gaps in the numbered push (re-run the read; nothing is written by this route).
  • matchesExpected:null / matchesLastWrite:null mean there was nothing to compare against.
  • 200 {"ok":false,"error":"no replacement-data push within 15000 ms after enabling notify …"} when the pump did not push (not bonded, CCCD write refused, or link dropped).
  • ?gatt=true performs the legacy plain ATT read attempt instead and reports the refusal verbatim (readback: "gatt-attempt"); kept as a diagnostic only.
  • expirationUtc comes from info[12] (u64 big-endian Unix seconds). The cloud issues every blob for exactly 180 days, so an old stored blob may carry a stale expiry — worth reading before treating provisioning as current.
  • Live status of the readback: enabling the notify CCCD alone does not cause a push; the trigger write does. With it (?trigger=HEX, default 00; trigger=none = notify only, no trigger), the bench pump pushed its complete, byte-exact stored blob at MTU 247 (in pairing mode, fresh bond, unarmed). At MTU 23 the push is truncated (57 bytes). Readback on an ordinary armed reconnect is not separately confirmed (one attempt lost the link); do not assume "timed out" means the stored blob is wrong.

5.10 Pump log and local history

GET /pump/events?start=HEX&count=N

Reads pump log records newest-first by walking getLogRecord (0x0502). start is the first event id (hex; defaults to the latest therapy event id from pumpStatus), count is 1–200 (default 20). Each read is a real command (~0.3–0.4 s); failures are skipped, the rest are returned.

{
  "from": 8817,
  "count": 1,
  "events": [
    {"eventId": 8817, "type": 90, "typeHex": "0x005A", "size": 16, "logfile": 0,
     "timestamp": 597101513, "timeOffsetMinutes": -360, "resetCount": 47,
     "data": "00005802200005003300000000000000",
     "name": "Bolus stopped", "family": "Delivery",
     "summary": "Bolus 32 stopped: 0.00 of 6.00 U, manual, after 51 s"}
  ]
}
  • name, family and summary are the History screen's decode (protocol/EventTypes.kt); null when the record type or layout is not known. data is always the raw record.

  • 409 {"ok":false,"error":"no event id yet (wait for pumpStatus)"} before the first status broadcast. Arm and wait for GET /pump/ready.

  • Requires an armed session to actually reach the pump; without one every read fails and the response is {"from": N, "count": 0, "events": []}.
  • Engineering log: not exposed as a dedicated route (known gap). getLogRecord (0x0502) has two logs: logfileNumber 0 = therapy log (what this route reads) and 1 = engineering log. The engineering log is a separate read-only channel the pump exposes; it can be read today only by hand: POST /pump/command?opcode=0502&payload=0100<eventID LE32> (note the leading 0100, the u16 LE logfile, instead of 0000). A ?logfile=N parameter on this route is the natural follow-up; deliberately not implemented in this change.

GET /pump/history?limit=N

Locally cached decoded pumpStatus samples (SQLite), newest last. No pump traffic. limit default 200. count is the total number of cached samples.

{
  "count": 4213,
  "samples": [
    {"timeMs": 1795996800123, "pumpState": 123, "alarmBits": 0, "alarmCode": 0,
     "alertBits": 0, "noticeBits": 0, "battery": 87, "selfTest": 100,
     "priming": 0, "therapyEvent": 466874, "token": 27258}
  ]
}

5.11 Therapy settings

The pump cannot read its settings back, so the app keeps the only copy: all 20 settings it writes (Setup and recovery §6.0). These routes read, edit, move and write that copy. Each calls the same SetupRunner / SettingsStore method as the Therapy settings page, the pattern editor and the cassette set-up wizard.

A setting changed in the app but not yet accepted by the pump (an import, a preset, an edit whose write failed) is marked "unwritten": true until it is written.

GET /settings

Every stored setting in words and on the wire, the verify record built from them, and the last batch of writes. No pump I/O.

curl -s "http://127.0.0.1:8090/settings"
{
  "settings": [
    {"name": "IDLE_ALERT", "opcode": "0x8000", "title": "Pump-idle alert", "value": "15 min",
     "wire": "0F00", "length": 2, "inVerifyRecord": false, "editable": true, "provenByVerify": false,
     "pumpHolds": true, "unwritten": false},
    {"name": "DELIVERY_LIMITS", "opcode": "0x800A", "title": "Delivery limits",
     "value": "max basal 5.00 U/h, max bolus 5.00 U", "wire": "F401F401", "length": 4,
     "inVerifyRecord": true, "editable": true, "provenByVerify": true, "pumpHolds": null, "unwritten": true},
    "…"
  ],
  "problems": [],
  "verifyRecord": "<84 hex: the 42-byte verifyTherapySettings record>",
  "lastVerifyMatch": true,
  "configurationState": "0x1FFF",
  "lastWrites": [{"setting": "DELIVERY_LIMITS", "accepted": true, "skipped": false, "outcome": "accepted", "valueSent": "F401F401"}],
  "export": {"format": "twiistoff-pump-settings", "version": 1, "idleAlertMinutes": 15, "…": "…"}
}

name is the setting's id for /settings/write?setting=; wire is the value after the therapy number; length its size in bytes; problems lists values outside the bounds the app applies (empty when the record may be written). lastVerifyMatch is the last verify answer this session (null = none yet).

Unwritten, and what the pump holds. For each setting the app keeps the value the pump last confirmed: a write the pump accepted, or a verify 01 for a record that carries the whole setting. pumpHolds is true when the stored value equals it, false when it differs, null when nothing is confirmed. unwritten is true when the pump is not known to hold the stored value. A verify 01 proves the 11 settings with provenByVerify: true (the four patterns through their CRCs, the delivery limits, the loop targets, the CGM low and high alerts, the display range, one-button bolus and the insulin model) and clears their mark. It does not carry the pump-idle alert, the cassette reminder, the CGM sleep schedule, the closed-loop switch, the CGM info, the audio level or the CGM signal-loss minutes, and the pump answers 01 whatever the low-insulin and walk-away fields hold. Those nine are confirmed only by writing them, and the pump takes those writes while basal runs.

GET /settings/export

The settings export: one JSON object, the same file as Therapy settings → Export to file. It holds the settings only (no key, no pump identifiers); patterns are arrays of 48 wire values.

curl -s "http://127.0.0.1:8090/settings/export" > twiistoff-settings.json
{
  "format": "twiistoff-pump-settings",
  "version": 1,
  "idleAlertMinutes": 15,
  "lowInsulinUe2": 2000,
  "walkawayMinutes": 0,
  "oneButtonBolus": true,
  "…": "…",
  "closedLoop": false,
  "basal": [200, 200, "… 48 values …"],
  "maxBasalUe2": 500,
  "maxBolusUe2": 500,
  "insulinModel": 1
}

POST /settings/import (body = an export)

Replaces the app's settings with an export (missing keys keep the current value; unknown keys are ignored). App only: nothing is sent to the pump. A setting whose value equals the one the pump last confirmed stays written; every other setting becomes "unwritten". On a new phone that is all 20. Then verify: a 01 clears the 11 settings it proves, and the rest are written with /settings/write?all=true (the pump takes them while basal runs).

curl -s -X POST --data @twiistoff-settings.json "http://127.0.0.1:8090/settings/import"
# -> 200 { …GET /settings…, "ok": true,
#          "note": "imported into the app only; POST /settings/verify (01 clears every setting it proves), then write the rest with /settings/write?all=true" }
  • 400 when the body is not an export ("format" must be "twiistoff-pump-settings"), is newer than the app understands, or holds a value outside the bounds ("the export has invalid values: …").

POST /settings/preset?name=defaults|bench-replay

Loads the bench defaults or the bench replay values into the app (Therapy settings → Load bench defaults / Load bench replay values). App only; the changed settings are listed and marked unwritten.

curl -s -X POST "http://127.0.0.1:8090/settings/preset?name=bench-replay"
# -> 200 { …GET /settings…, "ok": true, "changed": ["LOW_INSULIN", "ONE_BUTTON_BOLUS", "…"],
#          "note": "loaded in the app only; nothing was written to the pump" }

POST /settings/set (body = JSON fields)

Changes one or more settings, stores them, writes the settings whose wire value changed (delivery limits first) and re-verifies. The body uses the export's field names; the export header is optional.

curl -s -X POST --data '{"maxBolusUe2": 400}' "http://127.0.0.1:8090/settings/set"
{"action": "settings-set", "ok": true,
 "result": "1/1 writes accepted; configurationState 0x1FFF; verify 01",
 "writes": [{"setting": "DELIVERY_LIMITS", "opcode": "0x800A", "accepted": true, "outcome": "accepted", "valueSent": "F4019001"}],
 "verifyMatch": true, "configurationState": "0x1FFF"}
  • 400 for an invalid body or a value outside the bounds; nothing is stored.
  • 409 {"action":"settings-set","ok":false,"error":"saved in the app; not written (not armed). …"} when the value was stored but could not be written (not armed, or a pump condition blocks settings writes). Write it later with /settings/write.
  • 409 {"action":"settings-set","ok":false,"error":"saved in the app; not written: the delivery limits differ from the pump's, and the pump takes new delivery limits only with basal stopped …"} when the change touches the delivery limits while basal runs. Nothing was sent; change them with /settings/write-limits (below).

Delivery limits while basal runs. The pump refuses setDeliveryLimits 0x800A with NACK 0x13ED while basal runs (the pattern or a temp basal), even with an unchanged value, and accepts it once basal is stopped. So /settings/set, /settings/write and /settings/configure never send it while basal runs:

  • the pump holds the stored limits (pumpHolds: true): not rewritten. The write is reported with "skipped": true, "accepted": true and the outcome unchanged: the pump already holds these limits, …;
  • the stored limits differ from the pump's (pumpHolds: false): the whole request is refused with 409 and nothing is sent;
  • not known (pumpHolds: null, e.g. after an import on a new phone): the other settings are written, then the verify decides. 01 means the pump holds the limits (skipped, outcome unchanged (verify 01): …); otherwise the limits are reported "accepted": false with the way to change them.

POST /settings/write?setting=NAME | ?all=true

Writes stored values without changing them: one setting by name or opcode (setting=LOOP_CONFIG, setting=0x8700), every unwritten one (all=true), or both (all=true&setting=DELIVERY_LIMITS); then re-verifies. Same response as /settings/set (action: "settings-write"); 200 {…, "ok": true, "note": "nothing to write"} when nothing is unwritten.

POST /settings/write-limits

The write step of the Change delivery limits wizard: with basal stopped, writes the delivery limits and every setting still marked unwritten (the limits first: the basal and carb pattern messages carry the max basal rate), then re-verifies. Same response as /settings/set (action: "settings-write-limits"). 409 while basal runs ("not written: basal is running, …"). The whole change over REST:

curl -s -X POST --data '{"maxBolusUe2": 400}' "http://127.0.0.1:8090/settings/set"   # 409 while basal runs: stored, not sent
curl -s -X POST "http://127.0.0.1:8090/pump/stop-basal"
curl -s -X POST "http://127.0.0.1:8090/settings/write-limits"                         # writes, then verify 01
curl -s -X POST "http://127.0.0.1:8090/pump/resume-basal"

POST /settings/configure (= POST /setup/configure)

Configure pump: writes every stored setting, all 20, in the configure order, each once, 400 ms apart; waits up to 12 s for configurationState 0x1FFF; then verifies. A refused write is recorded and the run goes on; a write with no answer (outcome unknown) or that could not be sent ends the run. A write whose firmware gate is above the pump's firmware is not sent; it is skipped and reported.

curl -s -X POST "http://127.0.0.1:8090/settings/configure"
{"action": "configure", "ok": true,
 "result": "20/20 writes accepted; configurationState 0x1FFF; verify 01",
 "writes": [
   {"setting": "IDLE_ALERT", "opcode": "0x8000", "accepted": true, "outcome": "accepted", "valueSent": "0F00"},
   "… 19 more, in order …"
 ],
 "verifyMatch": true, "configurationState": "0x1FFF"}
  • ok is true only when every write was accepted (or skipped because the pump already holds it) and verify did not answer 00.
  • A write's outcome is accepted, refused: <NACK>, outcome unknown (no answer), not sent: …, skipped: 0x8017 is not tested on pump firmware 13.50; TwiistOff sends it only on 13.68 or later, or for the delivery limits while basal runs unchanged: … / unchanged (verify 01): … ("skipped": true) or not written: ….
  • On a delivering pump whose limits are unchanged the result reads 19/19 writes accepted; Delivery limits unchanged, not rewritten; configurationState 0x1FFF; verify 01.
  • 409 with the delivery-limits refusal when the stored limits differ from the pump's while basal runs: nothing is sent; use the Change delivery limits wizard or /settings/write-limits.
  • 409 {"action":"configure","ok":false,"error":"blocked at CONFIGURE: …"} when it cannot start: not armed, no status yet, cassette-change mode, priming, a blocking pump condition, or invalid stored values. Nothing is sent then.
  • DANGER (MED): rewrites every therapy setting, including the basal pattern and the closed loop.

POST /settings/verify (= POST /setup/verify)

verifyTherapySettings 0x800F with the app's 42-byte record. Read-only for the pump.

curl -s -X POST "http://127.0.0.1:8090/settings/verify"
# -> 200 {"ok":true,"action":"verify","result":"verify=01: the pump holds this app's settings","snapshot":{…}}
#    or   "result":"verify=00: the pump's settings differ from this app's"

5.12 Conditions and recovery

These routes expose the condition table and the recovery wizards (Setup and recovery §6.3–6.4). The wizards' buttons in the app call the same SetupRunner methods as the command routes below, so a recovery can be walked from the phone, from a script, or half and half.

GET /pump/conditions

The active pump conditions, highest priority first, and for every kind of command either "allowed" or the refusal the app would give.

curl -s "http://127.0.0.1:8090/pump/conditions"
{
  "conditions": [
    {"condition": "UNCONFIGURED", "severity": "BLOCKING",
     "text": "Pump not configured (configurationState 0x0000)",
     "action": "Configure pump: write this app's settings (Cassette set-up, or Settings).",
     "recovery": "CONFIGURE"},
    {"condition": "ALERT", "severity": "WARNING", "text": "Pump alert: …", "action": "Read it, then clear it.", "recovery": null}
  ],
  "commands": {
    "STOP": "allowed", "READ": "allowed", "ALARM_RESET": "allowed", "SILENCE_ALARM": "allowed",
    "CLEAR_ALERT": "allowed", "SETTINGS_WRITE": "allowed", "CHANGE_MODE": "allowed",
    "FILL": "allowed", "PRIME": "allowed", "PRIME_COMPLETE": "allowed",
    "START_BASAL": "start basal refused: Pump not configured (configurationState 0x0000). Configure pump: …",
    "TEMP_BASAL": "temp basal refused: …", "BOLUS": "bolus refused: …", "CANNULA_FILL": "cannula fill refused: …"
  },
  "suggestedWizard": "CONFIGURE"
}

severity is BLOCKING, WARNING or INFO; recovery names the wizard that resolves the condition. UNTESTED_FIRMWARE (a WARNING that blocks nothing) is active when the pump reports firmware other than RIS messages 13.76 / events 14.32; suggestedWizard is the wizard GET /recovery opens without kind.

GET /recovery[?kind=KIND]

One wizard's plan, computed from the live pump state and the recorded choices. KIND is CONFIGURE, ALARM, BATTERY_CHANGE, REARM, NEW_PHONE, CHANGE_MODE or CHANGE_LIMITS; without kind the conditions' suggestion is used (and when there is none, only the list of wizards is returned with a note). Each step has a state (DONE, NOW, WAIT, LATER, SKIPPED), its instruction, and the buttons the app shows for it; current is the first step that is NOW or WAIT.

curl -s "http://127.0.0.1:8090/recovery?kind=ALARM"
{
  "wizards": ["CONFIGURE", "ALARM", "BATTERY_CHANGE", "REARM", "NEW_PHONE", "CHANGE_MODE", "CHANGE_LIMITS"],
  "kind": "ALARM", "title": "Alarm recovery", "current": "What happened",
  "steps": [
    {"title": "What happened", "state": "NOW",
     "text": "Cassette Not Attached: the cassette came off while delivering. Delivery has stopped. …", "actions": []},
    {"title": "Reset the alarm (the pump restarts)", "state": "NOW",
     "text": "Once the cause is fixed: Reset the alarm (alarmReset 0x0D00). …", "actions": ["ALARM_RESET"]},
    {"title": "The pump restarts", "state": "LATER", "text": "…", "actions": []},
    {"title": "Re-arm on the same link", "state": "DONE", "text": "Armed; commands are answered.", "actions": []},
    {"title": "Cassette attached and self-tested", "state": "NOW", "text": "…", "actions": []},
    {"title": "Same cassette or a new one?", "state": "LATER", "text": "Did you put the same cassette back, or a new one?",
     "actions": ["SAME_CASSETTE", "NEW_CASSETTE"]},
    {"title": "Line fixed, or infusion set changed?", "state": "LATER", "text": "…", "actions": []},
    {"title": "Verify settings", "state": "LATER", "text": "verifyTherapySettings 0x800F must answer 01 before basal starts.", "actions": []},
    {"title": "Start basal", "state": "LATER", "text": "…", "actions": []}
  ],
  "choices": {"sameCassette": null, "lineFixed": null, "changeCommandSent": false, "alarmResetSent": false}
}

Each action maps to a route: ALARM_RESET → /pump/alarm-reset, SILENCE → /pump/silence, STOP_BASAL → /pump/stop-basal, BATTERY_CHANGE → /pump/battery-change, REARM → /pump/rearm, ARM / STORE_KEY → /setup/arm, CONFIGURE → /settings/configure, VERIFY → /settings/verify, IMPORT_SETTINGS → /settings/import, LOAD_BENCH_PRESET → /settings/preset?name=bench-replay, SAME_CASSETTE / NEW_CASSETTE / LINE_FIXED / SET_CHANGED → /recovery/choice, ADJUST_VOLUME → /pump/cassette-volume, START_BASAL → /pump/resume-basal, WRITE_LIMITS → /settings/write-limits, OPEN_CASSETTE_SETUP → the /setup/* stages; OPEN_CONNECT, OPEN_ALARM_WIZARD and OPEN_BATTERY_WIZARD open a page or another wizard.

POST /recovery/begin?kind=KIND

Starts a wizard's record of choices (keeps nothing from an earlier recovery) and notes the pump's resetCount, so a later restart is recognised. Answers with the plan, plus "ok": true. App only. 400 without a valid kind.

POST /recovery/choice?sameCassette=true|false&lineFixed=true|false

changed?". A new cassette or a changed set turns the recovery into a new-cassette set-up at once (fill and prime are required again), exactly like the app's New cassette and Infusion set changed buttons; no separate POST /setup/new-cassette is needed.

curl -s -X POST "http://127.0.0.1:8090/recovery/choice?sameCassette=true"
# -> 200 {"ok":true,"action":"recovery-choice","result":"recovery choice: same cassette","snapshot":{…}}

400 when neither parameter is given.

Recovery commands

Each route sends one command, once, through the therapy-number path, and answers like the stage actions: {"ok", "action", "result" | "error", "snapshot"}. A refusal by a pump condition, a NACK ("refused: …"), a lost answer ("… - read the status and the pump log before deciding; nothing was resent") or an unsendable command ("not sent: …") is ok: false.

Route Sends Notes App control
POST /pump/stop-basal stopBasal 0x8103 a stop: refused only when nothing can be sent Suspend Insulin Delivery (Pump Menu, battery-change wizard)
POST /pump/resume-basal verifyTherapySettings 0x800F, then startBasal 0x8100 from the stored settings; refused when verify answers 00 Resume basal, Start basal in a wizard
POST /pump/silence silenceAlarms 0x0700 (therapy number only) not yet sent on the bench; check status byte 91 bit 0x04 afterwards Silence the alarm, Pump tools
POST /pump/battery-change batteryChange 0x8805 refused while basal runs, and below RIS messages 13.54 (nothing is sent in its place); the pump-side effect of 0x8805 is not yet confirmed battery-change wizard, Pump tools
POST /pump/cassette-change cassetteChange 0x8804 (therapy number only) refused while basal runs; the pump stays in cassette-change mode until it restarts Change cassette…, Pump tools
POST /pump/cassette-volume?units=290 (or volumeUe2=) adjustStartingCassetteVolume 0x8002, u16 0.01 U 0.01–300.00 U; refused when a fill would be Correct volume
POST /pump/clear-alert?mask=0040 clearPumpAlert 0x0400 + u16 mask mask is hex, 0x0001–0xFFFF Clear on an alert banner, Pump tools
POST /pump/clear-notice?mask=0010 clearPumpNotice 0x0402 + u16 mask as above Clear on a notice banner, Pump tools
POST /pump/rearm arm on the existing link with the stored key, then a read-only log read for a restart whose automatic re-arm failed, or a path left REARM_FAILED; waits for an automatic re-arm that is still running instead of arming twice; when the read goes unanswered the app re-arms once more by itself before answering Re-arm now, Pump tools, Reconnect
curl -s -X POST "http://127.0.0.1:8090/pump/battery-change"
# -> 200 {"ok":false,"action":"battery-change","error":"basal is running: stop basal (Suspend Insulin Delivery) first","snapshot":{…}}
curl -s -X POST "http://127.0.0.1:8090/pump/stop-basal"
# -> 200 {"ok":true,"action":"stop-basal","result":"stopBasal accepted (0x8103); confirm the basal rate 0 in the next status","snapshot":{…}}
curl -s -X POST "http://127.0.0.1:8090/pump/battery-change"
# -> 200 {"ok":true,"action":"battery-change","result":"batteryChange accepted (0x8805): remove the cassette, change the battery, attach the same cassette","snapshot":{…}}

DANGER (HIGH) for stop / resume basal and the change commands: they stop or start delivery, or put the pump in a state it leaves only by restarting.

0x0E00–0x0E02 (acknowledge notification audio) are refused by every command route, including /pump/command and /pump/command-token (which reports NOT_SENT), before a frame is sealed: the pump refuses them as invalid commands. Use /pump/silence and the clear routes instead.

5.13 Retired

POST /command → HTTP 410 Gone

This route predates the solved channel crypto: it built len/seq/opcode/payload/auth/CRC but never sealed the frame, so the pump ignores everything it produces (and malformed frames can drop the link). It is retired, not deleted, so stale callers get an explanation instead of a bare 404.

curl -s -i -X POST "http://127.0.0.1:8090/command?opcode=0310&seq=1"
# HTTP/1.1 410 Error
{
  "ok": false,
  "deprecated": true,
  "error": "/command is retired: it builds an UNSEALED frame (pre-crypto) and the pump ignores it",
  "use": [
    "POST /pump/command?opcode=&payload=  (sealed; requires an armed session)",
    "POST /pump/command-token?opcode=&value=  (sealed; therapy number prefixed)",
    "POST /pump/raw-wire?hex=&confirm=true  (fully pre-sealed wire bytes)"
  ]
}

5.14 Phone: permissions and the data folder

The same state the Permissions & files page shows (Permissions and files). None of these routes talks to the pump. The bridge cannot grant a permission: Android only lets the user do that, from the page's buttons.

GET /permissions

curl -s http://127.0.0.1:8090/permissions
{
  "missing": ["NOTIFICATIONS", "EXACT_ALARMS"],
  "items": [
    {"id": "BLUETOOTH", "title": "Bluetooth", "granted": true, "applies": true, "fix": "NONE", "state": "allowed", "why": "…"},
    {"id": "NOTIFICATIONS", "title": "Notifications", "granted": false, "applies": true, "fix": "RUNTIME_DIALOG", "state": "not allowed", "why": "…"},
    {"id": "BATTERY_OPTIMISATION", "title": "Ignore battery optimisation", "granted": true, "applies": true, "fix": "NONE", "state": "the app ignores battery optimisation", "why": "…"},
    {"id": "BACKGROUND_USE", "title": "Background use", "granted": true, "applies": true, "fix": "NONE", "state": "not restricted", "why": "…"},
    {"id": "EXACT_ALARMS", "title": "Alarms & reminders", "granted": false, "applies": true, "fix": "SETTINGS_PAGE", "state": "not allowed", "why": "…"}
  ],
  "dataFolder": {
    "path": "/storage/emulated/0/Android/data/com.infusionset.twiistoff/files",
    "external": true,
    "subfolders": ["logs", "exports"],
    "chosenFolder": null,
    "chosenFolderAccess": false
  }
}

fix is how the page fixes an item: RUNTIME_DIALOG (Android's permission dialog), SYSTEM_DIALOG (the one-tap battery dialog), SETTINGS_PAGE (a settings page the user changes) or NONE. applies: false means Android does not ask for it on this version (exact alarms before Android 12); it then counts as granted. GET /status carries the missing list as permissionsMissing.

POST /permissions/test-notification

Posts a test notification. {"ok": true}, or HTTP 409 with why not ("notifications are not allowed").

GET /files

The data folder and its files, newest first.

{
  "dataFolder": { "path": "/storage/emulated/0/Android/data/com.infusionset.twiistoff/files", "…": "as above" },
  "logs": [{"path": "logs/twiistoff-2026-12-04.log", "bytes": 1843311, "modifiedMs": 1796385600000}],
  "exports": [{"path": "exports/twiistoff-settings-20261204-120000.json", "bytes": 2210, "modifiedMs": 1796385600000}]
}

GET /files/get?path=logs/NAME[&tailBytes=N]

One file's text (text/plain). path is a path from GET /files: a file directly in logs/ or exports/, nothing else (404 otherwise). tailBytes=N returns the last N bytes, which is how to read the end of today's log. A file over 8 MB without tailBytes answers HTTP 413; pull it with adb pull instead.

curl -s "http://127.0.0.1:8090/files/get?path=logs/twiistoff-2026-12-04.log&tailBytes=20000"

POST /files/copy

Copies logs/ and exports/ to the folder chosen on the Permissions & files page: {"ok": true, "copied": 7, "folder": "Documents/TwiistOff"}, or HTTP 409 when no folder is chosen or the app lost access to it.


6. Worked flows

6.0 Pair a pump from nothing, then arm

Full human procedure (physical pump steps, registration boundary): Pairing and setup. Bridge-only version, GATT-level operations included:

BASE=http://127.0.0.1:8090
# 1. pump in pairing mode: charged battery, cassette off, ~5 s button hold until Ready Beep
curl -s -X POST $BASE/scan/start; sleep 6
ADDR=$(curl -s $BASE/devices | tr '{' '\n' | grep '"isPumpCandidate":true' | sed -n 's/.*"address":"\([^"]*\)".*/\1/p' | head -1)
curl -s -X POST $BASE/scan/stop
# 2. connect
curl -s -X POST "$BASE/connect?address=$ADDR"
# 3. bond: the pump refuses a protected operation until it is authenticated, so start pairing
#    either by subscribing to a protected characteristic or explicitly:
curl -s -X POST $BASE/subscribe-all          # or: curl -s -X POST "$BASE/bond/start"
curl -s $BASE/bond                            # pendingPasskeyRequest == true -> supply the PIN
curl -s -X POST "$BASE/pin?value=NNNNNN"      # 6-digit PIN from the pump label (in-app passkey mode)
# 4. import the per-user material into the app (saved locally, no pump write for the blob):
#    blob: preview then persist; LTSS: body of /pump/arm (also persisted)
curl -s -X POST "http://127.0.0.1:8090/setup/blob?blob=$(cat replacement_blob.hex)"            # preview
curl -s -X POST "http://127.0.0.1:8090/setup/blob?blob=$(cat replacement_blob.hex)&confirm=true"  # store
# 5. arm with the LTSS from the pump's own registration (secret; from the environment)
curl -s -X POST --data "$LTSS" "$BASE/pump/arm?respond=false"
# 6. where am I? read-only checklist + next action + stored blob metadata
curl -s $BASE/setup
# 7. confirm live status, then release the pump
curl -s $BASE/pump/ready
curl -s -X POST $BASE/disconnect

Notes:

  • In pairing mode the pump advertises for a limited time. If connect fails during pairing, put it in pairing mode again and retry. Once bonded, reconnecting needs no scan and no button press.
  • If the pump is still bonded to another phone or the vendor's app, it may refuse this bond, and the old bond must be removed on that device.
  • A wrong LTSS yields armed:false (the frames never decrypt), not a false success. Nothing is left armed.
  • GET /setup is the cheap poll in an automation loop: it reports link/bond/arm state and the next expected action without touching the pump.

6.1 Connect, arm, read status, disconnect

BASE=http://127.0.0.1:8090
curl -s -X POST $BASE/scan/start; sleep 6
ADDR=$(curl -s $BASE/devices | tr '{' '\n' | grep '"isPumpCandidate":true' | sed -n 's/.*"address":"\([^"]*\)".*/\1/p' | head -1)
curl -s -X POST $BASE/scan/stop
curl -s -X POST "$BASE/connect?address=$ADDR"; sleep 5
curl -s -X POST "$BASE/mtu?value=247"
curl -s -X POST --data "$LTSS" "$BASE/pump/arm?respond=false"; sleep 3
curl -s $BASE/pump/ready
curl -s -X POST $BASE/disconnect
curl -s $BASE/status   # {"state":"DISCONNECTED", ...}

6.2 Read the pump clock, sync it, verify

curl -s -X POST $BASE/pump/time
curl -s $BASE/pump/state | tr ',' '\n' | grep -E 'pumpTimeUtc|residual'

Beware: setTime is a Therapy command, so if the therapy chain is desynced the pump may NACK it (pump refused 0x800B: ...). Recover the chain from a fresh pumpStatus (the app retries once automatically).

6.3 Raw opcode with explicit prefix policy

# Simple read: getPumpIdentification
curl -s -X POST "$BASE/pump/command?opcode=0310&payload="
# Therapy: settings write through the token path
curl -s -X POST "$BASE/pump/command-token?opcode=8016&value=0003"
# Check what was actually transmitted:
curl -s $BASE/pump/state | tr ',' '\n' | grep lastPayloadSent

The Dev → Raw panel does the same with Auto/Simple/Therapy prefix modes and a pump/ready precondition.

6.4 Pre-sealed frame replay

WIRE=$(cat sealed_frame.hex)   # LE64(packet) || AES-CCM(frame), from a capture or a script
curl -s -X POST "$BASE/pump/raw-wire?hex=$WIRE"                    # 409: needs confirm
curl -s -X POST "$BASE/pump/raw-wire?hex=$WIRE&confirm=true"       # written verbatim

Read the pump's replies from GET /notifications; the app only predicts the decoded opcode.

6.5 Replacement blob preview, write, then read back (bench, user-approved only)

BLOB=$(cat replacement_blob.hex)                       # 608-610 bytes as hex
curl -s -X POST "$BASE/pump/replacement?blob=$BLOB"    # preview: size, sha256, expiry, chunks, serial
curl -s -X POST "$BASE/pump/replacement?blob=$BLOB&confirm=true"   # writes [n | data] packets + CRC32
SHA=$(curl -s -X POST "$BASE/pump/replacement?blob=$BLOB" | sed -n 's/.*"sha256":"\([^"]*\)".*/\1/p')
curl -s "$BASE/pump/replacement/readback?expectedSha256=$SHA"      # notify readback + compare

Preconditions: bonded, armed, MTU 247, and the blob must be the one issued for this pump. The readback is read-only and works after the write; compare matchesExpected/matchesLastWrite and check expirationUtc for staleness. A partial write returns an explicit partial-blob error — stop and review before retrying.

This confirmed route needs an armed session; the pairing-mode form is POST /pump/replacement?unarmed=true (above). Open questions about adoption are in Pairing and setup §9.

6.6 Alarm recovery on the same cassette

BASE=http://127.0.0.1:8090
curl -s $BASE/pump/conditions                       # ALARM, suggestedWizard ALARM
curl -s -X POST "$BASE/recovery/begin?kind=ALARM"   # plan from the live state
# fix the cause physically (reattach the cassette / clear the line), then:
curl -s -X POST $BASE/pump/alarm-reset              # the pump restarts; the app re-arms by itself
curl -s "$BASE/recovery?kind=ALARM"                 # wait for re-arm + self-test steps to be DONE
curl -s -X POST "$BASE/recovery/choice?sameCassette=true&lineFixed=true"
curl -s -X POST $BASE/settings/verify               # must say verify=01
curl -s -X POST $BASE/pump/resume-basal             # verify + startBasal; no fill, no prime
curl -s $BASE/pump/ready                            # confirm "delivering basal …"

6.7 Move the settings to a new phone

# old phone
curl -s $BASE/settings/export > twiistoff-settings.json
# new phone (after bonding / entering the key and arming)
curl -s -X POST --data @twiistoff-settings.json $BASE/settings/import
curl -s -X POST $BASE/settings/verify               # 01: the pump holds them; 00: configure or find the right export
curl -s -X POST $BASE/settings/configure            # only if verify answered 00 or the pump is unconfigured

7. Errors, traps and gotchas

Symptom Cause / fix
{"ok":false,"error":"not armed"} POST /pump/arm first; a link drop invalidates the session.
arm fails with "granted MTU N" Request POST /mtu?value=247 (or reconnect) before arming. Below 247 the arm write is silently ignored by the pump.
no response to opcode 0x0502 Timeout: pump asleep/disconnected, wrong packet/seq chain, or a command the pump refuses. Reset (reconnect + arm).
Command acknowledged but state unchanged "Succeeded" = the pump answered. Confirm in the next pumpStatus/GET /pump/ready/GET /pump/history.
Empty payload was sent The /pump/command payload vs /pump/command-token value trap. Both routes now accept both names, and payloadSent in the response and in GET /pump/state is authoritative.
payloadSent still empty on a Therapy command The prefix alone can be a valid payload (payloadSent = 4 hex chars, e.g. 7B6A); check valueSent.
200 {"ok":false, "error":"unknown key"} key= did not resolve: read GET /gatt and copy the composite key.
Read of e5332027 refused Expected for a plain ATT read. Use GET /pump/replacement/readback (notify-based) to read the stored blob; ?gatt=true shows the refusal verbatim.
Readback times out with no packets The pump pushes the blob only when bonded, with the CCCD enabled, after the trigger write, at MTU 247. Check GET /bond, GET /status (mtu), and keep the default trigger.
409 from /pump/raw-wire Add confirm=true; without it nothing is written.
410 from /command Retired route; use /pump/command, /pump/command-token or /pump/raw-wire.
Bonding prompt never appears Subscribe to a protected characteristic (or POST /subscribe-all) to trigger it; POST /pin supplies the label PIN.
Pump advertises then disappears During pairing it advertises for a limited time; put it in pairing mode again. A connected pump does not advertise. A bonded pump needs no scan: POST /setup/reconnect connects to its remembered address. Its advertising address rotates (RPA) — find it by name/manufacturer data, not by address.
arm reports a previous session salt / armed:true then GET /pump/state says armed:false The app restarted (reinstall/update) under a live pump link and attached to the inherited link; the pump kept serving the old session. Fixed: /connect recycles the inherited link on the first connect after a process start, session state is reset at every boundary, and arm only reports success after a sealed pumpStatus arrives. If you still see it: POST /disconnect, POST /connect, then arm.
NACK 0x13EE on a bolus (0x8400) Range check failed, not the delivery gate. The pump rejected an argument outside its limits — most often normalBolus_UE2 (bytes 4–5) above the max bolus. The NACK's debugValue1 is the offending value and debugValue3 the limit (measured: 2560 vs 600 = 25.60 U over the 6.00 U max). Correct the payload; verifyTherapySettings does not change it.
A "0.1 U" bolus is refused 0x13EE Byte-offset trap: normalBolus_UE2 is bytes 4–5. …00000A00… writes 0x0A00 = 2560 = 25.60 U, which the pump refuses as over max bolus; 0.10 U is 0A 00 at bytes 4–5 — see the payload table in Delivery. The corrected value is accepted with 0x8480 and the pump log records deliveredVolume = 10.
/setup/basal or /pump/resume-basal: "verifyTherapySettings (0x800F) answered 00" The pump's settings differ from the app's copy (a pairing cleared them, or another phone set them). POST /settings/configure, or import the export that matches and verify again.
/setup/prime-complete refused at priming state 1 The prime was stopped before the pump's minimum volume. POST /setup/prime again (prime more), stop when drops form, then complete at state 3.
… refused: The pump's closed loop is ON … The pump doses by itself while its loop is on, so every delivery start is refused. Write the loop off: POST /settings/set with {"closedLoop": false}.
/pump/battery-change or /pump/cassette-change: "basal is running" Stop basal first (POST /pump/stop-basal).
pumpStatus delivered UE2 reads 0 for a 0.1 U bolus That field (bytes 56–57) tracks live progress while a bolus is running. A 0.1 U delivery finishes in well under one 5 s status interval, so no broadcast lands inside it; confirm delivery with lastBolusVolume_UE2 (bytes 70–71) and the pump log's 0x005B NORMAL_BOLUS_COMPLETED (deliveredVolume/requestedVolume, UE2). A 1.00 U bolus shows progress normally (0 → 20 → 38 → … → 100).

9. Implementation map

Path Role in the bridge
bridge/RestBridge.kt HTTP server, routing, JSON serialisation, confirm gates
pump/PumpLink.kt Arm/session, command send, setTime, replacement write/readback, raw wire; feeds observer
pump/observe/ Observe-first instrumentation behind GET /pump/observed: PumpObserver (rings + stats), FrameClassifier (response/NACK/unsolicited labelling), StatusTransitions (pumpStatus diff)
protocol/StatusPushes.kt loopStatus (0x8705) / cgmStatus (0x8304) decoders
pump/ReplacementData.kt Blob size/layout validation, packet-numbered write framing with CRC32, write-window ack classification, SHA-256, expiry, readback reassembly
pump/SessionMaterial.kt The per-session material (channel/keys, message sequence, therapy token, status counter, in-flight flag) and its unit-tested reset contract; PumpLink.reset clears it plus the decoded state
protocol/SetTimePayload.kt 0x800B payload (u32 LE seconds since 2008), decode/verify helpers
protocol/RawCommand.kt Simple/Therapy prefix policy, delivery-range classification
protocol/RawWire.kt Pre-sealed wire hex parsing and 255-byte cap
ble/MtuPolicy.kt MTU 247 requirement and error messages
ble/PumpBleManager.kt Scan/connect/GATT/read/write/subscribe/MTU primitives; connectAndAwait inherited-link recycle
pump/SetupRunner.kt The shared executor behind /setup/*, /settings/* writes, /recovery/* and the recovery command routes; the app's wizards and settings pages call the same methods
pump/PairingFlow.kt Stage order, per-action gates and the cassette set-up stages (GET /setup)
pump/PumpSettings.kt / pump/SettingsStore.kt The 20 stored settings, wire encoders, bounds, presets, the 42-byte verify record, the export format; persistence and the "unwritten" set
pump/PumpConditions.kt The condition table behind GET /pump/conditions and every refusal
pump/RecoveryWizards.kt The wizard plans behind GET /recovery
pump/RisGate.kt Firmware gates (e5332001 version block) and the never-sent 0x0E00–0x0E02
MainViewModel.kt Same operations for the phone UI (Advanced / Bench → Pump tools / Raw / Provision, Therapy settings, wizards)