Files
2026-11-11 04:08:00 +01:00

11 KiB
Raw Permalink Blame History

PocketTrainer API (protocol 1)

PocketTrainer hosts one Pokémon from Crystal. The Pokémon walks, eats, trains and takes trainers' challenges on the device, then goes back to Crystal with what it earned there.

The device talks to Crystal in two ways:

  • Device local API. HTTP on the local network. Crystal, or a tool such as tools/pocket_tool.py, can deposit and withdraw a Pokémon or push a challenge directly.
  • Server synchronization. The device calls the Crystal server on its own (POST /api/pocket/v1/sync). The device side is implemented. The server side does not exist yet; tools/pocket_tool.py mock-server stands in for it.

The device never contains a ROM asset. The sprite, species name, base stats and move names come from Crystal, which reads them from the player's ROM.

Identity and pairing

Element Value Where to find it
deviceId PT-69C0-EEB8, derived from the MAC address. This is the device's "number" that trainers find. Options › WiFi & Crystal, GET /api/v1/info
PIN 6 digits, generated at first boot. Required for every local call except info. Options › WiFi & Crystal
Server token Free text, sent as Authorization: Bearer <token> during sync. Set through the portal or the serial port

Data formats

Deposit payload (Crystal → device)

{
  "transferId": "2f1c…",              // unique per transfer, makes a repeated deposit idempotent
  "partyMon": {                        // PartyMon from src/game/party/pokemon.ts, unchanged
    "species": 155, "item": 0, "moves": [33, 52, 44, 45],
    "otId": 51234, "ot": "KAWA", "nickname": "BRAISOU",
    "exp": 973, "statExp": [120, 80, 64, 200, 90], "dvs": 43463,
    "pp": [35, 25, 25, 40], "happiness": 90, "pokerus": 0, "caughtData": 0,
    "level": 12, "status": 0, "hp": 34, "stats": [34, 20, 17, 23, 21, 18]
  },
  "species": {                          // from the ROM's BaseData
    "name": "CYNDAQUIL",
    "baseStats": [39, 52, 43, 65, 60, 50],
    "types": ["FIRE"],                  // pokecrystal names or numeric ROM IDs (20 = FIRE)
    "growthRate": "medium_slow",        // or 0..5 (GROWTH_* constants)
    "baseExp": 65
  },
  "moves": [                            // same order as partyMon.moves
    {"id": 33, "name": "TACKLE", "type": "NORMAL", "power": 35, "pp": 35}
  ],
  "sprite": {                           // front picture, already decoded
    "width": 56, "height": 56,          // up to 56×56
    "palette": ["#ffffff", "#f8c048", "#c04020", "#000000"],
    "pixels": "base64…"                 // 2 bits per pixel, row-major, most significant bits first
  },
  "replaceDemo": false                  // local API only: replaces a demo creature
}

Rules:

  • Color 0 of the sprite is treated as transparent. The sprite is optional; without it the device shows a "?" placeholder.
  • The device refuses eggs (partyMon.egg) and Pokémon holding mail (partyMon.mail). Egg support is planned (see the end of this document).
  • PP: the raw byte (bits 6–7 = PP Ups) is kept. The device computes the maximum from moves[i].pp.

Return payload (device → Crystal)

The return payload contains the same transferId, partyMon (current state), species and sprite, plus a pocket block:

"pocket": {
  "deviceId": "PT-69C0-EEB8",
  "depositedAt": 1794000000, "returnedAt": 1794086400,   // epoch, 0 if the time was unknown
  "steps": 8421,
  "earned": { "exp": 1520, "levels": 2, "happiness": 7, "statExp": [337, 120, 0, 450, 0] },
  "care": { "satiety": 64, "mood": 82 },
  "record": { "wins": 5, "losses": 1, "games": 9, "quests": 6 },
  "deposited": { …the partyMon exactly as it arrived… }
}

What the device changes in partyMon, and how:

Field Change on the device
exp, level Gen 2 curves (CalcExpAtLevel). Steps, battles (baseExp × level / 7 × 1.5) and challenges. Capped at the exp for level 100.
stats Recomputed with calcStat (same squareRoot, DV and 999-cap logic).
statExp Training mini-games (Attack/Defense/Speed/Special) and walking (HP). Capped at 65535.
happiness Petting, feeding, training, wins, walking. Drops if the Pokémon is left starving. Range 0–255.
hp, pp, status Battles reduce them; walking restores them.

The device does not do the following. When the Pokémon returns, Crystal should:

  1. Re-validate everything against the ROM: recompute level from exp, stats from statExp and DVs, and cap HP and PP.
  2. Run the learnsets for each level gained (earned.levels). The device teaches no moves.
  3. Handle evolution on the next level-up or at Crystal's usual checkpoint. The device does not evolve Pokémon.
  4. Use pocket.deposited together with earned to detect a tampered return. For example, earned.exp should stay plausible given pocket.steps.

Challenge

Battle challenge:

{
  "id": "c-91ab",                       // 23 characters max, idempotent
  "trainer": "Youngster Joey",
  "message": "My Rattata is in the top percentage!",
  "kind": "battle",
  "team": [                              // 1 to 3 Pokémon
    {"name": "RATTATA", "level": 9, "types": ["NORMAL"],
     "stats": [28, 18, 14, 22, 12, 13],  // or "baseStats" (the device then uses average DVs)
     "baseExp": 57,
     "moves": [{"name": "TACKLE", "type": "NORMAL", "power": 35, "pp": 35}],
     "sprite": { …same format as the deposit… }}
  ],
  "reward": {"exp": 50, "berries": 2},
  "expiresAt": 1794086400                // epoch, 0 = never
}

Mini-game challenge: "kind": "minigame", "game", and "target" (the score to reach). Possible games:

game Stat trained Score
force Attack Taps in 6 s
guard Defense Hits out of 8
reflex Speed Targets hit in 20 s
memory Special Length of the longest sequence repeated

Challenge result (device → server)

{"challengeId": "c-91ab", "outcome": "won", "score": 0, "at": 1794001234}

outcome is one of: won, lost, forfeit, success, fail, declined, expired.

Device local API

Base: http://<device-ip>/ (also reachable as pockettrainer.local via mDNS). The API is CORS-enabled and answers Private Network Access preflights. Every call except info needs the X-Pocket-Pin: <PIN> header.

Method and path Purpose
GET /api/v1/info Device ID, firmware, step count, Pokémon summary (or null).
GET /api/v1/pokemon Return payload, read-only (nothing changes).
POST /api/v1/pokemon Deposit. Returns 201 on success; 200 with already_deposited for the same transferId; 409 occupied; 400 invalid_pokemon; 423 busy (battle or mini-game in progress).
POST /api/v1/pokemon/withdraw Optional body {"withdrawalId"}. Returns {"withdrawalId", "pokemon": <return payload>}. The Pokémon is locked but stays on the device.
POST /api/v1/pokemon/withdraw/confirm Body {"withdrawalId"}. Crystal calls it after saving the Pokémon; the device then deletes its copy. Repeating the call is harmless.
POST /api/v1/pokemon/withdraw/cancel Unlocks the Pokémon.
GET /api/v1/challenges Pending challenges.
POST /api/v1/challenges Pushes a challenge (format above).
GET /api/v1/outbox Results not yet acknowledged by the server.

The withdrawal happens in two phases, so a Pokémon is never lost or duplicated if the connection drops:

  1. Crystal calls withdraw and receives the payload.
  2. Crystal saves the Pokémon in its save file.
  3. Crystal calls confirm.

If step 2 fails, Crystal calls cancel, or simply calls withdraw again: it is idempotent and returns the same withdrawalId.

Crystal is served over HTTPS, so a browser will block calls to http://<lan-ip>. In production, go through the server (below). The local API is for development and for tools.

Server synchronization (to be implemented on the Crystal side)

The device calls POST {server}/api/pocket/v1/sync when it connects, then every 15 minutes, and also on demand from Options › WiFi & Crystal › Synchro.

Request headers: Content-Type: application/json and Authorization: Bearer <token>.

Request:

{
  "protocol": 1, "firmware": "0.2.0", "deviceId": "PT-69C0-EEB8", "sentAt": 1794000000,
  "steps": 12345,
  "pokemon": { "nickname", "species", "level", "hp", "maxHp", "happiness", "satiety", "mood",
               "origin", "transferId", "withdrawPending" } | null,
  "withdrawal": { "withdrawalId": "…", "pokemon": <return payload> },   // only while a withdrawal is in progress
  "depositResult": { "transferId": "…", "error": "" },                 // after a deposit; "" = accepted
  "results": [ <challenge result>, … ],
  "knownChallenges": ["c-91ab", …]
}

Response (every field is optional):

{
  "serverTime": 1794000000,
  "challenges": [ <challenge>, … ],       // the device ignores IDs it already knows
  "ackResults": ["c-91ab"],               // results the server stored; the device deletes them
  "deposit": <deposit payload>,           // Pokémon to deliver (if the device is empty or holds a demo creature)
  "withdraw": { "withdrawalId": "…" },    // Crystal is recalling the Pokémon
  "withdrawalConfirmed": "…"              // the server stored the return; the device deletes its copy
}

Expected flows:

  • Deposit from Crystal. Crystal removes the Pokémon from the party or PC on its side, and the server queues deposit. At the next sync the device installs it and sends back depositResult. The server only considers the transfer complete when depositResult.error is empty. If there is an error, Crystal gives the Pokémon back.
  • Recall from Crystal. The server sends withdraw. The device locks the Pokémon and resyncs right away with withdrawal. The server stores the return, then answers withdrawalConfirmed.
  • Trainer challenges. The server pushes challenges to a given deviceId, for example a friend who entered your number. The device sends back the results, and the server acknowledges them with ackResults.

Security (prototype)

  • Over https://, the device does not check the certificate yet (setInsecure). A CA bundle or certificate pinning is needed before real use.
  • The server token is stored in clear in NVS.

Not covered yet

  • Eggs, as in the Pokéwalker. This lines up with section 7 of docs/PLAN.md in Crystal: on the device, steps would count down happiness, which holds the remaining egg cycles.
  • Evolution and moves learned on the device: these are left to Crystal on return.
  • Several Pokémon at once.