# Connect your foosball table to packeroo

> The public packeroo API with a guide, a reference and runnable examples in Python, JavaScript, C#, PHP, Go, Java, curl and for the ESP32. Today you pair a table device with a table.

## What you can build today

A device at a table asks for a code and gets its token with it. It shows the code, whoever manages the location enters it in the packeroo app, and from then on the device signs in with its token. It reads which table, location and organization it is paired with. Two operations do this: `POST /device-pairings` and `GET /device`. In the sandbox a third one lets a device confirm its code itself: `POST /sandbox/device-pairings/confirm`.

The [guide](https://developers.packeroo.com/en/guides/pair-a-table-device/) has the whole program in eight languages, from asking for the code to the first answer with 200.

## What is planned

These parts are decided but not built yet. They are listed so you know where the API is going:

- read the queue of a table: which match is running, who plays next
- start a match at the table, report goals live and report the result from the table
- recognize players by their chip
- organization keys for intranets, dashboards and chat bots
- webhooks

We name a date once it is fixed. If you need an organization key, [put your name down](mailto:info@packeroo.com?subject=Organization%20key) and we write to you once it exists. Every new operation appears in the [changelog](https://developers.packeroo.com/en/changelog/) on the day it becomes public.

## In three steps

1. **Ask for a code.** Your device sends `POST /device-pairings` and gets a code of six characters, valid for ten minutes, and its token.
2. **Show the code.** The device shows the code as two groups of three and as a QR code. Whoever manages the location scans it with their phone, or types it in the app: under Profile › Organization › Tables, then "Pair a device" at the table, or at `app.packeroo.com/verbinden`.
3. **Sign in.** The device asks `GET /device` every five seconds. Until the code has been entered, the answer is 401; then it is 200 with the table, location and organization.

## Everything for the integration

- [Quickstart](https://developers.packeroo.com/en/quickstart/)
  From the code to a paired device, in eight languages.
- [Pair a table device](https://developers.packeroo.com/en/guides/pair-a-table-device/)
  The guide with the complete program, the error cases and the rules for the display at the table.
- [Concepts](https://developers.packeroo.com/en/concepts/)
  Tokens, idempotency keys, error answers, rate limits, User-Agent, times and versions.
- [Reference](https://developers.packeroo.com/en/reference/)
  Every public operation with schemas, errors and code samples in many languages.
- [Postman and OpenAPI](https://developers.packeroo.com/en/downloads/)
  The collection with a sandbox environment, and the contract as JSON and YAML.
- [For AI assistants](https://developers.packeroo.com/en/ai/)
  `llms.txt`, every page as Markdown and the OpenAPI file at fixed addresses.

## Sandbox and contact

To try things out there is the sandbox at `https://api.qm.packeroo.com/api/v1`; tokens there start with `pkd_test_`. There your device pairs itself, with a test table of its own and without signing up with us: the [quickstart](https://developers.packeroo.com/en/quickstart/) shows how. We answer questions at [info@packeroo.com](mailto:info@packeroo.com).

---

# Your first call in five minutes

> Ask the sandbox for a code for a table device and read GET /device with its token. With Python, JavaScript, C#, PHP, Go, Java, curl and for the ESP32.

You need a terminal, and the Arduino IDE for the ESP32. You do not need a packeroo account in the sandbox: a device asks for its code without signing in and confirms it there itself. The language you pick here holds for every example on this page, in the guide and in the reference. PowerShell, Ruby, Kotlin, Swift, Dart and Rust are in the [reference](https://developers.packeroo.com/en/reference/).

## 1. Ask for a code

Send `POST /device-pairings` to the sandbox. Two headers are required: `User-Agent` names your device with product and firmware, and `Idempotency-Key` is a UUID or ULID you make new for this request.

Python:

```python
import json, urllib.request, uuid

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/device-pairings",
    method="POST",
    data=json.dumps({"model": "Kickertisch-Beispiel", "firmware": "1.0"}).encode(),
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Idempotency-Key": str(uuid.uuid4()),
        "Content-Type": "application/json",
        "Accept-Language": "en",
    },
)
with urllib.request.urlopen(request) as response:
    print(json.load(response)["data"])
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/device-pairings', {
  method: 'POST',
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    'Idempotency-Key': crypto.randomUUID(),
    'Content-Type': 'application/json',
    'Accept-Language': 'en',
  },
  body: JSON.stringify({ model: 'Kickertisch-Beispiel', firmware: '1.0' }),
})
console.log(response.status, (await response.json()).data)
```

C#:

```csharp
using System.Net.Http.Json;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.qm.packeroo.com/api/v1/device-pairings")
{
    Content = JsonContent.Create(new { model = "Kickertisch-Beispiel", firmware = "1.0" }),
};
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
request.Headers.AcceptLanguage.ParseAdd("en");
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$bytes = random_bytes(16);
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
$key = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));

$curl = curl_init('https://api.qm.packeroo.com/api/v1/device-pairings');
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => ["Idempotency-Key: $key", 'Content-Type: application/json', 'Accept-Language: en'],
    CURLOPT_POSTFIELDS => json_encode(['model' => 'Kickertisch-Beispiel', 'firmware' => '1.0']),
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
package main

import (
	"bytes"
	"crypto/rand"
	"fmt"
	"io"
	"net/http"
)

func main() {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	b[6], b[8] = b[6]&0x0f|0x40, b[8]&0x3f|0x80
	key := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

	body := bytes.NewBufferString(`{"model": "Kickertisch-Beispiel", "firmware": "1.0"}`)
	request, _ := http.NewRequest("POST", "https://api.qm.packeroo.com/api/v1/device-pairings", body)
	request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
	request.Header.Set("Idempotency-Key", key)
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Accept-Language", "en")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	data, _ := io.ReadAll(response.Body)
	fmt.Println(response.Status, string(data))
}
```

Java:

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;

public class AskForCode {
    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/device-pairings"))
            .header("User-Agent", "Kickertisch-Beispiel/1.0")
            .header("Idempotency-Key", UUID.randomUUID().toString())
            .header("Content-Type", "application/json")
            .header("Accept-Language", "en")
            .POST(HttpRequest.BodyPublishers.ofString("{\"model\": \"Kickertisch-Beispiel\", \"firmware\": \"1.0\"}"))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

curl:

```bash
# uuidgen exists on macOS and many Linux systems; otherwise the kernel hands out a UUID.
KEY="$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)"
curl -sS -X POST https://api.qm.packeroo.com/api/v1/device-pairings \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Idempotency-Key: $KEY" \
  -H "Content-Type: application/json" \
  -H "Accept-Language: en" \
  -d '{"model": "Kickertisch-Beispiel", "firmware": "1.0"}'
```

ESP32:

```cpp
// In setup(), after Wi-Fi, configTime() and tls.setCACert() as in the full sketch of the guide.
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/device-pairings");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Idempotency-Key", newKey());  // newKey() from the full sketch
http.addHeader("Content-Type", "application/json");
http.addHeader("Accept-Language", "en");
int status = http.POST("{\"model\":\"Kickertisch-ESP32\",\"firmware\":\"1.0\"}");
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

The answer comes with `201 Created`:

```json
{
  "data": {
    "code": "K7F4QX",
    "expires_at": "2026-11-22T14:15:00Z",
    "token": "pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD"
  }
}
```

You see the token only this once. Put it into an environment variable in the same terminal; the examples of the next steps read it from there:

```bash
export PACKEROO_TOKEN='pkd_test_…'   # your token from the answer here
# PowerShell: $env:PACKEROO_TOKEN = 'pkd_test_…'
```

On the ESP32 the sketch keeps it in the variable `token`.

## 2. Ask with the token

Ask `GET /device` with the token. Until someone has entered the code, the API answers `401` with the code `unauthenticated`: the token counts only once the code belongs to a table. With a wrong token, or a `pkd_test_` token against the live API, the answer looks the same. Step 3 shows whether your token is right.

Python:

```python
import json, os, urllib.error, urllib.request

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/device",
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Authorization": "Bearer " + os.environ["PACKEROO_TOKEN"],
    },
)
try:
    with urllib.request.urlopen(request) as response:
        print(response.status, json.load(response)["data"])
except urllib.error.HTTPError as error:
    print(error.code, error.read().decode())
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/device', {
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    Authorization: `Bearer ${process.env.PACKEROO_TOKEN}`,
  },
})
console.log(response.status, await response.json())
```

C#:

```csharp
using System.Net.Http.Headers;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.qm.packeroo.com/api/v1/device");
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
var token = Environment.GetEnvironmentVariable("PACKEROO_TOKEN");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$curl = curl_init('https://api.qm.packeroo.com/api/v1/device');
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('PACKEROO_TOKEN')],
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
request, _ := http.NewRequest("GET", "https://api.qm.packeroo.com/api/v1/device", nil)
request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
request.Header.Set("Authorization", "Bearer "+os.Getenv("PACKEROO_TOKEN"))
response, err := http.DefaultClient.Do(request)
if err != nil {
	panic(err)
}
defer response.Body.Close()
data, _ := io.ReadAll(response.Body)
fmt.Println(response.Status, string(data))
```

Java:

```java
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/device"))
    .header("User-Agent", "Kickertisch-Beispiel/1.0")
    .header("Authorization", "Bearer " + System.getenv("PACKEROO_TOKEN"))
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
```

curl:

```bash
curl -sS https://api.qm.packeroo.com/api/v1/device \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Authorization: Bearer $PACKEROO_TOKEN"
```

ESP32:

```cpp
// token: from the answer to step 1, as in the complete sketch.
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/device");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Authorization", "Bearer " + token);
int status = http.GET();
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

## 3. Have the code entered

Live, someone enters the code in the app, under Profile › Organization › Tables, then "Pair a device" at the table. In the sandbox no person is needed: your device confirms its code itself with `POST /sandbox/device-pairings/confirm` and the same token. It gets a test table of its own. If this answers `401`, no code waits for the token: it is wrong, or the code ran out after 10 minutes. Then start again at step 1.

Python:

```python
import json, os, urllib.error, urllib.request, uuid

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm",
    method="POST",
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Idempotency-Key": str(uuid.uuid4()),
        "Authorization": "Bearer " + os.environ["PACKEROO_TOKEN"],
    },
)
try:
    with urllib.request.urlopen(request) as response:
        print(response.status, json.load(response)["data"])
except urllib.error.HTTPError as error:
    print(error.code, error.read().decode())
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm', {
  method: 'POST',
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    'Idempotency-Key': crypto.randomUUID(),
    Authorization: `Bearer ${process.env.PACKEROO_TOKEN}`,
  },
})
console.log(response.status, await response.json())
```

C#:

```csharp
using System.Net.Http.Headers;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm");
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
var token = Environment.GetEnvironmentVariable("PACKEROO_TOKEN");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$curl = curl_init('https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm');
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => [
        'Idempotency-Key: ' . bin2hex(random_bytes(16)),
        'Authorization: Bearer ' . getenv('PACKEROO_TOKEN'),
    ],
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
request, _ := http.NewRequest("POST", "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm", nil)
request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
request.Header.Set("Idempotency-Key", key) // key: a new UUID, made as in step 1
request.Header.Set("Authorization", "Bearer "+os.Getenv("PACKEROO_TOKEN"))
response, err := http.DefaultClient.Do(request)
if err != nil {
	panic(err)
}
defer response.Body.Close()
data, _ := io.ReadAll(response.Body)
fmt.Println(response.Status, string(data))
```

Java:

```java
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm"))
    .header("User-Agent", "Kickertisch-Beispiel/1.0")
    .header("Idempotency-Key", UUID.randomUUID().toString())
    .header("Authorization", "Bearer " + System.getenv("PACKEROO_TOKEN"))
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
```

curl:

```bash
curl -sS -X POST https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
  -H "Authorization: Bearer $PACKEROO_TOKEN"
```

ESP32:

```cpp
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Idempotency-Key", newKey());
http.addHeader("Authorization", "Bearer " + token);
int status = http.POST("");
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

The answer is the device already, as `GET /device` shows it. This operation exists in the sandbox only; live it answers `404`, once `User-Agent` and `Idempotency-Key` are checked. The sandbox keeps the latest 100 test tables; the oldest is unpaired with its device when a new one comes.

Your device is paired now. From here on `GET /device` from step 2 answers `200`:

```json
{
  "data": {
    "id": "01JD7Q3V9TQ6Z8K2M4N5P6R7S8",
    "name": "Kickertisch Halle",
    "table": { "id": "01JD7Q2B1C3D4E5F6G7H8J9K0M", "name": "Tisch 2" },
    "location": { "id": "01JD7Q1A2B3C4D5E6F7G8H9J0K", "name": "Büro Freiburg", "time_zone": "Europe/Berlin" },
    "organization": { "id": "01JD7Q0Z9Y8X7W6V5T4S3R2Q1P", "name": "Beispiel AG" },
    "scopes": ["leagues:read", "standings:read", "matches:read", "matches:write", "matches:live"]
  }
}
```

The values above are an example. `scopes` names what the token may do later; the operations for it are [planned](https://developers.packeroo.com/en/concepts/#scopes).

## Next

- The [guide](https://developers.packeroo.com/en/guides/pair-a-table-device/) has the complete program, with waiting, an expired code and every error case.
- [Postman](https://developers.packeroo.com/en/downloads/#postman): import the collection, choose the environment "packeroo Sandbox", paste the token.
- The [reference](https://developers.packeroo.com/en/reference/) has every operation with code samples in many more languages.

---

# Pair a table device

> Ask for a code, show it with a QR code, keep the token safe and wait for the pairing. With a complete program in Python, JavaScript, C#, PHP, Go, Java, curl and for the ESP32.

A table device is anything at a table that talks to packeroo: a foosball table with goal detection, a display, a Raspberry Pi under the playing field. Before it may report anything, it pairs once with exactly one table of a location. This guide takes you through the pairing, from the first call to the answer `200`.

## The flow

1. The device asks for a code with `POST /device-pairings` and gets its token with it.
2. It keeps the token in a file that only its own user can read.
3. It shows the code as two groups of three and as a QR code.
4. Whoever manages the location enters the code in the packeroo app, under Profile › Organization › Tables, then "Pair a device" at the table or at `app.packeroo.com/verbinden`, or scans the QR code with their phone, which opens the same link with the code filled in.
5. The device asks `GET /device` every five seconds. Until the code is entered the answer is `401`, then `200` with the table, location and organization.

If the code runs out after ten minutes, the device asks for a new one and sends the token it has.

## The complete program

The program does everything in this guide: it reads a stored token, otherwise asks for a code, shows it, keeps the token, waits for the pairing and handles the errors. The base address comes from the environment variable `PACKEROO_BASE_URL`; without it the program uses the sandbox. `PACKEROO_TOKEN_FILE` sets where the token is kept, by default `~/.config/packeroo/device-token`.

#### Python (python/pair_device.py)

```python
"""Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
someone enters the code in the app. Python 3.9 or newer, standard library only; with the
package qrcode installed (pip install qrcode) it also prints the QR code in the terminal.

    python3 pair_device.py

PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
"""

import email.utils
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from datetime import datetime, timezone
from pathlib import Path

# What the device shows, in the language of the location.
TEXT = {
    "code": "Code am Tisch: {code}  (gilt bis {until} Uhr)",
    "link": "QR-Code mit diesem Link: {link}",
    "enter": "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.",
    "qr_hint": "Für einen QR-Code im Terminal: pip install qrcode",
    "expired": "Der Code ist abgelaufen. Ich hole einen neuen.",
    "unpaired": "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.",
    "off": "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.",
    "offline": "Keine Verbindung ({error}), neuer Versuch in {seconds:g} s",
    "paired": "Verbunden mit {table} ({location})",
    "no_location": "ohne Standort",
    "error": "Fehler {status} {code}: {detail}",
    "unexpected": "unerwartete Antwort",
}

BASE_URL = os.environ.get("PACKEROO_BASE_URL", "https://api.qm.packeroo.com/api/v1").rstrip("/")
TOKEN_FILE = Path(os.environ.get("PACKEROO_TOKEN_FILE", Path.home() / ".config" / "packeroo" / "device-token"))
POLL_SECONDS = float(os.environ.get("PACKEROO_POLL_SECONDS", "5"))
# After errors in a row the pause doubles, up to this many seconds.
MAX_PAUSE_SECONDS = 60
# Every request names the device: product and firmware.
USER_AGENT = "Kickertisch-Beispiel/1.0"

def call(method, path, token=None, body=None, idempotency_key=None):
    """One request to the API. Returns (status, json, headers); network errors are retried."""
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json", "Accept-Language": "de"}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode()
    # A write carries an Idempotency-Key; a retry of the same request sends the same key.
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key

    failures = 0
    while True:
        request = urllib.request.Request(BASE_URL + path, data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return response.status, read_json(response), response.headers
        except urllib.error.HTTPError as error:
            return error.code, read_json(error), error.headers
        except (urllib.error.URLError, TimeoutError, ConnectionError) as error:
            failures += 1
            pause_after_error(failures, error)

def read_json(response):
    """The body as JSON; {} when there is none or it is no JSON, such as the error page of a proxy."""
    try:
        return json.loads(response.read().decode() or "{}")
    except ValueError:
        return {}

def pause_after_error(failures, reason):
    """Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
    error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause."""
    seconds = min(POLL_SECONDS * 2 ** (failures - 1), MAX_PAUSE_SECONDS)
    print(TEXT["offline"].format(error=reason, seconds=seconds), file=sys.stderr)
    time.sleep(seconds)

def retry_after(headers):
    """Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date."""
    value = headers.get("Retry-After", "60")
    if value.isdigit():
        return max(1, int(value))
    try:
        return max(1, (email.utils.parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds())
    except (TypeError, ValueError):
        return 60

def read_token():
    try:
        return TOKEN_FILE.read_text().strip() or None
    except FileNotFoundError:
        return None

def save_token(token):
    """Keeps the token in a file only this user can read, written in one step."""
    TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    temporary = TOKEN_FILE.with_name(TOKEN_FILE.name + ".tmp")
    # A leftover from a crash may have other rights: remove it, then create the file anew.
    temporary.unlink(missing_ok=True)
    descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(descriptor, "w") as file:
        file.write(token + "\n")
    os.chmod(temporary, 0o600)
    os.replace(temporary, TOKEN_FILE)

def pair_link(code):
    """The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com."""
    host = urllib.parse.urlsplit(BASE_URL).netloc
    if host.startswith("api."):
        host = "app." + host[4:]
    return f"https://{host}/verbinden?code={code}"

def show_code(code, expires_at):
    until = datetime.fromisoformat(expires_at.replace("Z", "+00:00")).astimezone().strftime("%H:%M")
    link = pair_link(code)
    print("\n" + TEXT["code"].format(code=f"{code[:3]} {code[3:]}", until=until))
    try:
        import qrcode

        qr = qrcode.QRCode(border=2)
        qr.add_data(link)
        qr.print_ascii(invert=True)
    except ImportError:
        print(TEXT["qr_hint"])
    print(TEXT["link"].format(link=link))
    print(TEXT["enter"] + "\n", flush=True)

def fail(status, problem):
    print(TEXT["error"].format(status=status, code=problem.get("code", ""), detail=problem.get("detail", TEXT["unexpected"])), file=sys.stderr)
    sys.exit(1)

def request_code(token):
    """Asks for a code. Returns (token, expires_at), with expires_at None when the token is paired already."""
    idempotency_key = str(uuid.uuid4())
    failures = 0
    while True:
        status, answer, headers = call(
            "POST", "/device-pairings", token=token, idempotency_key=idempotency_key,
            body={"model": "Kickertisch-Beispiel", "firmware": "1.0"},
        )
        if status == 201:
            data = answer["data"]
            # Shown only this once: keep it before anything else.
            save_token(data["token"])
            show_code(data["code"], data["expires_at"])
            expires = datetime.fromisoformat(data["expires_at"].replace("Z", "+00:00")).timestamp()
            return data["token"], expires
        code = answer.get("code")
        if status == 409 and code == "device_already_paired":
            return token, None
        if status == 409 and code == "table_devices_off":
            print(TEXT["off"], flush=True)
            time.sleep(60)
        elif status == 429:
            time.sleep(retry_after(headers))
        elif status >= 500:
            # The API is busy or being deployed: the same request with the same key, after a pause.
            failures += 1
            pause_after_error(failures, f"HTTP {status}")
        else:
            fail(status, answer)

def wait_for_pairing(token, expires_at):
    """GET /device until it answers 200. None once the code has run out, or at once when no code
    is waiting (expires_at None) and the token does not sign in: the device was unpaired.
    Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error."""
    failures = 0
    while True:
        status, answer, headers = call("GET", "/device", token=token)
        if status == 200:
            return answer["data"]
        if status == 429:
            time.sleep(retry_after(headers))
            continue
        if 400 <= status < 500 and status != 401:
            # A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
            fail(status, answer)
        if status != 401:
            # Someone may be typing the code right now: keep it, ask again after a pause.
            failures += 1
            pause_after_error(failures, f"HTTP {status}")
            continue
        failures = 0
        if expires_at is None or time.time() >= expires_at:
            return None
        time.sleep(POLL_SECONDS)

def main():
    token = read_token()
    # With a stored token, ask first whether it still signs in; None after a 401.
    device = wait_for_pairing(token, None) if token else None

    while device is None:
        token, expires_at = request_code(token)
        device = wait_for_pairing(token, expires_at)
        if device is None and expires_at is None:
            # Paired a moment ago, unpaired now: this token is of no use any more.
            print(TEXT["unpaired"], flush=True)
            token = None
        elif device is None:
            print(TEXT["expired"], flush=True)

    location = device["location"]["name"] or TEXT["no_location"]
    print(TEXT["paired"].format(table=device["table"]["name"], location=location))

if __name__ == "__main__":
    main()
```

#### JavaScript (javascript/pair-device.mjs)

```js
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. Node.js 20 or newer, no packages. Runs in Node.js, not in a
// browser: a browser does not let a page set the User-Agent.
//
//   node pair-device.mjs
//
// PACKEROO_BASE_URL    API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE  where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5

import { randomUUID } from 'node:crypto'
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'

// What the device shows, in the language of the location.
const TEXT = {
  code: (code, until) => `Code am Tisch: ${code}  (gilt bis ${until} Uhr)`,
  link: (link) => `QR-Code mit diesem Link: ${link}`,
  enter: 'Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.',
  expired: 'Der Code ist abgelaufen. Ich hole einen neuen.',
  unpaired: 'Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.',
  off: 'Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.',
  offline: (error, seconds) => `Keine Verbindung (${error}), neuer Versuch in ${seconds} s`,
  paired: (table, location) => `Verbunden mit ${table} (${location ?? 'ohne Standort'})`,
  error: (status, code, detail) => `Fehler ${status} ${code ?? ''}: ${detail ?? 'unerwartete Antwort'}`,
}

const BASE_URL = (process.env.PACKEROO_BASE_URL ?? 'https://api.qm.packeroo.com/api/v1').replace(/\/+$/, '')
const TOKEN_FILE = process.env.PACKEROO_TOKEN_FILE ?? join(homedir(), '.config', 'packeroo', 'device-token')
const POLL_SECONDS = Number(process.env.PACKEROO_POLL_SECONDS ?? 5)
// After errors in a row the pause doubles, up to this many seconds.
const MAX_PAUSE_SECONDS = 60
// Every request names the device: product and firmware.
const USER_AGENT = 'Kickertisch-Beispiel/1.0'

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000))

/** One request to the API. Returns status, the JSON body and the headers; network errors are retried. */
async function call(method, path, { token, body, idempotencyKey } = {}) {
  const headers = { 'User-Agent': USER_AGENT, Accept: 'application/json', 'Accept-Language': 'de' }
  if (token) headers.Authorization = `Bearer ${token}`
  if (body !== undefined) headers['Content-Type'] = 'application/json'
  // A write carries an Idempotency-Key; a retry of the same request sends the same key.
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey

  for (let failures = 1; ; failures++) {
    try {
      // A connection that stalls ends after 30 s, as in the other examples, and is retried.
      const response = await fetch(BASE_URL + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30_000) })
      return { status: response.status, json: parseJson(await response.text()), headers: response.headers }
    } catch (error) {
      await pauseAfterError(failures, error.cause?.code ?? error.message)
    }
  }
}

/** The body as JSON; null when there is none or it is no JSON, such as the error page of a proxy. */
function parseJson(text) {
  try {
    return text ? JSON.parse(text) : null
  } catch {
    return null
  }
}

/**
 * Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
 * error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
 */
async function pauseAfterError(failures, reason) {
  const seconds = Math.min(POLL_SECONDS * 2 ** (failures - 1), MAX_PAUSE_SECONDS)
  console.error(TEXT.offline(reason, seconds))
  await sleep(seconds)
}

/** Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date. */
function retryAfter(headers) {
  const value = headers.get('retry-after') ?? ''
  if (/^\d+$/.test(value)) return Math.max(1, Number(value))
  const date = Date.parse(value)
  return Number.isNaN(date) ? 60 : Math.max(1, (date - Date.now()) / 1000)
}

async function readToken() {
  try {
    return (await readFile(TOKEN_FILE, 'utf8')).trim() || undefined
  } catch {
    return undefined
  }
}

/** Keeps the token in a file only this user can read, written in one step. */
async function saveToken(token) {
  await mkdir(dirname(TOKEN_FILE), { recursive: true, mode: 0o700 })
  const temporary = `${TOKEN_FILE}.tmp`
  // A leftover from a crash may have other rights: remove it, then create the file anew.
  await rm(temporary, { force: true })
  await writeFile(temporary, `${token}\n`, { mode: 0o600, flag: 'wx' })
  await rename(temporary, TOKEN_FILE)
}

/** The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com. */
function pairLink(code) {
  const url = new URL(BASE_URL)
  const host = url.hostname.startsWith('api.') ? `app.${url.hostname.slice(4)}` : url.host
  return `https://${host}/verbinden?code=${code}`
}

function showCode(code, expiresAt) {
  const until = new Date(expiresAt).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })
  console.log(`\n${TEXT.code(`${code.slice(0, 3)} ${code.slice(3)}`, until)}`)
  // For a QR code on a display, a package such as qrcode (npm) draws pairLink(code).
  console.log(TEXT.link(pairLink(code)))
  console.log(`${TEXT.enter}\n`)
}

function fail(result) {
  const problem = result.json ?? {}
  console.error(TEXT.error(result.status, problem.code, problem.detail))
  process.exit(1)
}

/** Asks for a code. Returns { token, expiresAt }; expiresAt is undefined when the token is paired already. */
async function requestCode(token) {
  const idempotencyKey = randomUUID()
  let failures = 0
  for (;;) {
    const result = await call('POST', '/device-pairings', { token, idempotencyKey, body: { model: 'Kickertisch-Beispiel', firmware: '1.0' } })
    if (result.status === 201) {
      const { code, expires_at: expiresAt, token: newToken } = result.json.data
      // Shown only this once: keep it before anything else.
      await saveToken(newToken)
      showCode(code, expiresAt)
      return { token: newToken, expiresAt: Date.parse(expiresAt) }
    }
    const code = result.json?.code
    if (result.status === 409 && code === 'device_already_paired') return { token, expiresAt: undefined }
    if (result.status === 409 && code === 'table_devices_off') {
      console.log(TEXT.off)
      await sleep(60)
    } else if (result.status === 429) {
      await sleep(retryAfter(result.headers))
    } else if (result.status >= 500) {
      // The API is busy or being deployed: the same request with the same key, after a pause.
      await pauseAfterError(++failures, `HTTP ${result.status}`)
    } else {
      fail(result)
    }
  }
}

/**
 * GET /device until it answers 200. Undefined once the code has run out, or at once when no code
 * is waiting (expiresAt undefined) and the token does not sign in: the device was unpaired.
 * Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
 */
async function waitForPairing(token, expiresAt) {
  let failures = 0
  for (;;) {
    const result = await call('GET', '/device', { token })
    if (result.status === 200) return result.json.data
    if (result.status === 429) {
      await sleep(retryAfter(result.headers))
      continue
    }
    // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
    if (result.status >= 400 && result.status < 500 && result.status !== 401) fail(result)
    if (result.status !== 401) {
      // Someone may be typing the code right now: keep it, ask again after a pause.
      await pauseAfterError(++failures, `HTTP ${result.status}`)
      continue
    }
    failures = 0
    if (expiresAt === undefined || Date.now() >= expiresAt) return undefined
    await sleep(POLL_SECONDS)
  }
}

let token = await readToken()
// With a stored token, ask first whether it still signs in; undefined after a 401.
let device = token ? await waitForPairing(token, undefined) : undefined

while (!device) {
  const pairing = await requestCode(token)
  token = pairing.token
  device = await waitForPairing(token, pairing.expiresAt)
  if (!device && pairing.expiresAt === undefined) {
    // Paired a moment ago, unpaired now: this token is of no use any more.
    console.log(TEXT.unpaired)
    token = undefined
  } else if (!device) {
    console.log(TEXT.expired)
  }
}

console.log(TEXT.paired(device.table.name, device.location.name))
```

#### C# (csharp/Program.cs)

```csharp
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. .NET 8 or newer, no packages.
//
//   dotnet run
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5

using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

// What the device shows, in the language of the location.
var TEXT = new
{
    Code = "Code am Tisch: {0}  (gilt bis {1:HH:mm} Uhr)",
    Link = "QR-Code mit diesem Link: {0}",
    Enter = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.",
    Expired = "Der Code ist abgelaufen. Ich hole einen neuen.",
    Unpaired = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.",
    Off = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.",
    Offline = "Keine Verbindung ({0}), neuer Versuch in {1} s",
    Paired = "Verbunden mit {0} ({1})",
    NoLocation = "ohne Standort",
    Error = "Fehler {0} {1}: {2}",
    Unexpected = "unerwartete Antwort",
};

var baseUrl = (Environment.GetEnvironmentVariable("PACKEROO_BASE_URL") ?? "https://api.qm.packeroo.com/api/v1").TrimEnd('/');
var tokenFile = Environment.GetEnvironmentVariable("PACKEROO_TOKEN_FILE")
    ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "packeroo", "device-token");
var pollSeconds = double.Parse(Environment.GetEnvironmentVariable("PACKEROO_POLL_SECONDS") ?? "5", CultureInfo.InvariantCulture);
// After errors in a row the pause doubles, up to this many seconds.
const double MaxPauseSeconds = 60;

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
// Every request names the device: product and firmware.
http.DefaultRequestHeaders.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
http.DefaultRequestHeaders.AcceptLanguage.ParseAdd("de");

var token = File.Exists(tokenFile) ? File.ReadAllText(tokenFile).Trim() : null;
if (string.IsNullOrEmpty(token)) token = null;
// With a stored token, ask first whether it still signs in; null after a 401.
var device = token is null ? null : await WaitForPairing(token, null);

while (device is null)
{
    var (newToken, expiresAt) = await RequestCode(token);
    token = newToken;
    device = await WaitForPairing(token, expiresAt);
    if (device is null && expiresAt is null)
    {
        // Paired a moment ago, unpaired now: this token is of no use any more.
        Console.WriteLine(TEXT.Unpaired);
        token = null;
    }
    else if (device is null) Console.WriteLine(TEXT.Expired);
}

var d = device.Value;
Console.WriteLine(TEXT.Paired, d.GetProperty("table").GetProperty("name").GetString(), d.GetProperty("location").GetProperty("name").GetString() ?? TEXT.NoLocation);

// One request to the API. Network errors are retried.
async Task<(HttpStatusCode Status, JsonElement Json, HttpResponseHeaders Headers)> Call(HttpMethod method, string path, string? bearer, object? body = null, string? idempotencyKey = null)
{
    for (var failures = 1; ; failures++)
    {
        using var request = new HttpRequestMessage(method, baseUrl + path);
        if (bearer is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
        // A write carries an Idempotency-Key; a retry of the same request sends the same key.
        if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey);
        if (body is not null) request.Content = JsonContent.Create(body);
        try
        {
            using var response = await http.SendAsync(request);
            return (response.StatusCode, ParseJson(await response.Content.ReadAsStringAsync()), response.Headers);
        }
        catch (Exception error) when (error is HttpRequestException or TaskCanceledException)
        {
            await PauseAfterError(failures, error.Message);
        }
    }
}

// The body as JSON; empty when there is none or it is no JSON, such as the error page of a proxy.
static JsonElement ParseJson(string text)
{
    try
    {
        return text.Length > 0 ? JsonDocument.Parse(text).RootElement.Clone() : default;
    }
    catch (JsonException)
    {
        return default;
    }
}

// Waits after a network error, a 5xx or an unexpected answer: pollSeconds, doubled with every error
// in a row, at most MaxPauseSeconds. A device never asks again without a pause.
async Task PauseAfterError(int failures, string reason)
{
    var seconds = Math.Min(pollSeconds * Math.Pow(2, failures - 1), MaxPauseSeconds);
    Console.Error.WriteLine(TEXT.Offline, reason, seconds);
    await Task.Delay(TimeSpan.FromSeconds(seconds));
}

// Asks for a code. Returns the token and when the code runs out; null when the token is paired already.
async Task<(string? Token, DateTimeOffset? ExpiresAt)> RequestCode(string? bearer)
{
    var key = Guid.NewGuid().ToString();
    var failures = 0;
    while (true)
    {
        var (status, json, headers) = await Call(HttpMethod.Post, "/device-pairings", bearer, new { model = "Kickertisch-Beispiel", firmware = "1.0" }, key);
        if (status == HttpStatusCode.Created)
        {
            var data = json.GetProperty("data");
            var newToken = data.GetProperty("token").GetString()!;
            // Shown only this once: keep it before anything else.
            SaveToken(newToken);
            var code = data.GetProperty("code").GetString()!;
            var expiresAt = DateTimeOffset.Parse(data.GetProperty("expires_at").GetString()!, CultureInfo.InvariantCulture);
            ShowCode(code, expiresAt);
            return (newToken, expiresAt);
        }
        var problem = ProblemCode(json);
        if (status == HttpStatusCode.Conflict && problem == "device_already_paired") return (bearer, null);
        if (status == HttpStatusCode.Conflict && problem == "table_devices_off")
        {
            Console.WriteLine(TEXT.Off);
            await Task.Delay(TimeSpan.FromSeconds(60));
        }
        else if (status == HttpStatusCode.TooManyRequests) await Task.Delay(RetryAfter(headers));
        // The API is busy or being deployed: the same request with the same key, after a pause.
        else if ((int)status >= 500) await PauseAfterError(++failures, $"HTTP {(int)status}");
        else Fail(status, json);
    }
}

// GET /device until it answers 200. Null once the code has run out, or at once when no code is
// waiting (expiresAt null) and the token does not sign in: the device was unpaired.
// Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
async Task<JsonElement?> WaitForPairing(string? bearer, DateTimeOffset? expiresAt)
{
    var failures = 0;
    while (true)
    {
        var (status, json, headers) = await Call(HttpMethod.Get, "/device", bearer);
        if (status == HttpStatusCode.OK) return json.GetProperty("data");
        if (status == HttpStatusCode.TooManyRequests) { await Task.Delay(RetryAfter(headers)); continue; }
        // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
        if ((int)status is >= 400 and < 500 && status != HttpStatusCode.Unauthorized) Fail(status, json);
        if (status != HttpStatusCode.Unauthorized)
        {
            // Someone may be typing the code right now: keep it, ask again after a pause.
            await PauseAfterError(++failures, $"HTTP {(int)status}");
            continue;
        }
        failures = 0;
        if (expiresAt is null || DateTimeOffset.UtcNow >= expiresAt) return null;
        await Task.Delay(TimeSpan.FromSeconds(pollSeconds));
    }
}

// Keeps the token in a file only this user can read, written in one step.
void SaveToken(string value)
{
    Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(tokenFile))!);
    var temporary = tokenFile + ".tmp";
    // A leftover from a crash may have other rights: remove it, then create the file anew.
    File.Delete(temporary);
    var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };
    if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
    using (var stream = new FileStream(temporary, options))
    using (var writer = new StreamWriter(stream)) writer.WriteLine(value);
    File.Move(temporary, tokenFile, overwrite: true);
}

void ShowCode(string code, DateTimeOffset expiresAt)
{
    // The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
    // For a QR code on a display, a package such as QRCoder draws this link.
    var host = new Uri(baseUrl).Authority;
    if (host.StartsWith("api.")) host = "app." + host[4..];
    Console.WriteLine();
    Console.WriteLine(TEXT.Code, $"{code[..3]} {code[3..]}", expiresAt.ToLocalTime());
    Console.WriteLine(TEXT.Link, $"https://{host}/verbinden?code={code}");
    Console.WriteLine(TEXT.Enter);
    Console.WriteLine();
}

// Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date.
static TimeSpan RetryAfter(HttpResponseHeaders headers)
{
    var wait = headers.RetryAfter?.Delta ?? (headers.RetryAfter?.Date - DateTimeOffset.UtcNow) ?? TimeSpan.FromSeconds(60);
    return wait < TimeSpan.FromSeconds(1) ? TimeSpan.FromSeconds(1) : wait;
}

static string? ProblemCode(JsonElement json) =>
    json.ValueKind == JsonValueKind.Object && json.TryGetProperty("code", out var code) ? code.GetString() : null;

void Fail(HttpStatusCode status, JsonElement json)
{
    var detail = json.ValueKind == JsonValueKind.Object && json.TryGetProperty("detail", out var text) ? text.GetString() : TEXT.Unexpected;
    Console.Error.WriteLine(TEXT.Error, (int)status, ProblemCode(json), detail);
    Environment.Exit(1);
}
```

#### PHP (php/pair-device.php)

```php
<?php

// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. PHP 8.1 or newer with the curl extension, no framework.
//
//   php pair-device.php
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5

declare(strict_types=1);

// What the device shows, in the language of the location.
const TEXT = [
    'code' => 'Code am Tisch: %s  (gilt bis %s Uhr)',
    'link' => 'QR-Code mit diesem Link: %s',
    'enter' => 'Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.',
    'expired' => 'Der Code ist abgelaufen. Ich hole einen neuen.',
    'unpaired' => 'Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.',
    'off' => 'Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.',
    'offline' => 'Keine Verbindung (%s), neuer Versuch in %s s',
    'paired' => 'Verbunden mit %s (%s)',
    'no_location' => 'ohne Standort',
    'error' => 'Fehler %d %s: %s',
    'unexpected' => 'unerwartete Antwort',
];

const USER_AGENT = 'Kickertisch-Beispiel/1.0'; // Every request names the device: product and firmware.
const MAX_PAUSE_SECONDS = 60; // After errors in a row the pause doubles, up to this many seconds.

$baseUrl = rtrim(getenv('PACKEROO_BASE_URL') ?: 'https://api.qm.packeroo.com/api/v1', '/');
$tokenFile = getenv('PACKEROO_TOKEN_FILE') ?: (getenv('HOME') ?: getenv('USERPROFILE')).'/.config/packeroo/device-token';
$pollSeconds = (float) (getenv('PACKEROO_POLL_SECONDS') ?: 5);

/** One request to the API: [status, json, retryAfter]. Network errors are retried. */
function call(string $method, string $path, ?string $token = null, ?array $body = null, ?string $idempotencyKey = null): array
{
    global $baseUrl, $pollSeconds;
    $headers = ['Accept: application/json', 'Accept-Language: de'];
    if ($token !== null) {
        $headers[] = 'Authorization: Bearer '.$token;
    }
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
    }
    // A write carries an Idempotency-Key; a retry of the same request sends the same key.
    if ($idempotencyKey !== null) {
        $headers[] = 'Idempotency-Key: '.$idempotencyKey;
    }

    for ($failures = 1; ; $failures++) {
        $retryAfter = 60;
        $curl = curl_init($baseUrl.$path);
        curl_setopt_array($curl, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_USERAGENT => USER_AGENT,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$retryAfter): int {
                // Retry-After is a number of seconds or an HTTP date.
                if (preg_match('/^Retry-After:\s*(.+?)\s*$/i', $line, $match)) {
                    $seconds = ctype_digit($match[1]) ? (int) $match[1] : (strtotime($match[1]) ?: time() + 60) - time();
                    $retryAfter = max(1, $seconds);
                }

                return strlen($line);
            },
        ]);
        if ($body !== null) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
        }
        $text = curl_exec($curl);
        if ($text === false) {
            pauseAfterError($failures, curl_error($curl));

            continue;
        }
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        // An empty body or one that is no JSON, such as the error page of a proxy, gives [].
        $json = json_decode($text, true);

        return [$status, is_array($json) ? $json : [], $retryAfter];
    }
}

/**
 * Waits after a network error, a 5xx or an unexpected answer: the poll interval, doubled with every
 * error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
 */
function pauseAfterError(int $failures, string $reason): void
{
    global $pollSeconds;
    $seconds = min($pollSeconds * 2 ** ($failures - 1), MAX_PAUSE_SECONDS);
    fwrite(STDERR, sprintf(TEXT['offline'], $reason, $seconds)."\n");
    usleep((int) ($seconds * 1_000_000));
}

/** Keeps the token in a file only this user can read, written in one step. */
function saveToken(string $token): void
{
    global $tokenFile;
    if (! is_dir(dirname($tokenFile))) {
        mkdir(dirname($tokenFile), 0700, true);
    }
    $temporary = $tokenFile.'.tmp';
    // A leftover from a crash may have other rights: remove it, then create the file anew ('x').
    if (file_exists($temporary)) {
        unlink($temporary);
    }
    $old = umask(0077);
    $file = fopen($temporary, 'x');
    umask($old);
    if ($file === false) {
        throw new RuntimeException("Cannot create {$temporary}");
    }
    fwrite($file, $token."\n");
    fclose($file);
    chmod($temporary, 0600);
    rename($temporary, $tokenFile);
}

function showCode(string $code, string $expiresAt): void
{
    global $baseUrl;
    // The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
    // For a QR code on a display, a library such as chillerlan/php-qrcode draws this link.
    $host = parse_url($baseUrl, PHP_URL_HOST).(parse_url($baseUrl, PHP_URL_PORT) ? ':'.parse_url($baseUrl, PHP_URL_PORT) : '');
    if (str_starts_with($host, 'api.')) {
        $host = 'app.'.substr($host, 4);
    }
    $until = (new DateTimeImmutable($expiresAt))->setTimezone(new DateTimeZone(date_default_timezone_get()))->format('H:i');
    echo "\n".sprintf(TEXT['code'], substr($code, 0, 3).' '.substr($code, 3), $until)."\n";
    echo sprintf(TEXT['link'], "https://{$host}/verbinden?code={$code}")."\n";
    echo TEXT['enter']."\n\n";
}

function fail(int $status, array $problem): never
{
    fwrite(STDERR, sprintf(TEXT['error'], $status, $problem['code'] ?? '', $problem['detail'] ?? TEXT['unexpected'])."\n");
    exit(1);
}

/** Asks for a code: [token, expiresAt], with expiresAt null when the token is paired already. */
function requestCode(?string $token): array
{
    $key = sprintf('%04x%04x-%04x-4%03x-%04x-%04x%04x%04x', ...[
        random_int(0, 0xFFFF), random_int(0, 0xFFFF), random_int(0, 0xFFFF), random_int(0, 0xFFF),
        random_int(0, 0x3FFF) | 0x8000, random_int(0, 0xFFFF), random_int(0, 0xFFFF), random_int(0, 0xFFFF),
    ]);
    $failures = 0;
    while (true) {
        [$status, $answer, $retryAfter] = call('POST', '/device-pairings', $token, ['model' => 'Kickertisch-Beispiel', 'firmware' => '1.0'], $key);
        if ($status === 201) {
            $data = $answer['data'];
            // Shown only this once: keep it before anything else.
            saveToken($data['token']);
            showCode($data['code'], $data['expires_at']);

            return [$data['token'], strtotime($data['expires_at'])];
        }
        $code = $answer['code'] ?? null;
        if ($status === 409 && $code === 'device_already_paired') {
            return [$token, null];
        }
        if ($status === 409 && $code === 'table_devices_off') {
            echo TEXT['off']."\n";
            sleep(60);
        } elseif ($status === 429) {
            sleep($retryAfter);
        } elseif ($status >= 500) {
            // The API is busy or being deployed: the same request with the same key, after a pause.
            pauseAfterError(++$failures, "HTTP {$status}");
        } else {
            fail($status, $answer);
        }
    }
}

/**
 * GET /device until it answers 200. Null once the code has run out, or at once when no code is
 * waiting ($expiresAt null) and the token does not sign in: the device was unpaired.
 * Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
 */
function waitForPairing(?string $token, ?int $expiresAt): ?array
{
    global $pollSeconds;
    $failures = 0;
    while (true) {
        [$status, $answer, $retryAfter] = call('GET', '/device', $token);
        if ($status === 200) {
            return $answer['data'];
        }
        if ($status === 429) {
            sleep($retryAfter);

            continue;
        }
        // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
        if ($status >= 400 && $status < 500 && $status !== 401) {
            fail($status, $answer);
        }
        if ($status !== 401) {
            // Someone may be typing the code right now: keep it, ask again after a pause.
            pauseAfterError(++$failures, "HTTP {$status}");

            continue;
        }
        $failures = 0;
        if ($expiresAt === null || time() >= $expiresAt) {
            return null;
        }
        usleep((int) ($pollSeconds * 1_000_000));
    }
}

$token = is_file($tokenFile) ? (trim((string) file_get_contents($tokenFile)) ?: null) : null;
// With a stored token, ask first whether it still signs in; null after a 401.
$device = $token === null ? null : waitForPairing($token, null);

while ($device === null) {
    [$token, $expiresAt] = requestCode($token);
    $device = waitForPairing($token, $expiresAt);
    if ($device === null && $expiresAt === null) {
        // Paired a moment ago, unpaired now: this token is of no use any more.
        echo TEXT['unpaired']."\n";
        $token = null;
    } elseif ($device === null) {
        echo TEXT['expired']."\n";
    }
}

echo sprintf(TEXT['paired'], $device['table']['name'], $device['location']['name'] ?? TEXT['no_location'])."\n";
```

#### Go (go/main.go)

```go
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. Go 1.21 or newer, standard library only.
//
//	go run .
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
package main

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io"
	"math"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// What the device shows, in the language of the location.
var text = struct{ code, link, enter, expired, unpaired, off, offline, paired, noLocation, error, unexpected string }{
	code:       "Code am Tisch: %s %s  (gilt bis %s Uhr)\n",
	link:       "QR-Code mit diesem Link: %s\n",
	enter:      "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.",
	expired:    "Der Code ist abgelaufen. Ich hole einen neuen.",
	unpaired:   "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.",
	off:        "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.",
	offline:    "Keine Verbindung (%v), neuer Versuch in %g s\n",
	paired:     "Verbunden mit %s (%s)\n",
	noLocation: "ohne Standort",
	error:      "Fehler %d %s: %s\n",
	unexpected: "unerwartete Antwort",
}

// Every request names the device: product and firmware.
const userAgent = "Kickertisch-Beispiel/1.0"

// After errors in a row the pause doubles, up to this many seconds.
const maxPauseSeconds = 60

var (
	baseURL     = strings.TrimRight(env("PACKEROO_BASE_URL", "https://api.qm.packeroo.com/api/v1"), "/")
	tokenFile   = env("PACKEROO_TOKEN_FILE", filepath.Join(home(), ".config", "packeroo", "device-token"))
	pollSeconds = mustFloat(env("PACKEROO_POLL_SECONDS", "5"))
	client      = &http.Client{Timeout: 30 * time.Second}
)

type device struct {
	Table        struct{ Name string }  `json:"table"`
	Location     struct{ Name *string } `json:"location"`
	Organization struct{ Name *string } `json:"organization"`
}

type answer struct {
	status     int
	body       []byte
	retryAfter time.Duration
	problem    struct {
		Code   string `json:"code"`
		Detail string `json:"detail"`
	}
}

func main() {
	token := readToken()
	var paired *device

	// With a stored token, ask first whether it still signs in; nil after a 401.
	if token != "" {
		paired = waitForPairing(token, nil)
	}

	for paired == nil {
		var expiresAt *time.Time
		token, expiresAt = requestCode(token)
		paired = waitForPairing(token, expiresAt)
		if paired == nil && expiresAt == nil {
			// Paired a moment ago, unpaired now: this token is of no use any more.
			fmt.Println(text.unpaired)
			token = ""
		} else if paired == nil {
			fmt.Println(text.expired)
		}
	}

	location := text.noLocation
	if paired.Location.Name != nil {
		location = *paired.Location.Name
	}
	fmt.Printf(text.paired, paired.Table.Name, location)
}

// call sends one request to the API. Network errors are retried.
func call(method, path, token string, body any, idempotencyKey string) answer {
	for failures := 1; ; failures++ {
		var reader io.Reader
		if body != nil {
			encoded, _ := json.Marshal(body)
			reader = bytes.NewReader(encoded)
		}
		request, _ := http.NewRequest(method, baseURL+path, reader)
		request.Header.Set("User-Agent", userAgent)
		request.Header.Set("Accept", "application/json")
		request.Header.Set("Accept-Language", "de")
		if token != "" {
			request.Header.Set("Authorization", "Bearer "+token)
		}
		if body != nil {
			request.Header.Set("Content-Type", "application/json")
		}
		// A write carries an Idempotency-Key; a retry of the same request sends the same key.
		if idempotencyKey != "" {
			request.Header.Set("Idempotency-Key", idempotencyKey)
		}

		response, err := client.Do(request)
		if err != nil {
			pauseAfterError(failures, err)
			continue
		}
		data, _ := io.ReadAll(response.Body)
		response.Body.Close()

		result := answer{status: response.StatusCode, body: data, retryAfter: 60 * time.Second}
		// Retry-After is a number of seconds or an HTTP date.
		if value := response.Header.Get("Retry-After"); value != "" {
			if seconds, err := strconv.Atoi(value); err == nil {
				result.retryAfter = time.Duration(seconds) * time.Second
			} else if date, err := http.ParseTime(value); err == nil {
				result.retryAfter = time.Until(date)
			}
			if result.retryAfter < time.Second {
				result.retryAfter = time.Second
			}
		}
		// A body that is no JSON, such as the error page of a proxy, leaves the problem empty.
		if response.StatusCode >= 400 {
			_ = json.Unmarshal(data, &result.problem)
		}
		return result
	}
}

// pauseAfterError waits after a network error, a 5xx or an unexpected answer: pollSeconds, doubled
// with every error in a row, at most maxPauseSeconds. A device never asks again without a pause.
func pauseAfterError(failures int, reason any) {
	seconds := math.Min(pollSeconds*math.Pow(2, float64(failures-1)), maxPauseSeconds)
	fmt.Fprintf(os.Stderr, text.offline, reason, seconds)
	sleep(seconds)
}

// requestCode asks for a code. It returns the token and when the code runs out; nil when the token is paired already.
func requestCode(token string) (string, *time.Time) {
	key := uuid()
	failures := 0
	for {
		result := call("POST", "/device-pairings", token, map[string]string{"model": "Kickertisch-Beispiel", "firmware": "1.0"}, key)
		switch {
		case result.status == 201:
			var created struct {
				Data struct {
					Code      string    `json:"code"`
					ExpiresAt time.Time `json:"expires_at"`
					Token     string    `json:"token"`
				} `json:"data"`
			}
			if err := json.Unmarshal(result.body, &created); err != nil {
				fail(result)
			}
			// Shown only this once: keep it before anything else.
			saveToken(created.Data.Token)
			showCode(created.Data.Code, created.Data.ExpiresAt)
			return created.Data.Token, &created.Data.ExpiresAt
		case result.status == 409 && result.problem.Code == "device_already_paired":
			return token, nil
		case result.status == 409 && result.problem.Code == "table_devices_off":
			fmt.Println(text.off)
			time.Sleep(60 * time.Second)
		case result.status == 429:
			time.Sleep(result.retryAfter)
		case result.status >= 500:
			// The API is busy or being deployed: the same request with the same key, after a pause.
			failures++
			pauseAfterError(failures, fmt.Sprintf("HTTP %d", result.status))
		default:
			fail(result)
		}
	}
}

// waitForPairing reads GET /device until it answers 200. Nil once the code has run out, or at once
// when no code is waiting (expiresAt nil) and the token does not sign in: the device was unpaired.
// Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
func waitForPairing(token string, expiresAt *time.Time) *device {
	failures := 0
	for {
		result := call("GET", "/device", token, nil, "")
		switch result.status {
		case 200:
			return decodeDevice(result)
		case 429:
			time.Sleep(result.retryAfter)
			continue
		case 401:
			failures = 0
		default:
			// A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
			if result.status >= 400 && result.status < 500 {
				fail(result)
			}
			// Someone may be typing the code right now: keep it, ask again after a pause.
			failures++
			pauseAfterError(failures, fmt.Sprintf("HTTP %d", result.status))
			continue
		}
		if expiresAt == nil || !time.Now().Before(*expiresAt) {
			return nil
		}
		sleep(pollSeconds)
	}
}

func decodeDevice(result answer) *device {
	var read struct{ Data device }
	if err := json.Unmarshal(result.body, &read); err != nil {
		fail(result)
	}
	return &read.Data
}

func readToken() string {
	data, err := os.ReadFile(tokenFile)
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(data))
}

// saveToken keeps the token in a file only this user can read, written in one step.
func saveToken(token string) {
	if err := os.MkdirAll(filepath.Dir(tokenFile), 0o700); err != nil {
		panic(err)
	}
	temporary := tokenFile + ".tmp"
	// A leftover from a crash may have other rights: remove it, then create the file anew.
	_ = os.Remove(temporary)
	file, err := os.OpenFile(temporary, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
	if err != nil {
		panic(err)
	}
	if _, err := file.WriteString(token + "\n"); err != nil {
		panic(err)
	}
	if err := file.Close(); err != nil {
		panic(err)
	}
	if err := os.Rename(temporary, tokenFile); err != nil {
		panic(err)
	}
}

func showCode(code string, expiresAt time.Time) {
	// The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
	// For a QR code on a display, a package such as github.com/skip2/go-qrcode draws this link.
	parsed, _ := url.Parse(baseURL)
	host := parsed.Host
	if strings.HasPrefix(host, "api.") {
		host = "app." + host[4:]
	}
	fmt.Println()
	fmt.Printf(text.code, code[:3], code[3:], expiresAt.Local().Format("15:04"))
	fmt.Printf(text.link, "https://"+host+"/verbinden?code="+code)
	fmt.Println(text.enter)
	fmt.Println()
}

func fail(result answer) {
	detail := result.problem.Detail
	if detail == "" {
		detail = text.unexpected
	}
	fmt.Fprintf(os.Stderr, text.error, result.status, result.problem.Code, detail)
	os.Exit(1)
}

func uuid() string {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	b[6] = b[6]&0x0f | 0x40
	b[8] = b[8]&0x3f | 0x80
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}

func env(name, fallback string) string {
	if value := os.Getenv(name); value != "" {
		return value
	}
	return fallback
}

func home() string {
	dir, _ := os.UserHomeDir()
	return dir
}

func mustFloat(value string) float64 {
	number, err := strconv.ParseFloat(value, 64)
	if err != nil {
		return 5
	}
	return number
}

func sleep(seconds float64) {
	time.Sleep(time.Duration(seconds * float64(time.Second)))
}
```

#### Java (java/PairDevice.java)

```java
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. Java 17 or newer, java.net.http, no libraries.
//
//   java PairDevice.java
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
//
// The answers are read with a small helper to stay without libraries; in a real device take a
// JSON library such as Jackson or Gson.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PairDevice {
    /** What the device shows, in the language of the location. */
    static final class Text {
        static final String CODE = "Code am Tisch: %s %s  (gilt bis %s Uhr)";
        static final String LINK = "QR-Code mit diesem Link: %s";
        static final String ENTER = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.";
        static final String EXPIRED = "Der Code ist abgelaufen. Ich hole einen neuen.";
        static final String UNPAIRED = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.";
        static final String OFF = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.";
        static final String OFFLINE = "Keine Verbindung (%s), neuer Versuch in %s s";
        static final String PAIRED = "Verbunden mit %s";
        static final String ERROR = "Fehler %d %s: %s";
        static final String UNEXPECTED = "unerwartete Antwort";
    }

    // Every request names the device: product and firmware.
    static final String USER_AGENT = "Kickertisch-Beispiel/1.0";
    static final String BASE_URL = env("PACKEROO_BASE_URL", "https://api.qm.packeroo.com/api/v1").replaceAll("/+$", "");
    static final Path TOKEN_FILE = Path.of(env("PACKEROO_TOKEN_FILE", Path.of(System.getProperty("user.home"), ".config", "packeroo", "device-token").toString()));
    static final double POLL_SECONDS = Double.parseDouble(env("PACKEROO_POLL_SECONDS", "5"));
    /** After errors in a row the pause doubles, up to this many seconds. */
    static final double MAX_PAUSE_SECONDS = 60;
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();

    record Answer(int status, String body, long retryAfterSeconds) {}

    record Pairing(String token, Instant expiresAt) {}

    public static void main(String[] args) throws Exception {
        String token = readToken();
        // With a stored token, ask first whether it still signs in; null after a 401.
        String device = token == null ? null : waitForPairing(token, null);

        while (device == null) {
            Pairing pairing = requestCode(token);
            token = pairing.token();
            device = waitForPairing(token, pairing.expiresAt());
            if (device == null && pairing.expiresAt() == null) {
                // Paired a moment ago, unpaired now: this token is of no use any more.
                System.out.println(Text.UNPAIRED);
                token = null;
            } else if (device == null) {
                System.out.println(Text.EXPIRED);
            }
        }

        String table = field(device, "\"table\"\\s*:\\s*\\{[^}]*?\"name\"").orElse("?");
        System.out.println(String.format(Text.PAIRED, table));
    }

    /** One request to the API. Network errors are retried. */
    static Answer call(String method, String path, String token, String json, String idempotencyKey) throws InterruptedException {
        HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(BASE_URL + path))
            .timeout(Duration.ofSeconds(30))
            .header("User-Agent", USER_AGENT)
            .header("Accept", "application/json")
            .header("Accept-Language", "de")
            .method(method, json == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(json));
        if (token != null) builder.header("Authorization", "Bearer " + token);
        if (json != null) builder.header("Content-Type", "application/json");
        // A write carries an Idempotency-Key; a retry of the same request sends the same key.
        if (idempotencyKey != null) builder.header("Idempotency-Key", idempotencyKey);
        HttpRequest request = builder.build();

        for (int failures = 1; ; failures++) {
            try {
                HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
                long retryAfter = response.headers().firstValue("Retry-After").map(PairDevice::retryAfterSeconds).orElse(60L);
                // A body that is no JSON, such as the error page of a proxy, has no fields: field() finds none.
                return new Answer(response.statusCode(), response.body(), retryAfter);
            } catch (IOException error) {
                pauseAfterError(failures, error.getMessage());
            }
        }
    }

    /**
     * Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
     * error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
     */
    static void pauseAfterError(int failures, String reason) throws InterruptedException {
        double seconds = Math.min(POLL_SECONDS * Math.pow(2, failures - 1), MAX_PAUSE_SECONDS);
        System.err.println(String.format(Text.OFFLINE, reason, seconds));
        sleep(seconds);
    }

    /** Retry-After is a number of seconds or an HTTP date such as "Wed, 21 Oct 2026 07:28:00 GMT". */
    static long retryAfterSeconds(String value) {
        try {
            return Math.max(1, Long.parseLong(value.trim()));
        } catch (NumberFormatException notANumber) {
            try {
                ZonedDateTime date = ZonedDateTime.parse(value.trim(), DateTimeFormatter.RFC_1123_DATE_TIME);
                return Math.max(1, Duration.between(Instant.now(), date.toInstant()).getSeconds());
            } catch (DateTimeParseException notADate) {
                return 60;
            }
        }
    }

    /** Asks for a code. expiresAt is null when the token is paired already. */
    static Pairing requestCode(String token) throws Exception {
        String key = UUID.randomUUID().toString();
        int failures = 0;
        while (true) {
            Answer result = call("POST", "/device-pairings", token, "{\"model\":\"Kickertisch-Beispiel\",\"firmware\":\"1.0\"}", key);
            if (result.status() == 201) {
                String newToken = field(result.body(), "\"token\"").orElseThrow();
                // Shown only this once: keep it before anything else.
                saveToken(newToken);
                String code = field(result.body(), "\"code\"").orElseThrow();
                Instant expiresAt = Instant.parse(field(result.body(), "\"expires_at\"").orElseThrow());
                showCode(code, expiresAt);
                return new Pairing(newToken, expiresAt);
            }
            String problem = field(result.body(), "\"code\"").orElse("");
            if (result.status() == 409 && problem.equals("device_already_paired")) return new Pairing(token, null);
            if (result.status() == 409 && problem.equals("table_devices_off")) {
                System.out.println(Text.OFF);
                sleep(60);
            } else if (result.status() == 429) {
                sleep(result.retryAfterSeconds());
            } else if (result.status() >= 500) {
                // The API is busy or being deployed: the same request with the same key, after a pause.
                pauseAfterError(++failures, "HTTP " + result.status());
            } else {
                fail(result);
            }
        }
    }

    /**
     * GET /device until it answers 200. Null once the code has run out, or at once when no code is
     * waiting (expiresAt null) and the token does not sign in: the device was unpaired.
     * Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
     */
    static String waitForPairing(String token, Instant expiresAt) throws InterruptedException {
        int failures = 0;
        while (true) {
            Answer result = call("GET", "/device", token, null, null);
            if (result.status() == 200) return result.body();
            if (result.status() == 429) {
                sleep(result.retryAfterSeconds());
                continue;
            }
            // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
            if (result.status() >= 400 && result.status() < 500 && result.status() != 401) fail(result);
            if (result.status() != 401) {
                // Someone may be typing the code right now: keep it, ask again after a pause.
                pauseAfterError(++failures, "HTTP " + result.status());
                continue;
            }
            failures = 0;
            if (expiresAt == null || !Instant.now().isBefore(expiresAt)) return null;
            sleep(POLL_SECONDS);
        }
    }

    static String readToken() throws IOException {
        if (!Files.exists(TOKEN_FILE)) return null;
        String token = Files.readString(TOKEN_FILE).trim();
        return token.isEmpty() ? null : token;
    }

    /** Keeps the token in a file only this user can read, written in one step. */
    static void saveToken(String token) throws IOException {
        Path directory = TOKEN_FILE.toAbsolutePath().getParent();
        Files.createDirectories(directory);
        Path temporary = directory.resolve(TOKEN_FILE.getFileName() + ".tmp");
        Files.deleteIfExists(temporary);
        try {
            Files.createFile(temporary, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
        } catch (UnsupportedOperationException windows) {
            Files.createFile(temporary);
        }
        Files.writeString(temporary, token + "\n");
        Files.move(temporary, TOKEN_FILE, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
    }

    static void showCode(String code, Instant expiresAt) {
        // The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
        // For a QR code on a display, a library such as ZXing draws this link.
        String host = URI.create(BASE_URL).getAuthority();
        if (host.startsWith("api.")) host = "app." + host.substring(4);
        String until = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneId.systemDefault()).format(expiresAt);
        System.out.println();
        System.out.println(String.format(Text.CODE, code.substring(0, 3), code.substring(3), until));
        System.out.println(String.format(Text.LINK, "https://" + host + "/verbinden?code=" + code));
        System.out.println(Text.ENTER);
        System.out.println();
    }

    /** The string value after a key, such as "\"code\"" in {"code":"K7F4QX"}. */
    static Optional<String> field(String json, String key) {
        Matcher match = Pattern.compile(key + "\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").matcher(json == null ? "" : json);
        return match.find() ? Optional.of(match.group(1)) : Optional.empty();
    }

    static void fail(Answer result) {
        String problem = field(result.body(), "\"code\"").orElse("");
        String detail = field(result.body(), "\"detail\"").orElse(Text.UNEXPECTED);
        System.err.println(String.format(Text.ERROR, result.status(), problem, detail));
        System.exit(1);
    }

    static void sleep(double seconds) throws InterruptedException {
        Thread.sleep((long) (seconds * 1000));
    }

    static String env(String name, String fallback) {
        String value = System.getenv(name);
        return value == null || value.isEmpty() ? fallback : value;
    }
}
```

#### curl (shell/pair-device.sh)

```bash
#!/usr/bin/env bash
# Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
# someone enters the code in the app. Needs bash, curl and jq.
#
#   bash pair-device.sh
#
# PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
# PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
# PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
set -euo pipefail

# What the device shows, in the language of the location.
TEXT_CODE='Code am Tisch: %s %s  (gilt bis %s UTC)\n'
TEXT_LINK='QR-Code mit diesem Link: %s\n'
TEXT_ENTER='Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.'
TEXT_EXPIRED='Der Code ist abgelaufen. Ich hole einen neuen.'
TEXT_UNPAIRED='Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.'
TEXT_OFF='Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.'
TEXT_OFFLINE='Keine Verbindung (%s), neuer Versuch in %s s\n'
TEXT_NO_KEY='Kein Idempotency-Key: weder /proc/sys/kernel/random/uuid noch uuidgen noch od gefunden.'
TEXT_PAIRED='"Verbunden mit \(.data.table.name) (\(.data.location.name // "ohne Standort"))"'
TEXT_ERROR='Fehler %s %s: %s\n'

BASE_URL="${PACKEROO_BASE_URL:-https://api.qm.packeroo.com/api/v1}"
BASE_URL="${BASE_URL%/}"
TOKEN_FILE="${PACKEROO_TOKEN_FILE:-$HOME/.config/packeroo/device-token}"
POLL_SECONDS="${PACKEROO_POLL_SECONDS:-5}"
MAX_PAUSE_SECONDS=60 # After errors in a row the pause doubles, up to this many seconds.
USER_AGENT="Kickertisch-Beispiel/1.0" # Every request names the device: product and firmware.

BODY_FILE="$(mktemp)"
HEADER_FILE="$(mktemp)"
trap 'rm -f "$BODY_FILE" "$HEADER_FILE"' EXIT

# call METHOD PATH [TOKEN] [IDEMPOTENCY_KEY] [JSON]: prints the status, the body is in $BODY_FILE.
# Network errors are retried.
call() {
  local method="$1" path="$2" token="${3:-}" key="${4:-}" json="${5:-}"
  local args=(-sS -X "$method" -o "$BODY_FILE" -D "$HEADER_FILE" -w '%{http_code}' --max-time 30
    -H "User-Agent: $USER_AGENT" -H 'Accept: application/json' -H 'Accept-Language: de')
  # A write carries an Idempotency-Key; a retry of the same request sends the same key.
  [[ -n "$key" ]] && args+=(-H "Idempotency-Key: $key")
  [[ -n "$json" ]] && args+=(-H 'Content-Type: application/json' --data "$json")
  local status error failures=0
  # The token reaches curl on stdin (--config -), not on the command line, where ps would show it.
  until status="$(curl "${args[@]}" --config - "$BASE_URL$path" <<< "${token:+header = \"Authorization: Bearer $token\"}")"; do
    error=$?
    failures=$((failures + 1))
    pause_after_error "$failures" "curl $error"
  done
  echo "$status"
}

# Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
# error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
pause_after_error() {
  local seconds
  seconds="$(awk -v poll="$POLL_SECONDS" -v n="$1" -v max="$MAX_PAUSE_SECONDS" 'BEGIN { s = poll * 2 ^ (n - 1); print (s > max ? max : s) }')"
  printf "$TEXT_OFFLINE" "$2" "$seconds" >&2
  sleep "$seconds"
}

# Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date.
retry_after() {
  local value seconds
  value="$(grep -i '^retry-after:' "$HEADER_FILE" | cut -d: -f2- | tr -d '\r' | sed 's/^ *//' || true)"
  if [[ "$value" =~ ^[0-9]+$ ]]; then seconds="$value"
  elif [[ -n "$value" ]] && date -d "$value" +%s >/dev/null 2>&1; then seconds=$(( $(date -d "$value" +%s) - $(date +%s) ))
  else seconds=60
  fi
  (( seconds < 1 )) && seconds=1
  echo "$seconds"
}

problem() { jq -r '.code // empty' "$BODY_FILE" 2>/dev/null || true; }

fail() {
  printf "$TEXT_ERROR" "$1" "$(problem)" "$(jq -r '.detail // "unerwartete Antwort"' "$BODY_FILE" 2>/dev/null)" >&2
  exit 1
}

new_key() {
  if [[ -r /proc/sys/kernel/random/uuid ]]; then cat /proc/sys/kernel/random/uuid
  elif command -v uuidgen >/dev/null; then uuidgen | tr 'A-Z' 'a-z'
  elif command -v od >/dev/null; then od -An -N16 -tx1 /dev/urandom | tr -d ' \n' | sed -E 's/(.{8})(.{4}).(.{3}).(.{3})(.{12})/\1-\2-4\3-a\4-\5/'
  fi
}

# Keeps the token in a file only this user can read, written in one step.
save_token() {
  mkdir -p "$(dirname "$TOKEN_FILE")"
  chmod 700 "$(dirname "$TOKEN_FILE")" 2>/dev/null || true
  # A leftover from a crash may have other rights: remove it, then create the file anew
  # (with noclobber, > fails instead of writing into a file that is there).
  rm -f "$TOKEN_FILE.tmp"
  (umask 077 && set -o noclobber && printf '%s\n' "$1" > "$TOKEN_FILE.tmp")
  mv -f "$TOKEN_FILE.tmp" "$TOKEN_FILE"
}

show_code() {
  local code="$1" host
  # The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
  # For a QR code in the terminal, qrencode -t ansiutf8 draws this link.
  host="$(printf '%s' "$BASE_URL" | sed -E 's#^[a-z]+://([^/]+).*#\1#; s#^api\.#app.#')"
  printf '\n'
  printf "$TEXT_CODE" "${code:0:3}" "${code:3}" "$2"
  printf "$TEXT_LINK" "https://$host/verbinden?code=$code"
  printf '%s\n\n' "$TEXT_ENTER"
}

TOKEN=""
[[ -s "$TOKEN_FILE" ]] && TOKEN="$(tr -d '[:space:]' < "$TOKEN_FILE")"
PAIRED=""
EXPIRES=0

# With a stored token, ask first whether it still signs in; only 401 means it does not.
if [[ -n "$TOKEN" ]]; then
  failures=0
  while :; do
    status="$(call GET /device "$TOKEN")"
    case "$status" in
      200) PAIRED=1; break ;;
      401) break ;;
      429) sleep "$(retry_after)" ;;
      # A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
      4??) fail "$status" ;;
      *) failures=$((failures + 1)); pause_after_error "$failures" "HTTP $status" ;;
    esac
  done
fi

while [[ -z "$PAIRED" ]]; do
  # Ask for a code. Without a key the API answers 400, so stop here instead.
  key="$(new_key)"
  if [[ -z "$key" ]]; then echo "$TEXT_NO_KEY" >&2; exit 1; fi
  failures=0
  while :; do
    status="$(call POST /device-pairings "$TOKEN" "$key" '{"model":"Kickertisch-Beispiel","firmware":"1.0"}')"
    if [[ "$status" == 201 ]]; then
      TOKEN="$(jq -r '.data.token' "$BODY_FILE")"
      # Shown only this once: keep it before anything else.
      save_token "$TOKEN"
      expires_at="$(jq -r '.data.expires_at' "$BODY_FILE")"
      EXPIRES="$(jq -r '.data.expires_at | fromdateiso8601' "$BODY_FILE")"
      show_code "$(jq -r '.data.code' "$BODY_FILE")" "${expires_at:11:5}"
      break
    elif [[ "$status" == 409 && "$(problem)" == device_already_paired ]]; then
      EXPIRES=0
      break
    elif [[ "$status" == 409 && "$(problem)" == table_devices_off ]]; then
      echo "$TEXT_OFF"
      sleep 60
    elif [[ "$status" == 429 ]]; then
      sleep "$(retry_after)"
    elif (( status >= 500 )); then
      # The API is busy or being deployed: the same request with the same key, after a pause.
      failures=$((failures + 1))
      pause_after_error "$failures" "HTTP $status"
    else
      fail "$status"
    fi
  done

  # GET /device until it answers 200. Without a waiting code (EXPIRES 0) a 401 means the device
  # was unpaired: drop the token and ask for a new code without it. Only 401 means "not paired";
  # on a 5xx someone may be typing the code: keep it, ask again after a pause. Another 4xx is an error.
  failures=0
  while :; do
    status="$(call GET /device "$TOKEN")"
    if [[ "$status" == 200 ]]; then PAIRED=1; break; fi
    if [[ "$status" == 429 ]]; then sleep "$(retry_after)"; continue; fi
    if [[ "$status" == 4?? && "$status" != 401 ]]; then fail "$status"; fi
    if [[ "$status" != 401 ]]; then
      failures=$((failures + 1))
      pause_after_error "$failures" "HTTP $status"
      continue
    fi
    failures=0
    if [[ "$EXPIRES" == 0 ]]; then
      echo "$TEXT_UNPAIRED"
      TOKEN=""
      break
    fi
    if [[ "$(date +%s)" -ge "$EXPIRES" ]]; then
      echo "$TEXT_EXPIRED"
      break
    fi
    sleep "$POLL_SECONDS"
  done
done

jq -r "$TEXT_PAIRED" "$BODY_FILE"
```

#### ESP32 (arduino/pair_device/pair_device.ino)

```cpp
// Pair an ESP32 with packeroo: ask for a code, show it, keep the token in flash, and ask
// GET /device every 5 seconds until someone enters the code in the app.
// Arduino core for ESP32 (2.x or 3.x) and the library ArduinoJson 7.
//
// Fill in WIFI_SSID and WIFI_PASSWORD. BASE_URL points at the sandbox. This sketch prints to the
// serial monitor; for a display, draw the same texts with a library such as TFT_eSPI or U8g2,
// and the link as a QR code with a library such as QRCode (ricmoo).

#include <Arduino.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <Preferences.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <esp_random.h>
#include <time.h>

// What the device shows, in the language of the location.
const char *TEXT_CODE = "Code am Tisch: %s %s\n";
const char *TEXT_LINK = "QR-Code mit diesem Link: %s/verbinden?code=%s\n";
const char *TEXT_ENTER = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.";
const char *TEXT_EXPIRED = "Der Code ist abgelaufen. Ich hole einen neuen.";
const char *TEXT_UNPAIRED = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.";
const char *TEXT_OFF = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.";
const char *TEXT_PAIRED = "Verbunden mit %s\n";
const char *TEXT_ERROR = "Fehler %d %s, neuer Versuch in %lu s\n";

const char *WIFI_SSID = "";
const char *WIFI_PASSWORD = "";
const char *BASE_URL = "https://api.qm.packeroo.com/api/v1";
const char *APP_URL = "https://app.qm.packeroo.com";
// Every request names the device: product and firmware.
const char *USER_AGENT = "Kickertisch-ESP32/1.0";
const unsigned long POLL_MS = 5000;
// After errors in a row the pause doubles, up to one minute.
const unsigned long MAX_PAUSE_MS = 60000;

// The roots api.packeroo.com and api.qm.packeroo.com chain up to (Let's Encrypt): ISRG Root X1
// (RSA, valid until 2035) and ISRG Root X2 (ECDSA, valid until 2040). If the chain of the API
// changes to a root not listed here, add it and ship a firmware update.
const char *ROOT_CERTIFICATES =
    "-----BEGIN CERTIFICATE-----\n"
    "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n"
    "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"
    "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n"
    "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n"
    "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n"
    "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n"
    "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n"
    "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n"
    "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n"
    "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n"
    "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n"
    "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n"
    "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n"
    "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n"
    "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n"
    "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n"
    "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
    "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n"
    "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n"
    "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n"
    "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n"
    "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n"
    "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n"
    "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n"
    "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n"
    "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n"
    "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n"
    "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n"
    "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n"
    "-----END CERTIFICATE-----\n"
    "-----BEGIN CERTIFICATE-----\n"
    "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n"
    "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n"
    "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n"
    "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n"
    "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n"
    "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n"
    "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n"
    "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n"
    "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n"
    "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n"
    "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n"
    "/q4AaOeMSQ+2b1tbFfLn\n"
    "-----END CERTIFICATE-----\n";

Preferences store;  // The token lives in NVS, never in the sketch.
String token;
unsigned long expiresAtMs = 0;  // millis() when the shown code runs out; 0 when no code is waiting
bool waitingForCode = false;
unsigned long pauseMs = POLL_MS;  // the next pause after an error, doubled with every error in a row

// Waits after a network error, a 5xx or an unexpected answer, and doubles the next pause up to
// MAX_PAUSE_MS. The sketch never asks the API again without a pause.
void pauseAfterError(int status, const char *problem) {
  Serial.printf(TEXT_ERROR, status, problem, pauseMs / 1000);
  delay(pauseMs);
  pauseMs = min(pauseMs * 2, MAX_PAUSE_MS);
}

WiFiClientSecure tls;

// One request. Returns the status (negative on a network error), the body in `body`.
int call(const char *method, const char *path, const String &json, const String &idempotencyKey, String &body, int &retryAfter) {
  HTTPClient http;
  http.begin(tls, String(BASE_URL) + path);
  http.setUserAgent(USER_AGENT);
  http.addHeader("Accept", "application/json");
  http.addHeader("Accept-Language", "de");
  if (token.length() > 0) http.addHeader("Authorization", "Bearer " + token);
  // A write carries an Idempotency-Key; a retry of the same request sends the same key.
  if (idempotencyKey.length() > 0) http.addHeader("Idempotency-Key", idempotencyKey);
  const char *wanted[] = {"Retry-After"};
  http.collectHeaders(wanted, 1);

  int status;
  if (json.length() > 0) {
    http.addHeader("Content-Type", "application/json");
    status = http.sendRequest(method, json);
  } else {
    status = http.sendRequest(method);
  }
  body = status > 0 ? http.getString() : "";
  // Retry-After in seconds; the API sends seconds, so an HTTP date falls back to 60.
  retryAfter = http.header("Retry-After").toInt();
  if (retryAfter <= 0) retryAfter = 60;
  http.end();
  return status;
}

String newKey() {
  uint8_t b[16];
  esp_fill_random(b, sizeof b);
  b[6] = (b[6] & 0x0f) | 0x40;
  b[8] = (b[8] & 0x3f) | 0x80;
  char key[37];
  snprintf(key, sizeof key, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
           b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
  return String(key);
}

// Show these on the display of the table: the code as two groups of three, and the link as a QR code.
void showCode(const String &code) {
  Serial.println();
  Serial.printf(TEXT_CODE, code.substring(0, 3).c_str(), code.substring(3).c_str());
  Serial.printf(TEXT_LINK, APP_URL, code.c_str());
  Serial.println(TEXT_ENTER);
  Serial.println();
}

// Asks for a code. Returns true when there is a code to wait for or the token is paired already;
// false on an answer the sketch cannot act on, after a pause.
bool requestCode() {
  String key = newKey();
  for (;;) {
    String body;
    int retryAfter;
    int status = call("POST", "/device-pairings", "{\"model\":\"Kickertisch-ESP32\",\"firmware\":\"1.0\"}", key, body, retryAfter);
    JsonDocument answer;
    deserializeJson(answer, body);
    const char *problem = answer["code"] | "";

    if (status == 201) {
      token = answer["data"]["token"].as<String>();
      // Shown only this once: keep it before anything else.
      store.putString("token", token);
      // The code is valid for 10 minutes; counted from now with millis(), a few seconds early.
      expiresAtMs = millis() + 10UL * 60UL * 1000UL - 5000UL;
      waitingForCode = true;
      pauseMs = POLL_MS;
      showCode(answer["data"]["code"].as<String>());
      return true;
    }
    if (status == 409 && strcmp(problem, "device_already_paired") == 0) {
      waitingForCode = false;
      pauseMs = POLL_MS;
      return true;
    }
    if (status == 409 && strcmp(problem, "table_devices_off") == 0) {
      Serial.println(TEXT_OFF);
      delay(60000);
    } else if (status == 429) {
      delay(retryAfter * 1000UL);
    } else if (status < 0 || status >= 500) {
      // No network, or the API is busy or being deployed: the same request with the same key.
      pauseAfterError(status, problem);
    } else {
      pauseAfterError(status, problem);
      return false;
    }
  }
}

// GET /device: 1 paired, 0 not yet, -1 the code ran out, -2 unpaired (401 with no code waiting),
// -3 no network, a 5xx or another answer. Only 401 means "not paired": after -3 the code stays,
// someone may be typing it right now. Unattended, the sketch has nobody to stop for: on an answer
// it cannot act on it prints the status and its problem code, and asks again after a pause.
int checkPaired() {
  String body;
  int retryAfter;
  int status = call("GET", "/device", "", "", body, retryAfter);
  if (status == 200) {
    JsonDocument device;
    deserializeJson(device, body);
    Serial.printf(TEXT_PAIRED, device["data"]["table"]["name"] | "?");
    return 1;
  }
  if (status == 429) {
    delay(retryAfter * 1000UL);
    return 0;
  }
  if (status == 401) {
    if (!waitingForCode) return -2;
    if ((long)(millis() - expiresAtMs) >= 0) return -1;
    return 0;
  }
  // No network, a 5xx or another answer: keep the code, ask again after a pause.
  JsonDocument problem;
  deserializeJson(problem, body);
  pauseAfterError(status, problem["code"] | "");
  return -3;
}

bool paired = false;
bool needCode = false;  // true while a new code has to be asked for

void setup() {
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) delay(250);

  // The certificate check needs the right time; take it from NTP before the first request.
  configTime(0, 0, "pool.ntp.org", "time.nist.gov");
  while (time(nullptr) < 1700000000) delay(250);
  tls.setCACert(ROOT_CERTIFICATES);

  store.begin("packeroo", false);
  token = store.getString("token", "");
  if (token.length() > 0) paired = checkPaired() == 1;
  // Not paired, or no answer yet: ask for a code with the stored token; a paired one gets 409.
  needCode = !paired;
}

void loop() {
  if (paired) {
    // From here the table reports to packeroo; the next operations are planned.
    delay(60000);
    return;
  }
  if (needCode) {
    // requestCode() has paused already when it gives up; loop() asks again with a new key.
    if (!requestCode()) return;
    needCode = false;
  }
  int state = checkPaired();
  if (state == 1) {
    paired = true;
  } else if (state == -2) {
    // Paired a moment ago, unpaired now: this token is of no use any more.
    Serial.println(TEXT_UNPAIRED);
    token = "";
    store.remove("token");
    needCode = true;
  } else if (state == -1) {
    Serial.println(TEXT_EXPIRED);
    needCode = true;
  } else if (state == 0) {
    pauseMs = POLL_MS;
    delay(POLL_MS);
  }
  // -3: checkPaired() has paused already.
}
```

The examples print German, because the app in which the code is entered is labelled in German. For your device, use the language of the location.

## Ask for a code

```http
POST /api/v1/device-pairings
User-Agent: Kickertisch/1.2
Idempotency-Key: 0d1c6f8e-3b9a-4c55-9e1f-7a2b4c6d8e90
Content-Type: application/json
Accept-Language: en

{"model": "Kickertisch", "serial": "KT-0042", "firmware": "1.2"}
```

- **`User-Agent`** is required and names product and firmware, such as `Kickertisch/1.2`. Without it the answer is `400` with `user_agent_required`.
- **`Idempotency-Key`** is required on every write: a UUID or ULID, new for each request. If a request fails on the network, send it again with the same key.
- **The body** is optional. `model` and `serial` may be 80 characters long, `firmware` 40. The app shows them in the list of the table, so the device can be recognized.
- **`Authorization: Bearer …`** is sent only by a device that has a token already, for example because its last code ran out. It then gives up the old code and gets a new one.

The answer with `201`:

```json
{
  "data": {
    "code": "K7F4QX",
    "expires_at": "2026-11-22T14:15:00Z",
    "token": "pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD"
  }
}
```

The code is valid for ten minutes, until `expires_at` (UTC). You get the token only in this answer; it carries `Cache-Control: no-store`, and the server does not keep it under the idempotency key either. If you send the same request again, you therefore get a new code and a new token. Always use the one you got last.

## Show the code and a QR code

Show the code as two groups of three characters: **K7F 4QX**. Codes are capital letters and digits without the easily confused characters 0, O, 1, I, L, 5 and S. Whoever types it may use spaces, dashes and small letters; the app takes care of that.

The QR code holds a link into the app ending in `/verbinden?code=`:

| Environment | Content of the QR code |
| --- | --- |
| Live | `https://app.packeroo.com/verbinden?code=K7F4QX` |
| Sandbox | `https://app.qm.packeroo.com/verbinden?code=K7F4QX` |

Scanned with the phone camera, it opens the page `/verbinden` of the app with the code filled in. There is a QR library for every language, such as `qrcode` for Python, `qrcode` for Node.js or `QRCoder` for .NET. The Python example draws the QR code in the terminal when `qrcode` is installed (`pip install qrcode`) and shows the link otherwise.

## Keep the token safe

The token is the key of your device. Whoever has it signs in as this device.

- **Keep it in a file only the device's user can read**, on Linux with mode `600` (`-rw-------`) in a directory with `700`. Write a temporary file first and rename it, so a power cut never leaves half a file. The examples do exactly that.
- **Not in the source code, not in a log, not in a URL.** To show it while debugging, show the first 13 characters, such as `pkd_test_7Hq2`; the app shows it the same way.
- **The prefix tells the environment:** `pkd_live_` works only live, `pkd_test_` only in the sandbox. The API refuses a token of the other environment as if there were none.
- **Not in a repository.** The default path `~/.config/packeroo/device-token` is outside your project. If you keep the file in the project folder, add it to `.gitignore`:

  ```text
  device-token
  device-token.tmp
  ```
- **Who sees the token:** nobody as a whole. Whoever manages the location sees the device's ID in the app, the first 13 characters such as `pkd_test_7Hq2`, to tell devices apart.
- **The checksum** at the end lets secret scanners recognize a leaked token, for example in a published repository.

### Why the token does not expire

A table device often runs for a long time without a keyboard and without anyone next to it. A token with an expiry date would lock the table out at some point, and restoring a backup of the SD card would bring back an outdated one. So the token stays valid until the device is unpaired. Replacing the token while the device runs is planned.

If you set up the device again or put in a new SD card, pair it again. Once the new device is paired at the table, the old token no longer works.

### Lost or stolen

Unpair the device in the app: under Profile › Organization › Tables, then "Pair a device" at the table, "Unpair" at the device. The token stops working at once. A device that has not reported for 90 days is unpaired by packeroo itself.

## Wait for the pairing

Ask `GET /device` every five seconds, with the token and the `User-Agent`:

```http
GET /api/v1/device
User-Agent: Kickertisch/1.2
Authorization: Bearer pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD
```

- **`401`** with `unauthenticated`: the code has not been entered yet. Keep waiting.
- **`200`**: the device is paired. The answer names the table, the location with its time zone and the organization.
- **After `expires_at`** the answer stays `401`, because nobody can enter the old code any more. Ask for a new one and send the token you have.

A device may ask `GET /device` 120 times a minute; every five seconds is twelve. There is no socket connection for devices yet.

## On restart

When the device starts again, it first asks `GET /device` with the stored token:

- `200`: it is paired and carries on.
- `401`: it is not paired, or no longer. It asks for a new code and sends the stored token with it.
- No answer, `5xx` or another answer: it asks again after a pause. Only `401` means "not paired".

A device is unpaired when someone unpairs it in the app, another device is paired at its table, the table is archived, or it has not reported for 90 days. After that `GET /device` answers `401`, and the device pairs as it did the first time.

No device is unpaired without notice: when it has not reported for 24 hours, everyone who looks after the location gets a notification, and the app shows at the device on which day it is unpaired if it stays silent. More under [Security and privacy](https://developers.packeroo.com/en/security-and-privacy/#when-a-device-is-unpaired).

## Error cases

Every error comes as a problem after RFC 9457 with a fixed `code`. Always branch on `code`, never on the text in `detail`; that one follows the language of `Accept-Language` (German or English, German without the header).

| Case | Answer | What the device does |
| --- | --- | --- |
| Code ran out | `GET /device` stays `401` after `expires_at` | ask for a new code, with the current token as bearer |
| Paired already | `POST /device-pairings` with a token: `409` `device_already_paired` | keep the token and ask `GET /device` |
| Table devices switched off | `POST`: `409` `table_devices_off`; `GET /device`: `401` | show "Table devices are switched off", try again once a minute |
| No User-Agent | `400` `user_agent_required` | set the header; this is a bug in the program |
| Missing or wrong idempotency key | `400` `idempotency_key_required` | send a UUID or ULID |
| Same key, other request | `422` `idempotency_key_reused` | make a new key for every new request |
| Same request still running | `409` `request_in_progress` | wait a moment, then send again with the same key |
| Field too long | `422` `validation_failed` with `errors` per field | shorten `model`, `serial`, `firmware` |
| Too many requests | `429` `rate_limited` with `Retry-After` | wait as many seconds as `Retry-After` says |
| No connection or server error | network error or `5xx`, often without JSON (during a deploy, say) | keep the code, ask again after a pause; the pause doubles up to 60 seconds |
| Device unpaired | `GET /device`: `401` after there was `200` | pair again, with the old token as bearer |
| Paired, then unpaired | `POST`: `409` `device_already_paired`, then `GET /device`: `401` | drop the token and ask for a new code without it |

The owner of an organization switches table devices on and off in the app. While they are off, no device pairs and none signs in.

## Recipe: a Raspberry Pi at the table

A Raspberry Pi with a display is the quickest way to a table device. Put `pair_device.py` and `display.py` side by side in `/home/pi/packeroo/`. `display.py` runs the program and shows the code full screen and, with `python3-qrcode` and `python3-pil.imagetk` installed, the QR code as well. If `pair_device.py` ends with an error, `display.py` starts it again after 30 seconds.

raspberry-pi/display.py:

```python
"""Full-screen display for a Raspberry Pi at the table: runs pair_device.py next to this file and
shows what it prints, the code large, readable from two metres. With the packages qrcode and
Pillow installed (sudo apt install python3-qrcode python3-pil python3-pil.imagetk) it also shows
the QR code. Python 3.9 or newer with tkinter (sudo apt install python3-tk).

    python3 display.py

Should pair_device.py end with an error, display.py starts it again after RESTART_SECONDS and
shows until then what it printed last. Escape closes the window.
"""

import os
import queue
import re
import subprocess
import sys
import threading
import time
import tkinter as tk
from pathlib import Path

PAIR_DEVICE = Path(__file__).with_name("pair_device.py")
CODE = re.compile(r"Code am Tisch: ([A-Z0-9]{3} [A-Z0-9]{3})")
LINK = re.compile(r"https://\S+/verbinden\?code=[A-Z0-9]{6}")
# Seconds before pair_device.py starts again after it ended with an error.
RESTART_SECONDS = 30

# Light type on a dark ground, more than 4.5:1.
BACKGROUND, FOREGROUND, ACCENT = "#15160f", "#f6f6ef", "#d6d63a"

root = tk.Tk()
root.configure(background=BACKGROUND, cursor="none")
root.attributes("-fullscreen", True)
root.bind("<Escape>", lambda _: root.destroy())

height = root.winfo_screenheight()
code_label = tk.Label(root, text="", font=("DejaVu Sans Mono", height // 6, "bold"), fg=FOREGROUND, bg=BACKGROUND)
qr_label = tk.Label(root, bg=BACKGROUND)
status_label = tk.Label(root, text="", font=("DejaVu Sans", height // 28), fg=ACCENT, bg=BACKGROUND, wraplength=root.winfo_screenwidth() - 80, justify="center")
code_label.pack(expand=True)
qr_label.pack()
status_label.pack(expand=True)

def show_qr(link):
    try:
        import qrcode
        from PIL import ImageTk
    except ImportError:
        return
    image = qrcode.make(link, border=2).resize((height // 3, height // 3))
    qr_label.image = ImageTk.PhotoImage(image)
    qr_label.configure(image=qr_label.image)

def show(line):
    """One line of pair_device.py: the code, the link for the QR code, or a message in words."""
    if match := CODE.search(line):
        code_label.configure(text=match.group(1))
    elif match := LINK.search(line):
        show_qr(match.group(0))
    elif line.strip():
        if line.startswith("Verbunden"):
            code_label.configure(text="")
            qr_label.configure(image="")
        status_label.configure(text=line.strip())

def read_output():
    """Runs pair_device.py until it ends with 0, paired. After an error it waits and starts it again;
    without this the screen would keep the last line, and systemd would not notice."""
    # Unbuffered, so every line arrives as soon as pair_device.py prints it.
    environment = {**os.environ, "PYTHONUNBUFFERED": "1", "PYTHONIOENCODING": "utf-8"}
    while True:
        process = subprocess.Popen([sys.executable, str(PAIR_DEVICE)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", env=environment)
        for line in process.stdout:
            lines.put(line)
        if process.wait() == 0:
            return
        time.sleep(RESTART_SECONDS)

def show_waiting_lines():
    # tkinter belongs to its own thread; the reader hands the lines over through a queue.
    while not lines.empty():
        show(lines.get())
    root.after(200, show_waiting_lines)

lines = queue.Queue()
threading.Thread(target=read_output, daemon=True).start()
show_waiting_lines()
root.mainloop()
```

So that the Pi shows it again after every boot and after a crash, systemd starts it:

raspberry-pi/packeroo-device.service:

```ini
# Starts the display at the table after every boot and again after a crash of display.py.
# display.py itself starts pair_device.py again when that ends with an error.
# Copy to /etc/systemd/system/, then: sudo systemctl enable --now packeroo-device
[Unit]
Description=packeroo table device
Wants=network-online.target
# After the display manager, not graphical.target: that target wants this unit, so ordering
# after it would make a cycle that systemd breaks by dropping a job at boot.
After=network-online.target display-manager.service

[Service]
User=pi
WorkingDirectory=/home/pi/packeroo
Environment=PACKEROO_BASE_URL=https://api.qm.packeroo.com/api/v1
Environment=PACKEROO_TOKEN_FILE=/home/pi/.config/packeroo/device-token
Environment=DISPLAY=:0
ExecStart=/usr/bin/python3 /home/pi/packeroo/display.py
Restart=always
RestartSec=5

[Install]
WantedBy=graphical.target
```

```bash
sudo cp packeroo-device.service /etc/systemd/system/
sudo systemctl enable --now packeroo-device
```

**After a power cut** the token file is still there, because it is written in one step. The Pi boots, systemd starts `display.py`, the program asks `GET /device` with the stored token and signs in again without a new code. It shows a new code only if the device has been unpaired meanwhile.

## Readable at the table

People read at the table standing, from two metres, often in the middle of a match. So for the display of your device:

- **Contrast after WCAG 2.2 AA:** at least 4.5:1 for text, 3:1 for large type and symbols.
- **Readable from two metres:** the code is the largest thing on the screen, in a typeface with equally wide digits, as two groups of three. Test it the way it is used: stand two metres in front of the display and read the code.
- **Never colour alone:** "Paired", "Code ran out" or "Table devices are switched off" stand on the display as words, not only as a green or red dot.
- **Time to read:** messages stay until the state changes, or as long as can be set on the device.

## What comes next

Planned and not available yet: reading the queue of a table, starting a match at the table, reporting goals live, reporting the result from the table and recognizing players by chip. The token carries the scopes for it already (`scopes` in `GET /device`); the operations follow one by one. Each new one appears in the [changelog](https://developers.packeroo.com/en/changelog/) on the day it becomes public.

---

# Concepts

> How the packeroo API signs in, makes retries safe, reports errors and limits requests. Token prefixes, idempotency keys, problem answers after RFC 9457, rate limits, User-Agent, times and versions.

These rules hold for every public operation. What is described here is built; what is planned is marked as such.

## Addresses

| Environment | Base address | Tokens |
| --- | --- | --- |
| Live | `https://api.packeroo.com/api/v1` | `pkd_live_…` |
| Sandbox | `https://api.qm.packeroo.com/api/v1` | `pkd_test_…` |

The sandbox is the demo environment of packeroo. It can be reset; keep nothing there you want to keep. In the sandbox a device pairs itself with `POST /sandbox/device-pairings/confirm` at a test table of its own, without anyone entering the code in the app; see the [quickstart](https://developers.packeroo.com/en/quickstart/).

## Authentication and token prefixes

A device signs in with its token in the header:

```http
Authorization: Bearer pkd_live_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD
```

The token is a random string, not a JWT: it carries no data, and once the device is unpaired it stops working at once. packeroo stores only its SHA-256 hash and shows it exactly once, in the answer to `POST /device-pairings`.

A token is 47 characters long: a prefix, 32 random characters and a checksum of 6. The prefix tells kind and environment. The checksum lets secret scanners recognize a leaked token, and the API refuses a mistyped one without looking it up.

| Prefix | Kind | State |
| --- | --- | --- |
| `pkd_live_`, `pkd_test_` | device at a table | available |
| `pko_live_`, `pko_test_` | organization key for intranets, dashboards, chat bots | planned |
| `pkp_live_`, `pkp_test_` | personal token | planned |

Tokens belong on devices and servers, never in a web page. The API accepts requests from a browser only from the packeroo app.

## Scopes

`GET /device` names in `scopes` what the token may do. For a device token this is a fixed set: `leagues:read`, `standings:read`, `matches:read`, `matches:write`, `matches:live`. It includes scopes for operations that are planned; those take effect only once the operations exist. Today the token is good for `GET /device`. When an operation is added, a paired device does not need to be paired again: its token has the scopes already.

## Idempotency key

Every write (`POST`, `PUT`, `PATCH`, `DELETE`) carries the header `Idempotency-Key` with a UUID or ULID. Make a new key for every new action, and send the same one when you repeat a request, for example after a network error.

- The same request with the same key gets the first answer again, with the header `Idempotent-Replayed: true`, and has no second effect. Only successful answers are kept, for 48 hours.
- No key, or one that is neither UUID nor ULID: `400` `idempotency_key_required`.
- The same key with a different request: `422` `idempotency_key_reused`.
- The first request is still running: `409` `request_in_progress`. Wait a moment and repeat it with the same key.
- An answer holding a secret, such as the token of `POST /device-pairings`, is never kept. A repeat runs again there and gives a new code with a new token.

## Error answers

Every error comes as a problem after [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) with the content type `application/problem+json`:

```json
{
  "type": "https://api.packeroo.com/problems/user-agent-required",
  "title": "User-Agent required",
  "status": 400,
  "detail": "The device does not name itself. Every request needs a User-Agent, such as Kickertisch/1.2.",
  "code": "user_agent_required",
  "correlation_id": "01JD7R4X2Y3Z4A5B6C7D8E9F0G"
}
```

- **`code`** is fixed. Branch only on `code` in your program.
- **`title`** is a short English summary, the same for every occurrence of a code.
- **`detail`** says what happened and what to do, in the language of `Accept-Language`: `de` or `en`, German without the header. It is meant for display, not for parsing.
- **`correlation_id`** is also in the header `X-Correlation-Id` of every answer. Name it when you write to us about an error.
- **`errors`** comes only with `validation_failed`: the messages per field.

### Codes of the public operations

| Code | Status | Meaning |
| --- | --- | --- |
| `user_agent_required` | 400 | The request has no `User-Agent`. |
| `idempotency_key_required` | 400 | The write has no valid `Idempotency-Key`. |
| `bad_request` | 400 | The request cannot be read, for example no valid UTF-8. |
| `unauthenticated` | 401 | No valid token: not paired yet, unpaired, from the other environment, or table devices are switched off. |
| `not_found` | 404 | The operation does not exist here, such as `POST /sandbox/device-pairings/confirm` outside the sandbox. |
| `device_already_paired` | 409 | The device asking for a code is paired already. It keeps its token. |
| `table_devices_off` | 409 | Table devices are switched off; no device pairs. |
| `request_in_progress` | 409 | A request with the same idempotency key is still running. |
| `idempotency_key_reused` | 422 | The idempotency key belongs to another request already. |
| `validation_failed` | 422 | A field is invalid; `errors` names it. |
| `rate_limited` | 429 | Too many requests; `Retry-After` gives the wait in seconds. |
| `server_error` | 500 | An error at packeroo. The cause is in our log under the `correlation_id`. |
| `unavailable` | 503 | packeroo cannot be reached for a moment. Try again later. |

## Rate limits

| What | Limit |
| --- | --- |
| `POST /device-pairings` | 60 a minute per IP address |
| `POST /sandbox/device-pairings/confirm` | 10 an hour and 20 new test tables a day per IP address (IPv6 per /48) |
| `GET /device` | 120 a minute per device |

The limit for codes counts per IP address, the one for `GET /device` per device. An example: in a hall, 40 tables sit behind one address. After a power cut all of them ask for a code at once, which is 40 of 60 `POST` a minute. Then every device asks `GET /device` every five seconds, 12 of 120 per device; the 40 devices do not add up there. With more than 60 tables behind one address, the rest get `429` with `Retry-After` and ask again after it; the examples of the guide do that by themselves. Whoever goes over a limit gets `429` with `rate_limited` and the header `Retry-After` in seconds. Wait that long before you try again.

Planned: the headers `RateLimit` and `RateLimit-Policy` after the IETF draft on every answer, and limits of their own for goals and organization keys once those operations exist.

## User-Agent

Every request of a device names its product and firmware in the `User-Agent`, such as `Kickertisch/1.2` or `Kickertisch-ESP32/0.9.3`. That tells a misbehaving device apart from the others in the logs without anyone looking at its token. Without a `User-Agent` the API answers `400` with `user_agent_required`.

## Times

Times come in ISO 8601 and always in UTC, with a `Z` at the end: `2026-11-22T14:15:00Z`. Show them in the time zone of the location; `GET /device` names it in `location.time_zone`, such as `Europe/Berlin`. IDs are ULIDs, 26 characters, sortable by time.

## Versioning

The version is in the path: `/api/v1`. Within `v1` only additions come: new operations, new fields, new error codes. Write your program so that unknown fields in an answer break nothing. What would break existing programs goes into a new version `v2`.

Planned: what goes away is announced with the headers `Deprecation` and `Sunset` (RFC 8594), at least six months ahead. For operations of devices, whose firmware stays in the field for years, twelve months ahead and not before 24 months after their release.

New operations and changes are in the [changelog](https://developers.packeroo.com/en/changelog/), also as an RSS feed.

---

# Reference

> Every public operation of the packeroo API with parameters, answers, error codes and code samples in curl, Python, JavaScript, PHP, Java, Kotlin, C#, Go, Ruby, Swift, Dart, Rust and PowerShell.

The public operations:

- [`POST /sandbox/device-pairings/confirm`](https://developers.packeroo.com/en/reference/#tag/sandbox/POST/sandbox/device-pairings/confirm): Pair this device in the sandbox
- [`POST /device-pairings`](https://developers.packeroo.com/en/reference/#tag/table-devices/POST/device-pairings): Ask to pair this device
- [`GET /device`](https://developers.packeroo.com/en/reference/#tag/table-devices/GET/device): This device

The same as files: [openapi.json](https://developers.packeroo.com/openapi.json), [openapi.yaml](https://developers.packeroo.com/openapi.yaml), this page as [Markdown](https://developers.packeroo.com/en/reference.md). The interactive reference below is generated from [openapi.json](https://developers.packeroo.com/openapi.json), the contract packeroo generates from the code of the API. Each operation lets you pick the language of its code sample, and the sandbox comes first as the server. Send requests from your own program, not from this page; the [quickstart](https://developers.packeroo.com/en/quickstart/) shows how.

---

# Postman and OpenAPI

> The public packeroo API as OpenAPI 3.1 in JSON and YAML, the Postman collection with a sandbox environment, and the import into Insomnia, Bruno and Hoppscotch.

Every file is built at each release from the same contract as the reference. They hold only the public operations and stay at these addresses.

## OpenAPI

| File | Address |
| --- | --- |
| OpenAPI 3.1, JSON | [/openapi.json](https://developers.packeroo.com/openapi.json) |
| OpenAPI 3.1, YAML | [/openapi.yaml](https://developers.packeroo.com/openapi.yaml) |

There is no official SDK. For the operations of today an HTTP client is enough, as the [examples](https://developers.packeroo.com/en/guides/pair-a-table-device/#the-complete-program) show. If you want a typed client anyway, generate it from the OpenAPI file, for example with OpenAPI Generator (needs Java):

```bash
npx @openapitools/openapi-generator-cli generate -i https://developers.packeroo.com/openapi.yaml -g python -o packeroo-client
```

Instead of `python`, use `typescript-fetch`, `csharp`, `php`, `go` or `java` for your language. Generate the client again when an operation is added in the [changelog](https://developers.packeroo.com/en/changelog/).

## Postman

| File | Address |
| --- | --- |
| Collection | [packeroo.postman_collection.json](https://developers.packeroo.com/packeroo.postman_collection.json) |
| Sandbox environment | [packeroo-sandbox.postman_environment.json](https://developers.packeroo.com/packeroo-sandbox.postman_environment.json) |

To send the first request:

1. Download both files.
2. In Postman: **Import**, drop both files in.
3. Choose the environment **packeroo Sandbox** at the top right.
4. Under **Table devices**, open **Ask to pair this device** and send it. Postman makes a new `Idempotency-Key` for every send (`{{$guid}}`).
5. Paste the `token` from the answer into **token** of the environment. From then on every request of the collection sends it as a bearer token.

The environment keeps `token` as a secret, so Postman does not show it openly. Do not share the environment with a token in it.

## Insomnia, Bruno, Hoppscotch

These tools read the OpenAPI file directly:

- **Insomnia:** Import, then "From URL" with `https://developers.packeroo.com/openapi.json`, or the downloaded file.
- **Bruno:** Import Collection, then "OpenAPI V3 Spec" and choose the file.
- **Hoppscotch:** Import, then "OpenAPI" and the file or address.

The base address of the sandbox is `https://api.qm.packeroo.com/api/v1`. Set `User-Agent` to the name of your device, or the API answers `400`.

---

# Changelog

> What changes in the public packeroo API, with dates. Also as an RSS feed.

New operations, new fields and everything you need to change in your program. Subscribe to the feed at [/en/changelog/feed.xml](https://developers.packeroo.com/en/changelog/feed.xml).

## 22 November 2026: Developer site and pairing table devices

developers.packeroo.com is online, in German and English. The first three operations are public: `POST /device-pairings` asks for a code for a table device, `GET /device` tells the paired device its table, location and organization, and in the sandbox a device pairs itself at a test table of its own with `POST /sandbox/device-pairings/confirm`. With them come the [guide](https://developers.packeroo.com/en/guides/pair-a-table-device/) with the complete program in eight languages, the [reference](https://developers.packeroo.com/en/reference/), the Postman collection and the contract as OpenAPI 3.1.

---

# For AI assistants

> llms.txt, llms-full.txt, every page as Markdown and the OpenAPI contract at fixed addresses, so assistants and coding agents explain the packeroo API correctly.

When you code with an AI assistant or a coding agent, give it these addresses. They do not change and hold only what exists; planned parts are marked as planned.

| What | Address |
| --- | --- |
| Overview with links | [/llms.txt](https://developers.packeroo.com/llms.txt) |
| Every page in one file, with OpenAPI | [/llms-full.txt](https://developers.packeroo.com/llms-full.txt) |
| The contract | [/openapi.json](https://developers.packeroo.com/openapi.json), [/openapi.yaml](https://developers.packeroo.com/openapi.yaml) |
| Every page as Markdown | the address of the page with `.md`, such as [/en/quickstart.md](https://developers.packeroo.com/en/quickstart.md) |

## How to ask

Tell the assistant what you are building and in which language, and attach the OpenAPI file or `llms-full.txt`. For example:

```text
Read https://developers.packeroo.com/llms-full.txt.
Write me a Rust program for a Raspberry Pi that pairs itself with packeroo as a table device:
ask for a code, keep the token in a file with mode 600, ask GET /device every 5 seconds.
Handle every error code from the docs.
```

Check what the assistant writes against the [reference](https://developers.packeroo.com/en/reference/). Operations that are not listed there do not exist.

---

# Security and privacy

> What a table device sends to packeroo, what packeroo keeps of it and for how long, how tokens are protected, and how to report a vulnerability. For developers, IT and data protection.

This page describes what the public API does today. It adds to the [privacy policy of packeroo](https://packeroo.com/en/privacy/); it does not replace it.

## What a device sees

A paired device reads with `GET /device` only what it is paired with: its name, the table, the location with its time zone, the organization and its scopes. It sees no people, no matches and no ratings. Further operations come only once they are in the [changelog](https://developers.packeroo.com/en/changelog/).

## What packeroo keeps about a device

| What | From | How long |
| --- | --- | --- |
| Hash of the token (SHA-256) and its first characters | `POST /device-pairings` | while the device is paired, then 30 days |
| `model`, `serial`, `firmware`, if the device sends them | `POST /device-pairings` | as above |
| Name of the device | whoever enters the code in the app | as above |
| Time of the last request | every request with the token | as above |
| Who paired or unpaired the device, with the first characters of the token | the app, packeroo itself | in the audit log of the organization, 24 months |
| A code not entered yet | `POST /device-pairings` | valid for ten minutes, deleted by the next day at the latest |

In the sandbox packeroo names the device itself, and the audit log keeps a month there.

packeroo does not keep the token itself. It is in the answer to `POST /device-pairings` exactly once. If it is lost, the device asks for a new code.

The IP address of a request counts for the rate limit of `POST /device-pairings` and expires with it after a minute, for `POST /sandbox/device-pairings/confirm` after an hour, and as a hash for the test tables of a day after a day. An answer a device got with an `Idempotency-Key` is kept for 48 hours for a retry; an answer with a token never.

## When a device is unpaired

- Whoever looks after the location unpairs it in the app. The token stops working at once.
- Another device is paired at its table, or the table is archived.
- In the sandbox: when a new test table comes and there are 100 already, the oldest is unpaired with its device.
- The device does not report for 90 days. Nobody is surprised by it: when a device has not reported for 24 hours, everyone who looks after the location gets a notification, and the app shows at the device on which day it is unpaired if it stays silent.

When the organization switches table devices off, no device is unpaired: while they are off, every token gets `401`, and afterwards it signs in again. The 90 days do not run in that time.

## Protecting tokens

- Keep the token on the device only, in a file only the program may read. The [examples](https://developers.packeroo.com/en/guides/pair-a-table-device/) create it with the rights `0600`.
- Send it only over HTTPS to the addresses in the [concepts](https://developers.packeroo.com/en/concepts/#addresses). The examples check the certificate, the ESP32 sketch too.
- A token does not belong in a web page, a repository or a log. Its checksum at the end lets secret scanners recognize a leaked token.
- If a token got into the wrong hands, unpair the device in the app and pair it again.

## Reporting a vulnerability

Write to [info@packeroo.com](mailto:info@packeroo.com) with the subject "Security". Describe what you found and how to reproduce it, and give the `correlation_id` of an answer if you have one. Test only in the sandbox and only with your own devices.

---

# Glossary

> The terms of the packeroo API in short, from organization and location to table and table device, token, scope, sandbox and Idempotency-Key.

## Organization, location, table

- **Organization:** A company, club or pub at packeroo. It owns locations, leagues and devices. `GET /device` names it in `organization`.
- **Location:** A place of the organization with an address and a time zone, such as an office or a hall. Whoever looks after it pairs devices there. In the contract `location`.
- **Table:** A table football table, a darts board or another place to play at a location. In the contract `table`.
- **Table device:** A device that belongs to exactly one table and signs in with a device token, such as a Raspberry Pi with a display or a table with goal detection. A table has at most one device.

## Pairing

- **Code:** Six characters a device shows after `POST /device-pairings`, valid for ten minutes. Whoever looks after the location enters it in the app.
- **Pair, unpair:** Pairing makes a device the device of a table; unpairing takes its token away. See [Pair a table device](https://developers.packeroo.com/en/guides/pair-a-table-device/).
- **Switching table devices off:** An organization can switch all its devices off at once. While they are off, none pairs, and every token gets `401`.

## Signing in

- **Token:** The secret string a device signs in with, as `Authorization: Bearer …`. Device tokens start with `pkd_live_`, or `pkd_test_` in the sandbox. See [Concepts](https://developers.packeroo.com/en/concepts/#authentication-and-token-prefixes).
- **Scope:** A right of a token, such as `matches:write`. `GET /device` names them in `scopes`.
- **Organization key:** Planned. A token for the servers of an organization, such as an intranet or dashboards, with the prefix `pko_`.

## Requests

- **Idempotency-Key:** A UUID or ULID in the header of that name on every writing request. The same request with the same key takes effect once.
- **Problem:** An error answer after RFC 9457 with a fixed `code`. See [Error answers](https://developers.packeroo.com/en/concepts/#error-answers).
- **correlation_id:** The id of a request, in every error answer and in the header `X-Correlation-Id`. Give it when you write to us.
- **Sandbox:** The demo environment at `https://api.qm.packeroo.com/api/v1` with `pkd_test_` tokens, for trying things out. It can be reset.

---

# Bau deinen Kickertisch an packeroo an

> Die öffentliche API von packeroo mit Anleitung, Referenz und lauffähigen Beispielen in Python, JavaScript, C#, PHP, Go, Java, curl und für den ESP32. Heute verbindest du ein Tischgerät mit einem Tisch.

## Was du heute bauen kannst

Ein Gerät am Tisch fragt einen Code an und bekommt dazu sein Token. Es zeigt den Code, wer den Standort verwaltet, gibt ihn in der packeroo-App ein, und ab dann meldet sich das Gerät mit seinem Token an. Es liest, mit welchem Tisch, Standort und welcher Organisation es verbunden ist. Dafür gibt es zwei Operationen: `POST /device-pairings` und `GET /device`. In der Sandbox kommt eine dritte dazu, mit der ein Gerät seinen Code selbst bestätigt: `POST /sandbox/device-pairings/confirm`.

Die [Anleitung](https://developers.packeroo.com/anleitung/tischgeraet-verbinden/) zeigt das ganze Programm in acht Sprachen, vom Anfordern des Codes bis zur ersten Antwort mit 200.

## Was geplant ist

Diese Teile sind beschlossen, aber noch nicht gebaut. Sie stehen hier, damit du weißt, wohin die API geht:

- die Warteschlange eines Tischs lesen: welches Spiel läuft, wer als Nächstes spielt
- ein Spiel am Tisch starten, Tore live melden und das Ergebnis vom Tisch melden
- Spielerinnen und Spieler per Chip erkennen
- Organisationsschlüssel für Intranet, Dashboards und Chat-Bots
- Webhooks

Ein Datum nennen wir, sobald es feststeht. Brauchst du einen Organisationsschlüssel, [trag dich ein](mailto:info@packeroo.com?subject=Organisationsschl%C3%BCssel), dann schreiben wir dir, sobald es ihn gibt. Jede neue Operation steht im [Changelog](https://developers.packeroo.com/changelog/), an dem Tag, an dem sie öffentlich wird.

## In drei Schritten

1. **Code anfordern.** Dein Gerät schickt `POST /device-pairings` und bekommt einen Code aus sechs Zeichen, der zehn Minuten gilt, und sein Token.
2. **Code zeigen.** Das Gerät zeigt den Code als zwei Dreiergruppen und als QR-Code. Wer den Standort verwaltet, scannt ihn mit dem Handy oder tippt ihn in der App ein: unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder über `app.packeroo.com/verbinden`.
3. **Anmelden.** Das Gerät fragt alle fünf Sekunden `GET /device`. Solange der Code nicht eingegeben ist, kommt 401. Danach kommt 200 mit Tisch, Standort und Organisation.

## Alles für die Integration

- [Schnellstart](https://developers.packeroo.com/schnellstart/)
  Vom Code bis zum verbundenen Gerät, in acht Sprachen.
- [Ein Tischgerät verbinden](https://developers.packeroo.com/anleitung/tischgeraet-verbinden/)
  Die Anleitung mit dem vollständigen Programm, den Fehlerfällen und den Regeln für die Anzeige am Tisch.
- [Konzepte](https://developers.packeroo.com/konzepte/)
  Token, Idempotency-Key, Fehlerantworten, Ratenlimits, User-Agent, Zeiten und Versionen.
- [Referenz](https://developers.packeroo.com/referenz/)
  Jede öffentliche Operation mit Schema, Fehlern und Codebeispielen in vielen Sprachen.
- [Postman und OpenAPI](https://developers.packeroo.com/downloads/)
  Die Collection mit Sandbox-Umgebung und der Vertrag als JSON und YAML.
- [Für KI-Assistenten](https://developers.packeroo.com/ki/)
  `llms.txt`, jede Seite als Markdown und die OpenAPI-Datei an festen Adressen.

## Sandbox und Kontakt

Zum Ausprobieren gibt es die Sandbox unter `https://api.qm.packeroo.com/api/v1`, Tokens dort beginnen mit `pkd_test_`. Dort verbindet sich dein Gerät selbst, mit einem eigenen Testtisch und ohne Anmeldung bei uns: Der [Schnellstart](https://developers.packeroo.com/schnellstart/) zeigt wie. Fragen beantworten wir unter [info@packeroo.com](mailto:info@packeroo.com).

---

# In fünf Minuten zum ersten Aufruf

> Fordere in der Sandbox einen Code für ein Tischgerät an und lies mit dem Token GET /device. Mit Python, JavaScript, C#, PHP, Go, Java, curl und für den ESP32.

Du brauchst ein Terminal, für den ESP32 die Arduino-IDE. Ein Konto bei packeroo brauchst du in der Sandbox nicht: Ein Gerät fordert seinen Code ohne Anmeldung an und bestätigt ihn dort selbst. Die Sprache, die du hier wählst, gilt für alle Beispiele auf dieser Seite, in der Anleitung und in der Referenz. PowerShell, Ruby, Kotlin, Swift, Dart und Rust findest du in der [Referenz](https://developers.packeroo.com/referenz/).

## 1. Code anfordern

Schick `POST /device-pairings` an die Sandbox. Zwei Header sind Pflicht: `User-Agent` nennt dein Gerät mit Produkt und Firmware, `Idempotency-Key` ist eine UUID oder ULID, die du für diese Anfrage neu erzeugst.

Python:

```python
import json, urllib.request, uuid

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/device-pairings",
    method="POST",
    data=json.dumps({"model": "Kickertisch-Beispiel", "firmware": "1.0"}).encode(),
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Idempotency-Key": str(uuid.uuid4()),
        "Content-Type": "application/json",
        "Accept-Language": "de",
    },
)
with urllib.request.urlopen(request) as response:
    print(json.load(response)["data"])
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/device-pairings', {
  method: 'POST',
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    'Idempotency-Key': crypto.randomUUID(),
    'Content-Type': 'application/json',
    'Accept-Language': 'de',
  },
  body: JSON.stringify({ model: 'Kickertisch-Beispiel', firmware: '1.0' }),
})
console.log(response.status, (await response.json()).data)
```

C#:

```csharp
using System.Net.Http.Json;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.qm.packeroo.com/api/v1/device-pairings")
{
    Content = JsonContent.Create(new { model = "Kickertisch-Beispiel", firmware = "1.0" }),
};
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
request.Headers.AcceptLanguage.ParseAdd("de");
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$bytes = random_bytes(16);
$bytes[6] = chr(ord($bytes[6]) & 0x0f | 0x40);
$bytes[8] = chr(ord($bytes[8]) & 0x3f | 0x80);
$key = vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($bytes), 4));

$curl = curl_init('https://api.qm.packeroo.com/api/v1/device-pairings');
curl_setopt_array($curl, [
    CURLOPT_POST => true,
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => ["Idempotency-Key: $key", 'Content-Type: application/json', 'Accept-Language: de'],
    CURLOPT_POSTFIELDS => json_encode(['model' => 'Kickertisch-Beispiel', 'firmware' => '1.0']),
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
package main

import (
	"bytes"
	"crypto/rand"
	"fmt"
	"io"
	"net/http"
)

func main() {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	b[6], b[8] = b[6]&0x0f|0x40, b[8]&0x3f|0x80
	key := fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])

	body := bytes.NewBufferString(`{"model": "Kickertisch-Beispiel", "firmware": "1.0"}`)
	request, _ := http.NewRequest("POST", "https://api.qm.packeroo.com/api/v1/device-pairings", body)
	request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
	request.Header.Set("Idempotency-Key", key)
	request.Header.Set("Content-Type", "application/json")
	request.Header.Set("Accept-Language", "de")
	response, err := http.DefaultClient.Do(request)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	data, _ := io.ReadAll(response.Body)
	fmt.Println(response.Status, string(data))
}
```

Java:

```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.UUID;

public class AskForCode {
    public static void main(String[] args) throws Exception {
        HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/device-pairings"))
            .header("User-Agent", "Kickertisch-Beispiel/1.0")
            .header("Idempotency-Key", UUID.randomUUID().toString())
            .header("Content-Type", "application/json")
            .header("Accept-Language", "de")
            .POST(HttpRequest.BodyPublishers.ofString("{\"model\": \"Kickertisch-Beispiel\", \"firmware\": \"1.0\"}"))
            .build();
        HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
        System.out.println(response.statusCode() + " " + response.body());
    }
}
```

curl:

```bash
# uuidgen gibt es auf macOS und vielen Linux-Systemen; sonst liefert der Kernel eine UUID.
KEY="$(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)"
curl -sS -X POST https://api.qm.packeroo.com/api/v1/device-pairings \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Idempotency-Key: $KEY" \
  -H "Content-Type: application/json" \
  -H "Accept-Language: de" \
  -d '{"model": "Kickertisch-Beispiel", "firmware": "1.0"}'
```

ESP32:

```cpp
// In setup(), nach WLAN, configTime() und tls.setCACert() wie im vollständigen Sketch der Anleitung.
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/device-pairings");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Idempotency-Key", newKey());  // newKey() aus dem vollständigen Sketch
http.addHeader("Content-Type", "application/json");
http.addHeader("Accept-Language", "de");
int status = http.POST("{\"model\":\"Kickertisch-ESP32\",\"firmware\":\"1.0\"}");
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

Die Antwort kommt mit `201 Created`:

```json
{
  "data": {
    "code": "K7F4QX",
    "expires_at": "2026-11-22T14:15:00Z",
    "token": "pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD"
  }
}
```

Das Token siehst du nur dieses eine Mal. Leg es im selben Terminal in eine Umgebungsvariable, die Beispiele der nächsten Schritte lesen es von dort:

```bash
export PACKEROO_TOKEN='pkd_test_…'   # hier dein Token aus der Antwort
# PowerShell: $env:PACKEROO_TOKEN = 'pkd_test_…'
```

Auf dem ESP32 hebt der Sketch es in der Variablen `token` auf.

## 2. Mit dem Token fragen

Frag mit dem Token `GET /device`. Solange niemand den Code eingegeben hat, antwortet die API mit `401` und dem Code `unauthenticated`: Das Token gilt erst, wenn der Code einem Tisch zugeordnet ist. Mit einem falschen Token, oder einem `pkd_test_`-Token gegen die Live-API, sieht die Antwort genauso aus. Ob dein Token stimmt, zeigt Schritt 3.

Python:

```python
import json, os, urllib.error, urllib.request

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/device",
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Authorization": "Bearer " + os.environ["PACKEROO_TOKEN"],
    },
)
try:
    with urllib.request.urlopen(request) as response:
        print(response.status, json.load(response)["data"])
except urllib.error.HTTPError as error:
    print(error.code, error.read().decode())
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/device', {
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    Authorization: `Bearer ${process.env.PACKEROO_TOKEN}`,
  },
})
console.log(response.status, await response.json())
```

C#:

```csharp
using System.Net.Http.Headers;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Get, "https://api.qm.packeroo.com/api/v1/device");
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
var token = Environment.GetEnvironmentVariable("PACKEROO_TOKEN");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$curl = curl_init('https://api.qm.packeroo.com/api/v1/device');
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => ['Authorization: Bearer ' . getenv('PACKEROO_TOKEN')],
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
request, _ := http.NewRequest("GET", "https://api.qm.packeroo.com/api/v1/device", nil)
request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
request.Header.Set("Authorization", "Bearer "+os.Getenv("PACKEROO_TOKEN"))
response, err := http.DefaultClient.Do(request)
if err != nil {
	panic(err)
}
defer response.Body.Close()
data, _ := io.ReadAll(response.Body)
fmt.Println(response.Status, string(data))
```

Java:

```java
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/device"))
    .header("User-Agent", "Kickertisch-Beispiel/1.0")
    .header("Authorization", "Bearer " + System.getenv("PACKEROO_TOKEN"))
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
```

curl:

```bash
curl -sS https://api.qm.packeroo.com/api/v1/device \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Authorization: Bearer $PACKEROO_TOKEN"
```

ESP32:

```cpp
// token: aus der Antwort auf Schritt 1, wie im vollständigen Sketch.
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/device");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Authorization", "Bearer " + token);
int status = http.GET();
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

## 3. Code eingeben lassen

Live gibt jemand den Code in der App ein, unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“. In der Sandbox geht das ohne Menschen: Dein Gerät bestätigt seinen Code selbst mit `POST /sandbox/device-pairings/confirm` und demselben Token. Es bekommt dabei einen eigenen Testtisch. Kommt hier `401`, wartet für das Token kein Code: Es ist falsch, oder der Code ist nach 10 Minuten abgelaufen. Dann fang bei Schritt 1 wieder an.

Python:

```python
import json, os, urllib.error, urllib.request, uuid

request = urllib.request.Request(
    "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm",
    method="POST",
    headers={
        "User-Agent": "Kickertisch-Beispiel/1.0",
        "Idempotency-Key": str(uuid.uuid4()),
        "Authorization": "Bearer " + os.environ["PACKEROO_TOKEN"],
    },
)
try:
    with urllib.request.urlopen(request) as response:
        print(response.status, json.load(response)["data"])
except urllib.error.HTTPError as error:
    print(error.code, error.read().decode())
```

JavaScript:

```js
const response = await fetch('https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm', {
  method: 'POST',
  headers: {
    'User-Agent': 'Kickertisch-Beispiel/1.0',
    'Idempotency-Key': crypto.randomUUID(),
    Authorization: `Bearer ${process.env.PACKEROO_TOKEN}`,
  },
})
console.log(response.status, await response.json())
```

C#:

```csharp
using System.Net.Http.Headers;

using var http = new HttpClient();
var request = new HttpRequestMessage(HttpMethod.Post, "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm");
request.Headers.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
request.Headers.Add("Idempotency-Key", Guid.NewGuid().ToString());
var token = Environment.GetEnvironmentVariable("PACKEROO_TOKEN");
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var response = await http.SendAsync(request);
Console.WriteLine($"{(int)response.StatusCode} {await response.Content.ReadAsStringAsync()}");
```

PHP:

```php
<?php
$curl = curl_init('https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm');
curl_setopt_array($curl, [
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_POST => true,
    CURLOPT_USERAGENT => 'Kickertisch-Beispiel/1.0',
    CURLOPT_HTTPHEADER => [
        'Idempotency-Key: ' . bin2hex(random_bytes(16)),
        'Authorization: Bearer ' . getenv('PACKEROO_TOKEN'),
    ],
]);
$body = curl_exec($curl);
echo curl_getinfo($curl, CURLINFO_RESPONSE_CODE), ' ', $body, "\n";
```

Go:

```go
request, _ := http.NewRequest("POST", "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm", nil)
request.Header.Set("User-Agent", "Kickertisch-Beispiel/1.0")
request.Header.Set("Idempotency-Key", key) // key: eine neue UUID, erzeugt wie in Schritt 1
request.Header.Set("Authorization", "Bearer "+os.Getenv("PACKEROO_TOKEN"))
response, err := http.DefaultClient.Do(request)
if err != nil {
	panic(err)
}
defer response.Body.Close()
data, _ := io.ReadAll(response.Body)
fmt.Println(response.Status, string(data))
```

Java:

```java
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm"))
    .header("User-Agent", "Kickertisch-Beispiel/1.0")
    .header("Idempotency-Key", UUID.randomUUID().toString())
    .header("Authorization", "Bearer " + System.getenv("PACKEROO_TOKEN"))
    .POST(HttpRequest.BodyPublishers.noBody())
    .build();
HttpResponse<String> response = HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.statusCode() + " " + response.body());
```

curl:

```bash
curl -sS -X POST https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm \
  -H "User-Agent: Kickertisch-Beispiel/1.0" \
  -H "Idempotency-Key: $(uuidgen 2>/dev/null || cat /proc/sys/kernel/random/uuid)" \
  -H "Authorization: Bearer $PACKEROO_TOKEN"
```

ESP32:

```cpp
HTTPClient http;
http.begin(tls, "https://api.qm.packeroo.com/api/v1/sandbox/device-pairings/confirm");
http.setUserAgent("Kickertisch-ESP32/1.0");
http.addHeader("Idempotency-Key", newKey());
http.addHeader("Authorization", "Bearer " + token);
int status = http.POST("");
Serial.printf("%d %s\n", status, http.getString().c_str());
http.end();
```

Die Antwort ist schon das Gerät, wie es `GET /device` zeigt. Diese Operation gibt es nur in der Sandbox; live antwortet sie mit `404`, nachdem `User-Agent` und `Idempotency-Key` geprüft sind. Die Sandbox hält die neuesten 100 Testtische, der älteste wird mit seinem Gerät getrennt, wenn ein neuer dazukommt.

Damit ist dein Gerät verbunden. `GET /device` aus Schritt 2 antwortet ab jetzt mit `200`:

```json
{
  "data": {
    "id": "01JD7Q3V9TQ6Z8K2M4N5P6R7S8",
    "name": "Kickertisch Halle",
    "table": { "id": "01JD7Q2B1C3D4E5F6G7H8J9K0M", "name": "Tisch 2" },
    "location": { "id": "01JD7Q1A2B3C4D5E6F7G8H9J0K", "name": "Büro Freiburg", "time_zone": "Europe/Berlin" },
    "organization": { "id": "01JD7Q0Z9Y8X7W6V5T4S3R2Q1P", "name": "Beispiel AG" },
    "scopes": ["leagues:read", "standings:read", "matches:read", "matches:write", "matches:live"]
  }
}
```

Die Werte oben sind ein Beispiel. `scopes` nennt, was das Token später darf; die Operationen dafür sind [geplant](https://developers.packeroo.com/konzepte/#scopes).

## Weiter

- Die [Anleitung](https://developers.packeroo.com/anleitung/tischgeraet-verbinden/) zeigt das vollständige Programm mit Warten, Ablauf des Codes und allen Fehlerfällen.
- [Postman](https://developers.packeroo.com/downloads/#postman): Collection importieren, Umgebung „packeroo Sandbox“ wählen, Token einsetzen.
- In der [Referenz](https://developers.packeroo.com/referenz/) findest du jede Operation mit Codebeispielen in vielen weiteren Sprachen.

---

# Ein Tischgerät verbinden

> Code anfordern, Code und QR-Code zeigen, das Token sicher ablegen und auf die Verbindung warten. Mit vollständigem Programm in Python, JavaScript, C#, PHP, Go, Java, curl und für den ESP32.

Ein Tischgerät ist alles, was an einem Tisch steht und mit packeroo spricht: ein Kicker mit Torerkennung, ein Display, ein Raspberry Pi unter der Platte. Bevor es etwas melden darf, verbindet es sich einmal mit genau einem Tisch eines Standorts. Diese Anleitung führt dich durch die Verbindung, vom ersten Aufruf bis zur Antwort `200`.

## Der Ablauf

1. Das Gerät fordert mit `POST /device-pairings` einen Code an und bekommt dazu sein Token.
2. Es legt das Token in einer Datei ab, die nur sein eigener Benutzer lesen kann.
3. Es zeigt den Code als zwei Dreiergruppen und als QR-Code.
4. Wer den Standort verwaltet, gibt den Code in der packeroo-App ein, unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“ oder über `app.packeroo.com/verbinden`, oder scannt den QR-Code mit dem Handy; der öffnet denselben Link mit dem Code schon ausgefüllt.
5. Das Gerät fragt alle fünf Sekunden `GET /device`. Bis der Code eingegeben ist, kommt `401`, danach `200` mit Tisch, Standort und Organisation.

Läuft der Code nach zehn Minuten ab, fordert das Gerät einen neuen an und schickt dabei sein bisheriges Token mit.

## Das vollständige Programm

Das Programm macht alles aus dieser Anleitung: Es liest ein gespeichertes Token, fordert sonst einen Code an, zeigt ihn, legt das Token ab, wartet auf die Verbindung und behandelt die Fehler. Die Basisadresse kommt aus der Umgebungsvariablen `PACKEROO_BASE_URL`, ohne sie nimmt das Programm die Sandbox. `PACKEROO_TOKEN_FILE` legt fest, wo das Token liegt, Standard ist `~/.config/packeroo/device-token`.

#### Python (python/pair_device.py)

```python
"""Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
someone enters the code in the app. Python 3.9 or newer, standard library only; with the
package qrcode installed (pip install qrcode) it also prints the QR code in the terminal.

    python3 pair_device.py

PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
"""

import email.utils
import json
import os
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
import uuid
from datetime import datetime, timezone
from pathlib import Path

# What the device shows, in the language of the location.
TEXT = {
    "code": "Code am Tisch: {code}  (gilt bis {until} Uhr)",
    "link": "QR-Code mit diesem Link: {link}",
    "enter": "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.",
    "qr_hint": "Für einen QR-Code im Terminal: pip install qrcode",
    "expired": "Der Code ist abgelaufen. Ich hole einen neuen.",
    "unpaired": "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.",
    "off": "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.",
    "offline": "Keine Verbindung ({error}), neuer Versuch in {seconds:g} s",
    "paired": "Verbunden mit {table} ({location})",
    "no_location": "ohne Standort",
    "error": "Fehler {status} {code}: {detail}",
    "unexpected": "unerwartete Antwort",
}

BASE_URL = os.environ.get("PACKEROO_BASE_URL", "https://api.qm.packeroo.com/api/v1").rstrip("/")
TOKEN_FILE = Path(os.environ.get("PACKEROO_TOKEN_FILE", Path.home() / ".config" / "packeroo" / "device-token"))
POLL_SECONDS = float(os.environ.get("PACKEROO_POLL_SECONDS", "5"))
# After errors in a row the pause doubles, up to this many seconds.
MAX_PAUSE_SECONDS = 60
# Every request names the device: product and firmware.
USER_AGENT = "Kickertisch-Beispiel/1.0"

def call(method, path, token=None, body=None, idempotency_key=None):
    """One request to the API. Returns (status, json, headers); network errors are retried."""
    headers = {"User-Agent": USER_AGENT, "Accept": "application/json", "Accept-Language": "de"}
    if token:
        headers["Authorization"] = f"Bearer {token}"
    data = None
    if body is not None:
        headers["Content-Type"] = "application/json"
        data = json.dumps(body).encode()
    # A write carries an Idempotency-Key; a retry of the same request sends the same key.
    if idempotency_key:
        headers["Idempotency-Key"] = idempotency_key

    failures = 0
    while True:
        request = urllib.request.Request(BASE_URL + path, data=data, headers=headers, method=method)
        try:
            with urllib.request.urlopen(request, timeout=30) as response:
                return response.status, read_json(response), response.headers
        except urllib.error.HTTPError as error:
            return error.code, read_json(error), error.headers
        except (urllib.error.URLError, TimeoutError, ConnectionError) as error:
            failures += 1
            pause_after_error(failures, error)

def read_json(response):
    """The body as JSON; {} when there is none or it is no JSON, such as the error page of a proxy."""
    try:
        return json.loads(response.read().decode() or "{}")
    except ValueError:
        return {}

def pause_after_error(failures, reason):
    """Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
    error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause."""
    seconds = min(POLL_SECONDS * 2 ** (failures - 1), MAX_PAUSE_SECONDS)
    print(TEXT["offline"].format(error=reason, seconds=seconds), file=sys.stderr)
    time.sleep(seconds)

def retry_after(headers):
    """Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date."""
    value = headers.get("Retry-After", "60")
    if value.isdigit():
        return max(1, int(value))
    try:
        return max(1, (email.utils.parsedate_to_datetime(value) - datetime.now(timezone.utc)).total_seconds())
    except (TypeError, ValueError):
        return 60

def read_token():
    try:
        return TOKEN_FILE.read_text().strip() or None
    except FileNotFoundError:
        return None

def save_token(token):
    """Keeps the token in a file only this user can read, written in one step."""
    TOKEN_FILE.parent.mkdir(parents=True, exist_ok=True, mode=0o700)
    temporary = TOKEN_FILE.with_name(TOKEN_FILE.name + ".tmp")
    # A leftover from a crash may have other rights: remove it, then create the file anew.
    temporary.unlink(missing_ok=True)
    descriptor = os.open(temporary, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
    with os.fdopen(descriptor, "w") as file:
        file.write(token + "\n")
    os.chmod(temporary, 0o600)
    os.replace(temporary, TOKEN_FILE)

def pair_link(code):
    """The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com."""
    host = urllib.parse.urlsplit(BASE_URL).netloc
    if host.startswith("api."):
        host = "app." + host[4:]
    return f"https://{host}/verbinden?code={code}"

def show_code(code, expires_at):
    until = datetime.fromisoformat(expires_at.replace("Z", "+00:00")).astimezone().strftime("%H:%M")
    link = pair_link(code)
    print("\n" + TEXT["code"].format(code=f"{code[:3]} {code[3:]}", until=until))
    try:
        import qrcode

        qr = qrcode.QRCode(border=2)
        qr.add_data(link)
        qr.print_ascii(invert=True)
    except ImportError:
        print(TEXT["qr_hint"])
    print(TEXT["link"].format(link=link))
    print(TEXT["enter"] + "\n", flush=True)

def fail(status, problem):
    print(TEXT["error"].format(status=status, code=problem.get("code", ""), detail=problem.get("detail", TEXT["unexpected"])), file=sys.stderr)
    sys.exit(1)

def request_code(token):
    """Asks for a code. Returns (token, expires_at), with expires_at None when the token is paired already."""
    idempotency_key = str(uuid.uuid4())
    failures = 0
    while True:
        status, answer, headers = call(
            "POST", "/device-pairings", token=token, idempotency_key=idempotency_key,
            body={"model": "Kickertisch-Beispiel", "firmware": "1.0"},
        )
        if status == 201:
            data = answer["data"]
            # Shown only this once: keep it before anything else.
            save_token(data["token"])
            show_code(data["code"], data["expires_at"])
            expires = datetime.fromisoformat(data["expires_at"].replace("Z", "+00:00")).timestamp()
            return data["token"], expires
        code = answer.get("code")
        if status == 409 and code == "device_already_paired":
            return token, None
        if status == 409 and code == "table_devices_off":
            print(TEXT["off"], flush=True)
            time.sleep(60)
        elif status == 429:
            time.sleep(retry_after(headers))
        elif status >= 500:
            # The API is busy or being deployed: the same request with the same key, after a pause.
            failures += 1
            pause_after_error(failures, f"HTTP {status}")
        else:
            fail(status, answer)

def wait_for_pairing(token, expires_at):
    """GET /device until it answers 200. None once the code has run out, or at once when no code
    is waiting (expires_at None) and the token does not sign in: the device was unpaired.
    Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error."""
    failures = 0
    while True:
        status, answer, headers = call("GET", "/device", token=token)
        if status == 200:
            return answer["data"]
        if status == 429:
            time.sleep(retry_after(headers))
            continue
        if 400 <= status < 500 and status != 401:
            # A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
            fail(status, answer)
        if status != 401:
            # Someone may be typing the code right now: keep it, ask again after a pause.
            failures += 1
            pause_after_error(failures, f"HTTP {status}")
            continue
        failures = 0
        if expires_at is None or time.time() >= expires_at:
            return None
        time.sleep(POLL_SECONDS)

def main():
    token = read_token()
    # With a stored token, ask first whether it still signs in; None after a 401.
    device = wait_for_pairing(token, None) if token else None

    while device is None:
        token, expires_at = request_code(token)
        device = wait_for_pairing(token, expires_at)
        if device is None and expires_at is None:
            # Paired a moment ago, unpaired now: this token is of no use any more.
            print(TEXT["unpaired"], flush=True)
            token = None
        elif device is None:
            print(TEXT["expired"], flush=True)

    location = device["location"]["name"] or TEXT["no_location"]
    print(TEXT["paired"].format(table=device["table"]["name"], location=location))

if __name__ == "__main__":
    main()
```

#### JavaScript (javascript/pair-device.mjs)

```js
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. Node.js 20 or newer, no packages. Runs in Node.js, not in a
// browser: a browser does not let a page set the User-Agent.
//
//   node pair-device.mjs
//
// PACKEROO_BASE_URL    API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE  where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5

import { randomUUID } from 'node:crypto'
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises'
import { homedir } from 'node:os'
import { dirname, join } from 'node:path'

// What the device shows, in the language of the location.
const TEXT = {
  code: (code, until) => `Code am Tisch: ${code}  (gilt bis ${until} Uhr)`,
  link: (link) => `QR-Code mit diesem Link: ${link}`,
  enter: 'Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.',
  expired: 'Der Code ist abgelaufen. Ich hole einen neuen.',
  unpaired: 'Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.',
  off: 'Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.',
  offline: (error, seconds) => `Keine Verbindung (${error}), neuer Versuch in ${seconds} s`,
  paired: (table, location) => `Verbunden mit ${table} (${location ?? 'ohne Standort'})`,
  error: (status, code, detail) => `Fehler ${status} ${code ?? ''}: ${detail ?? 'unerwartete Antwort'}`,
}

const BASE_URL = (process.env.PACKEROO_BASE_URL ?? 'https://api.qm.packeroo.com/api/v1').replace(/\/+$/, '')
const TOKEN_FILE = process.env.PACKEROO_TOKEN_FILE ?? join(homedir(), '.config', 'packeroo', 'device-token')
const POLL_SECONDS = Number(process.env.PACKEROO_POLL_SECONDS ?? 5)
// After errors in a row the pause doubles, up to this many seconds.
const MAX_PAUSE_SECONDS = 60
// Every request names the device: product and firmware.
const USER_AGENT = 'Kickertisch-Beispiel/1.0'

const sleep = (seconds) => new Promise((resolve) => setTimeout(resolve, seconds * 1000))

/** One request to the API. Returns status, the JSON body and the headers; network errors are retried. */
async function call(method, path, { token, body, idempotencyKey } = {}) {
  const headers = { 'User-Agent': USER_AGENT, Accept: 'application/json', 'Accept-Language': 'de' }
  if (token) headers.Authorization = `Bearer ${token}`
  if (body !== undefined) headers['Content-Type'] = 'application/json'
  // A write carries an Idempotency-Key; a retry of the same request sends the same key.
  if (idempotencyKey) headers['Idempotency-Key'] = idempotencyKey

  for (let failures = 1; ; failures++) {
    try {
      // A connection that stalls ends after 30 s, as in the other examples, and is retried.
      const response = await fetch(BASE_URL + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: AbortSignal.timeout(30_000) })
      return { status: response.status, json: parseJson(await response.text()), headers: response.headers }
    } catch (error) {
      await pauseAfterError(failures, error.cause?.code ?? error.message)
    }
  }
}

/** The body as JSON; null when there is none or it is no JSON, such as the error page of a proxy. */
function parseJson(text) {
  try {
    return text ? JSON.parse(text) : null
  } catch {
    return null
  }
}

/**
 * Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
 * error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
 */
async function pauseAfterError(failures, reason) {
  const seconds = Math.min(POLL_SECONDS * 2 ** (failures - 1), MAX_PAUSE_SECONDS)
  console.error(TEXT.offline(reason, seconds))
  await sleep(seconds)
}

/** Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date. */
function retryAfter(headers) {
  const value = headers.get('retry-after') ?? ''
  if (/^\d+$/.test(value)) return Math.max(1, Number(value))
  const date = Date.parse(value)
  return Number.isNaN(date) ? 60 : Math.max(1, (date - Date.now()) / 1000)
}

async function readToken() {
  try {
    return (await readFile(TOKEN_FILE, 'utf8')).trim() || undefined
  } catch {
    return undefined
  }
}

/** Keeps the token in a file only this user can read, written in one step. */
async function saveToken(token) {
  await mkdir(dirname(TOKEN_FILE), { recursive: true, mode: 0o700 })
  const temporary = `${TOKEN_FILE}.tmp`
  // A leftover from a crash may have other rights: remove it, then create the file anew.
  await rm(temporary, { force: true })
  await writeFile(temporary, `${token}\n`, { mode: 0o600, flag: 'wx' })
  await rename(temporary, TOKEN_FILE)
}

/** The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com. */
function pairLink(code) {
  const url = new URL(BASE_URL)
  const host = url.hostname.startsWith('api.') ? `app.${url.hostname.slice(4)}` : url.host
  return `https://${host}/verbinden?code=${code}`
}

function showCode(code, expiresAt) {
  const until = new Date(expiresAt).toLocaleTimeString('de-DE', { hour: '2-digit', minute: '2-digit' })
  console.log(`\n${TEXT.code(`${code.slice(0, 3)} ${code.slice(3)}`, until)}`)
  // For a QR code on a display, a package such as qrcode (npm) draws pairLink(code).
  console.log(TEXT.link(pairLink(code)))
  console.log(`${TEXT.enter}\n`)
}

function fail(result) {
  const problem = result.json ?? {}
  console.error(TEXT.error(result.status, problem.code, problem.detail))
  process.exit(1)
}

/** Asks for a code. Returns { token, expiresAt }; expiresAt is undefined when the token is paired already. */
async function requestCode(token) {
  const idempotencyKey = randomUUID()
  let failures = 0
  for (;;) {
    const result = await call('POST', '/device-pairings', { token, idempotencyKey, body: { model: 'Kickertisch-Beispiel', firmware: '1.0' } })
    if (result.status === 201) {
      const { code, expires_at: expiresAt, token: newToken } = result.json.data
      // Shown only this once: keep it before anything else.
      await saveToken(newToken)
      showCode(code, expiresAt)
      return { token: newToken, expiresAt: Date.parse(expiresAt) }
    }
    const code = result.json?.code
    if (result.status === 409 && code === 'device_already_paired') return { token, expiresAt: undefined }
    if (result.status === 409 && code === 'table_devices_off') {
      console.log(TEXT.off)
      await sleep(60)
    } else if (result.status === 429) {
      await sleep(retryAfter(result.headers))
    } else if (result.status >= 500) {
      // The API is busy or being deployed: the same request with the same key, after a pause.
      await pauseAfterError(++failures, `HTTP ${result.status}`)
    } else {
      fail(result)
    }
  }
}

/**
 * GET /device until it answers 200. Undefined once the code has run out, or at once when no code
 * is waiting (expiresAt undefined) and the token does not sign in: the device was unpaired.
 * Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
 */
async function waitForPairing(token, expiresAt) {
  let failures = 0
  for (;;) {
    const result = await call('GET', '/device', { token })
    if (result.status === 200) return result.json.data
    if (result.status === 429) {
      await sleep(retryAfter(result.headers))
      continue
    }
    // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
    if (result.status >= 400 && result.status < 500 && result.status !== 401) fail(result)
    if (result.status !== 401) {
      // Someone may be typing the code right now: keep it, ask again after a pause.
      await pauseAfterError(++failures, `HTTP ${result.status}`)
      continue
    }
    failures = 0
    if (expiresAt === undefined || Date.now() >= expiresAt) return undefined
    await sleep(POLL_SECONDS)
  }
}

let token = await readToken()
// With a stored token, ask first whether it still signs in; undefined after a 401.
let device = token ? await waitForPairing(token, undefined) : undefined

while (!device) {
  const pairing = await requestCode(token)
  token = pairing.token
  device = await waitForPairing(token, pairing.expiresAt)
  if (!device && pairing.expiresAt === undefined) {
    // Paired a moment ago, unpaired now: this token is of no use any more.
    console.log(TEXT.unpaired)
    token = undefined
  } else if (!device) {
    console.log(TEXT.expired)
  }
}

console.log(TEXT.paired(device.table.name, device.location.name))
```

#### C# (csharp/Program.cs)

```csharp
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. .NET 8 or newer, no packages.
//
//   dotnet run
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5

using System.Globalization;
using System.Net;
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;

// What the device shows, in the language of the location.
var TEXT = new
{
    Code = "Code am Tisch: {0}  (gilt bis {1:HH:mm} Uhr)",
    Link = "QR-Code mit diesem Link: {0}",
    Enter = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.",
    Expired = "Der Code ist abgelaufen. Ich hole einen neuen.",
    Unpaired = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.",
    Off = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.",
    Offline = "Keine Verbindung ({0}), neuer Versuch in {1} s",
    Paired = "Verbunden mit {0} ({1})",
    NoLocation = "ohne Standort",
    Error = "Fehler {0} {1}: {2}",
    Unexpected = "unerwartete Antwort",
};

var baseUrl = (Environment.GetEnvironmentVariable("PACKEROO_BASE_URL") ?? "https://api.qm.packeroo.com/api/v1").TrimEnd('/');
var tokenFile = Environment.GetEnvironmentVariable("PACKEROO_TOKEN_FILE")
    ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), ".config", "packeroo", "device-token");
var pollSeconds = double.Parse(Environment.GetEnvironmentVariable("PACKEROO_POLL_SECONDS") ?? "5", CultureInfo.InvariantCulture);
// After errors in a row the pause doubles, up to this many seconds.
const double MaxPauseSeconds = 60;

using var http = new HttpClient { Timeout = TimeSpan.FromSeconds(30) };
// Every request names the device: product and firmware.
http.DefaultRequestHeaders.UserAgent.ParseAdd("Kickertisch-Beispiel/1.0");
http.DefaultRequestHeaders.Accept.ParseAdd("application/json");
http.DefaultRequestHeaders.AcceptLanguage.ParseAdd("de");

var token = File.Exists(tokenFile) ? File.ReadAllText(tokenFile).Trim() : null;
if (string.IsNullOrEmpty(token)) token = null;
// With a stored token, ask first whether it still signs in; null after a 401.
var device = token is null ? null : await WaitForPairing(token, null);

while (device is null)
{
    var (newToken, expiresAt) = await RequestCode(token);
    token = newToken;
    device = await WaitForPairing(token, expiresAt);
    if (device is null && expiresAt is null)
    {
        // Paired a moment ago, unpaired now: this token is of no use any more.
        Console.WriteLine(TEXT.Unpaired);
        token = null;
    }
    else if (device is null) Console.WriteLine(TEXT.Expired);
}

var d = device.Value;
Console.WriteLine(TEXT.Paired, d.GetProperty("table").GetProperty("name").GetString(), d.GetProperty("location").GetProperty("name").GetString() ?? TEXT.NoLocation);

// One request to the API. Network errors are retried.
async Task<(HttpStatusCode Status, JsonElement Json, HttpResponseHeaders Headers)> Call(HttpMethod method, string path, string? bearer, object? body = null, string? idempotencyKey = null)
{
    for (var failures = 1; ; failures++)
    {
        using var request = new HttpRequestMessage(method, baseUrl + path);
        if (bearer is not null) request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
        // A write carries an Idempotency-Key; a retry of the same request sends the same key.
        if (idempotencyKey is not null) request.Headers.Add("Idempotency-Key", idempotencyKey);
        if (body is not null) request.Content = JsonContent.Create(body);
        try
        {
            using var response = await http.SendAsync(request);
            return (response.StatusCode, ParseJson(await response.Content.ReadAsStringAsync()), response.Headers);
        }
        catch (Exception error) when (error is HttpRequestException or TaskCanceledException)
        {
            await PauseAfterError(failures, error.Message);
        }
    }
}

// The body as JSON; empty when there is none or it is no JSON, such as the error page of a proxy.
static JsonElement ParseJson(string text)
{
    try
    {
        return text.Length > 0 ? JsonDocument.Parse(text).RootElement.Clone() : default;
    }
    catch (JsonException)
    {
        return default;
    }
}

// Waits after a network error, a 5xx or an unexpected answer: pollSeconds, doubled with every error
// in a row, at most MaxPauseSeconds. A device never asks again without a pause.
async Task PauseAfterError(int failures, string reason)
{
    var seconds = Math.Min(pollSeconds * Math.Pow(2, failures - 1), MaxPauseSeconds);
    Console.Error.WriteLine(TEXT.Offline, reason, seconds);
    await Task.Delay(TimeSpan.FromSeconds(seconds));
}

// Asks for a code. Returns the token and when the code runs out; null when the token is paired already.
async Task<(string? Token, DateTimeOffset? ExpiresAt)> RequestCode(string? bearer)
{
    var key = Guid.NewGuid().ToString();
    var failures = 0;
    while (true)
    {
        var (status, json, headers) = await Call(HttpMethod.Post, "/device-pairings", bearer, new { model = "Kickertisch-Beispiel", firmware = "1.0" }, key);
        if (status == HttpStatusCode.Created)
        {
            var data = json.GetProperty("data");
            var newToken = data.GetProperty("token").GetString()!;
            // Shown only this once: keep it before anything else.
            SaveToken(newToken);
            var code = data.GetProperty("code").GetString()!;
            var expiresAt = DateTimeOffset.Parse(data.GetProperty("expires_at").GetString()!, CultureInfo.InvariantCulture);
            ShowCode(code, expiresAt);
            return (newToken, expiresAt);
        }
        var problem = ProblemCode(json);
        if (status == HttpStatusCode.Conflict && problem == "device_already_paired") return (bearer, null);
        if (status == HttpStatusCode.Conflict && problem == "table_devices_off")
        {
            Console.WriteLine(TEXT.Off);
            await Task.Delay(TimeSpan.FromSeconds(60));
        }
        else if (status == HttpStatusCode.TooManyRequests) await Task.Delay(RetryAfter(headers));
        // The API is busy or being deployed: the same request with the same key, after a pause.
        else if ((int)status >= 500) await PauseAfterError(++failures, $"HTTP {(int)status}");
        else Fail(status, json);
    }
}

// GET /device until it answers 200. Null once the code has run out, or at once when no code is
// waiting (expiresAt null) and the token does not sign in: the device was unpaired.
// Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
async Task<JsonElement?> WaitForPairing(string? bearer, DateTimeOffset? expiresAt)
{
    var failures = 0;
    while (true)
    {
        var (status, json, headers) = await Call(HttpMethod.Get, "/device", bearer);
        if (status == HttpStatusCode.OK) return json.GetProperty("data");
        if (status == HttpStatusCode.TooManyRequests) { await Task.Delay(RetryAfter(headers)); continue; }
        // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
        if ((int)status is >= 400 and < 500 && status != HttpStatusCode.Unauthorized) Fail(status, json);
        if (status != HttpStatusCode.Unauthorized)
        {
            // Someone may be typing the code right now: keep it, ask again after a pause.
            await PauseAfterError(++failures, $"HTTP {(int)status}");
            continue;
        }
        failures = 0;
        if (expiresAt is null || DateTimeOffset.UtcNow >= expiresAt) return null;
        await Task.Delay(TimeSpan.FromSeconds(pollSeconds));
    }
}

// Keeps the token in a file only this user can read, written in one step.
void SaveToken(string value)
{
    Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(tokenFile))!);
    var temporary = tokenFile + ".tmp";
    // A leftover from a crash may have other rights: remove it, then create the file anew.
    File.Delete(temporary);
    var options = new FileStreamOptions { Mode = FileMode.CreateNew, Access = FileAccess.Write };
    if (!OperatingSystem.IsWindows()) options.UnixCreateMode = UnixFileMode.UserRead | UnixFileMode.UserWrite;
    using (var stream = new FileStream(temporary, options))
    using (var writer = new StreamWriter(stream)) writer.WriteLine(value);
    File.Move(temporary, tokenFile, overwrite: true);
}

void ShowCode(string code, DateTimeOffset expiresAt)
{
    // The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
    // For a QR code on a display, a package such as QRCoder draws this link.
    var host = new Uri(baseUrl).Authority;
    if (host.StartsWith("api.")) host = "app." + host[4..];
    Console.WriteLine();
    Console.WriteLine(TEXT.Code, $"{code[..3]} {code[3..]}", expiresAt.ToLocalTime());
    Console.WriteLine(TEXT.Link, $"https://{host}/verbinden?code={code}");
    Console.WriteLine(TEXT.Enter);
    Console.WriteLine();
}

// Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date.
static TimeSpan RetryAfter(HttpResponseHeaders headers)
{
    var wait = headers.RetryAfter?.Delta ?? (headers.RetryAfter?.Date - DateTimeOffset.UtcNow) ?? TimeSpan.FromSeconds(60);
    return wait < TimeSpan.FromSeconds(1) ? TimeSpan.FromSeconds(1) : wait;
}

static string? ProblemCode(JsonElement json) =>
    json.ValueKind == JsonValueKind.Object && json.TryGetProperty("code", out var code) ? code.GetString() : null;

void Fail(HttpStatusCode status, JsonElement json)
{
    var detail = json.ValueKind == JsonValueKind.Object && json.TryGetProperty("detail", out var text) ? text.GetString() : TEXT.Unexpected;
    Console.Error.WriteLine(TEXT.Error, (int)status, ProblemCode(json), detail);
    Environment.Exit(1);
}
```

#### PHP (php/pair-device.php)

```php
<?php

// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. PHP 8.1 or newer with the curl extension, no framework.
//
//   php pair-device.php
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5

declare(strict_types=1);

// What the device shows, in the language of the location.
const TEXT = [
    'code' => 'Code am Tisch: %s  (gilt bis %s Uhr)',
    'link' => 'QR-Code mit diesem Link: %s',
    'enter' => 'Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.',
    'expired' => 'Der Code ist abgelaufen. Ich hole einen neuen.',
    'unpaired' => 'Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.',
    'off' => 'Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.',
    'offline' => 'Keine Verbindung (%s), neuer Versuch in %s s',
    'paired' => 'Verbunden mit %s (%s)',
    'no_location' => 'ohne Standort',
    'error' => 'Fehler %d %s: %s',
    'unexpected' => 'unerwartete Antwort',
];

const USER_AGENT = 'Kickertisch-Beispiel/1.0'; // Every request names the device: product and firmware.
const MAX_PAUSE_SECONDS = 60; // After errors in a row the pause doubles, up to this many seconds.

$baseUrl = rtrim(getenv('PACKEROO_BASE_URL') ?: 'https://api.qm.packeroo.com/api/v1', '/');
$tokenFile = getenv('PACKEROO_TOKEN_FILE') ?: (getenv('HOME') ?: getenv('USERPROFILE')).'/.config/packeroo/device-token';
$pollSeconds = (float) (getenv('PACKEROO_POLL_SECONDS') ?: 5);

/** One request to the API: [status, json, retryAfter]. Network errors are retried. */
function call(string $method, string $path, ?string $token = null, ?array $body = null, ?string $idempotencyKey = null): array
{
    global $baseUrl, $pollSeconds;
    $headers = ['Accept: application/json', 'Accept-Language: de'];
    if ($token !== null) {
        $headers[] = 'Authorization: Bearer '.$token;
    }
    if ($body !== null) {
        $headers[] = 'Content-Type: application/json';
    }
    // A write carries an Idempotency-Key; a retry of the same request sends the same key.
    if ($idempotencyKey !== null) {
        $headers[] = 'Idempotency-Key: '.$idempotencyKey;
    }

    for ($failures = 1; ; $failures++) {
        $retryAfter = 60;
        $curl = curl_init($baseUrl.$path);
        curl_setopt_array($curl, [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_HTTPHEADER => $headers,
            CURLOPT_USERAGENT => USER_AGENT,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_HEADERFUNCTION => function ($curl, string $line) use (&$retryAfter): int {
                // Retry-After is a number of seconds or an HTTP date.
                if (preg_match('/^Retry-After:\s*(.+?)\s*$/i', $line, $match)) {
                    $seconds = ctype_digit($match[1]) ? (int) $match[1] : (strtotime($match[1]) ?: time() + 60) - time();
                    $retryAfter = max(1, $seconds);
                }

                return strlen($line);
            },
        ]);
        if ($body !== null) {
            curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($body, JSON_THROW_ON_ERROR));
        }
        $text = curl_exec($curl);
        if ($text === false) {
            pauseAfterError($failures, curl_error($curl));

            continue;
        }
        $status = curl_getinfo($curl, CURLINFO_RESPONSE_CODE);
        // An empty body or one that is no JSON, such as the error page of a proxy, gives [].
        $json = json_decode($text, true);

        return [$status, is_array($json) ? $json : [], $retryAfter];
    }
}

/**
 * Waits after a network error, a 5xx or an unexpected answer: the poll interval, doubled with every
 * error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
 */
function pauseAfterError(int $failures, string $reason): void
{
    global $pollSeconds;
    $seconds = min($pollSeconds * 2 ** ($failures - 1), MAX_PAUSE_SECONDS);
    fwrite(STDERR, sprintf(TEXT['offline'], $reason, $seconds)."\n");
    usleep((int) ($seconds * 1_000_000));
}

/** Keeps the token in a file only this user can read, written in one step. */
function saveToken(string $token): void
{
    global $tokenFile;
    if (! is_dir(dirname($tokenFile))) {
        mkdir(dirname($tokenFile), 0700, true);
    }
    $temporary = $tokenFile.'.tmp';
    // A leftover from a crash may have other rights: remove it, then create the file anew ('x').
    if (file_exists($temporary)) {
        unlink($temporary);
    }
    $old = umask(0077);
    $file = fopen($temporary, 'x');
    umask($old);
    if ($file === false) {
        throw new RuntimeException("Cannot create {$temporary}");
    }
    fwrite($file, $token."\n");
    fclose($file);
    chmod($temporary, 0600);
    rename($temporary, $tokenFile);
}

function showCode(string $code, string $expiresAt): void
{
    global $baseUrl;
    // The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
    // For a QR code on a display, a library such as chillerlan/php-qrcode draws this link.
    $host = parse_url($baseUrl, PHP_URL_HOST).(parse_url($baseUrl, PHP_URL_PORT) ? ':'.parse_url($baseUrl, PHP_URL_PORT) : '');
    if (str_starts_with($host, 'api.')) {
        $host = 'app.'.substr($host, 4);
    }
    $until = (new DateTimeImmutable($expiresAt))->setTimezone(new DateTimeZone(date_default_timezone_get()))->format('H:i');
    echo "\n".sprintf(TEXT['code'], substr($code, 0, 3).' '.substr($code, 3), $until)."\n";
    echo sprintf(TEXT['link'], "https://{$host}/verbinden?code={$code}")."\n";
    echo TEXT['enter']."\n\n";
}

function fail(int $status, array $problem): never
{
    fwrite(STDERR, sprintf(TEXT['error'], $status, $problem['code'] ?? '', $problem['detail'] ?? TEXT['unexpected'])."\n");
    exit(1);
}

/** Asks for a code: [token, expiresAt], with expiresAt null when the token is paired already. */
function requestCode(?string $token): array
{
    $key = sprintf('%04x%04x-%04x-4%03x-%04x-%04x%04x%04x', ...[
        random_int(0, 0xFFFF), random_int(0, 0xFFFF), random_int(0, 0xFFFF), random_int(0, 0xFFF),
        random_int(0, 0x3FFF) | 0x8000, random_int(0, 0xFFFF), random_int(0, 0xFFFF), random_int(0, 0xFFFF),
    ]);
    $failures = 0;
    while (true) {
        [$status, $answer, $retryAfter] = call('POST', '/device-pairings', $token, ['model' => 'Kickertisch-Beispiel', 'firmware' => '1.0'], $key);
        if ($status === 201) {
            $data = $answer['data'];
            // Shown only this once: keep it before anything else.
            saveToken($data['token']);
            showCode($data['code'], $data['expires_at']);

            return [$data['token'], strtotime($data['expires_at'])];
        }
        $code = $answer['code'] ?? null;
        if ($status === 409 && $code === 'device_already_paired') {
            return [$token, null];
        }
        if ($status === 409 && $code === 'table_devices_off') {
            echo TEXT['off']."\n";
            sleep(60);
        } elseif ($status === 429) {
            sleep($retryAfter);
        } elseif ($status >= 500) {
            // The API is busy or being deployed: the same request with the same key, after a pause.
            pauseAfterError(++$failures, "HTTP {$status}");
        } else {
            fail($status, $answer);
        }
    }
}

/**
 * GET /device until it answers 200. Null once the code has run out, or at once when no code is
 * waiting ($expiresAt null) and the token does not sign in: the device was unpaired.
 * Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
 */
function waitForPairing(?string $token, ?int $expiresAt): ?array
{
    global $pollSeconds;
    $failures = 0;
    while (true) {
        [$status, $answer, $retryAfter] = call('GET', '/device', $token);
        if ($status === 200) {
            return $answer['data'];
        }
        if ($status === 429) {
            sleep($retryAfter);

            continue;
        }
        // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
        if ($status >= 400 && $status < 500 && $status !== 401) {
            fail($status, $answer);
        }
        if ($status !== 401) {
            // Someone may be typing the code right now: keep it, ask again after a pause.
            pauseAfterError(++$failures, "HTTP {$status}");

            continue;
        }
        $failures = 0;
        if ($expiresAt === null || time() >= $expiresAt) {
            return null;
        }
        usleep((int) ($pollSeconds * 1_000_000));
    }
}

$token = is_file($tokenFile) ? (trim((string) file_get_contents($tokenFile)) ?: null) : null;
// With a stored token, ask first whether it still signs in; null after a 401.
$device = $token === null ? null : waitForPairing($token, null);

while ($device === null) {
    [$token, $expiresAt] = requestCode($token);
    $device = waitForPairing($token, $expiresAt);
    if ($device === null && $expiresAt === null) {
        // Paired a moment ago, unpaired now: this token is of no use any more.
        echo TEXT['unpaired']."\n";
        $token = null;
    } elseif ($device === null) {
        echo TEXT['expired']."\n";
    }
}

echo sprintf(TEXT['paired'], $device['table']['name'], $device['location']['name'] ?? TEXT['no_location'])."\n";
```

#### Go (go/main.go)

```go
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. Go 1.21 or newer, standard library only.
//
//	go run .
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
package main

import (
	"bytes"
	"crypto/rand"
	"encoding/json"
	"fmt"
	"io"
	"math"
	"net/http"
	"net/url"
	"os"
	"path/filepath"
	"strconv"
	"strings"
	"time"
)

// What the device shows, in the language of the location.
var text = struct{ code, link, enter, expired, unpaired, off, offline, paired, noLocation, error, unexpected string }{
	code:       "Code am Tisch: %s %s  (gilt bis %s Uhr)\n",
	link:       "QR-Code mit diesem Link: %s\n",
	enter:      "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.",
	expired:    "Der Code ist abgelaufen. Ich hole einen neuen.",
	unpaired:   "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.",
	off:        "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.",
	offline:    "Keine Verbindung (%v), neuer Versuch in %g s\n",
	paired:     "Verbunden mit %s (%s)\n",
	noLocation: "ohne Standort",
	error:      "Fehler %d %s: %s\n",
	unexpected: "unerwartete Antwort",
}

// Every request names the device: product and firmware.
const userAgent = "Kickertisch-Beispiel/1.0"

// After errors in a row the pause doubles, up to this many seconds.
const maxPauseSeconds = 60

var (
	baseURL     = strings.TrimRight(env("PACKEROO_BASE_URL", "https://api.qm.packeroo.com/api/v1"), "/")
	tokenFile   = env("PACKEROO_TOKEN_FILE", filepath.Join(home(), ".config", "packeroo", "device-token"))
	pollSeconds = mustFloat(env("PACKEROO_POLL_SECONDS", "5"))
	client      = &http.Client{Timeout: 30 * time.Second}
)

type device struct {
	Table        struct{ Name string }  `json:"table"`
	Location     struct{ Name *string } `json:"location"`
	Organization struct{ Name *string } `json:"organization"`
}

type answer struct {
	status     int
	body       []byte
	retryAfter time.Duration
	problem    struct {
		Code   string `json:"code"`
		Detail string `json:"detail"`
	}
}

func main() {
	token := readToken()
	var paired *device

	// With a stored token, ask first whether it still signs in; nil after a 401.
	if token != "" {
		paired = waitForPairing(token, nil)
	}

	for paired == nil {
		var expiresAt *time.Time
		token, expiresAt = requestCode(token)
		paired = waitForPairing(token, expiresAt)
		if paired == nil && expiresAt == nil {
			// Paired a moment ago, unpaired now: this token is of no use any more.
			fmt.Println(text.unpaired)
			token = ""
		} else if paired == nil {
			fmt.Println(text.expired)
		}
	}

	location := text.noLocation
	if paired.Location.Name != nil {
		location = *paired.Location.Name
	}
	fmt.Printf(text.paired, paired.Table.Name, location)
}

// call sends one request to the API. Network errors are retried.
func call(method, path, token string, body any, idempotencyKey string) answer {
	for failures := 1; ; failures++ {
		var reader io.Reader
		if body != nil {
			encoded, _ := json.Marshal(body)
			reader = bytes.NewReader(encoded)
		}
		request, _ := http.NewRequest(method, baseURL+path, reader)
		request.Header.Set("User-Agent", userAgent)
		request.Header.Set("Accept", "application/json")
		request.Header.Set("Accept-Language", "de")
		if token != "" {
			request.Header.Set("Authorization", "Bearer "+token)
		}
		if body != nil {
			request.Header.Set("Content-Type", "application/json")
		}
		// A write carries an Idempotency-Key; a retry of the same request sends the same key.
		if idempotencyKey != "" {
			request.Header.Set("Idempotency-Key", idempotencyKey)
		}

		response, err := client.Do(request)
		if err != nil {
			pauseAfterError(failures, err)
			continue
		}
		data, _ := io.ReadAll(response.Body)
		response.Body.Close()

		result := answer{status: response.StatusCode, body: data, retryAfter: 60 * time.Second}
		// Retry-After is a number of seconds or an HTTP date.
		if value := response.Header.Get("Retry-After"); value != "" {
			if seconds, err := strconv.Atoi(value); err == nil {
				result.retryAfter = time.Duration(seconds) * time.Second
			} else if date, err := http.ParseTime(value); err == nil {
				result.retryAfter = time.Until(date)
			}
			if result.retryAfter < time.Second {
				result.retryAfter = time.Second
			}
		}
		// A body that is no JSON, such as the error page of a proxy, leaves the problem empty.
		if response.StatusCode >= 400 {
			_ = json.Unmarshal(data, &result.problem)
		}
		return result
	}
}

// pauseAfterError waits after a network error, a 5xx or an unexpected answer: pollSeconds, doubled
// with every error in a row, at most maxPauseSeconds. A device never asks again without a pause.
func pauseAfterError(failures int, reason any) {
	seconds := math.Min(pollSeconds*math.Pow(2, float64(failures-1)), maxPauseSeconds)
	fmt.Fprintf(os.Stderr, text.offline, reason, seconds)
	sleep(seconds)
}

// requestCode asks for a code. It returns the token and when the code runs out; nil when the token is paired already.
func requestCode(token string) (string, *time.Time) {
	key := uuid()
	failures := 0
	for {
		result := call("POST", "/device-pairings", token, map[string]string{"model": "Kickertisch-Beispiel", "firmware": "1.0"}, key)
		switch {
		case result.status == 201:
			var created struct {
				Data struct {
					Code      string    `json:"code"`
					ExpiresAt time.Time `json:"expires_at"`
					Token     string    `json:"token"`
				} `json:"data"`
			}
			if err := json.Unmarshal(result.body, &created); err != nil {
				fail(result)
			}
			// Shown only this once: keep it before anything else.
			saveToken(created.Data.Token)
			showCode(created.Data.Code, created.Data.ExpiresAt)
			return created.Data.Token, &created.Data.ExpiresAt
		case result.status == 409 && result.problem.Code == "device_already_paired":
			return token, nil
		case result.status == 409 && result.problem.Code == "table_devices_off":
			fmt.Println(text.off)
			time.Sleep(60 * time.Second)
		case result.status == 429:
			time.Sleep(result.retryAfter)
		case result.status >= 500:
			// The API is busy or being deployed: the same request with the same key, after a pause.
			failures++
			pauseAfterError(failures, fmt.Sprintf("HTTP %d", result.status))
		default:
			fail(result)
		}
	}
}

// waitForPairing reads GET /device until it answers 200. Nil once the code has run out, or at once
// when no code is waiting (expiresAt nil) and the token does not sign in: the device was unpaired.
// Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
func waitForPairing(token string, expiresAt *time.Time) *device {
	failures := 0
	for {
		result := call("GET", "/device", token, nil, "")
		switch result.status {
		case 200:
			return decodeDevice(result)
		case 429:
			time.Sleep(result.retryAfter)
			continue
		case 401:
			failures = 0
		default:
			// A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
			if result.status >= 400 && result.status < 500 {
				fail(result)
			}
			// Someone may be typing the code right now: keep it, ask again after a pause.
			failures++
			pauseAfterError(failures, fmt.Sprintf("HTTP %d", result.status))
			continue
		}
		if expiresAt == nil || !time.Now().Before(*expiresAt) {
			return nil
		}
		sleep(pollSeconds)
	}
}

func decodeDevice(result answer) *device {
	var read struct{ Data device }
	if err := json.Unmarshal(result.body, &read); err != nil {
		fail(result)
	}
	return &read.Data
}

func readToken() string {
	data, err := os.ReadFile(tokenFile)
	if err != nil {
		return ""
	}
	return strings.TrimSpace(string(data))
}

// saveToken keeps the token in a file only this user can read, written in one step.
func saveToken(token string) {
	if err := os.MkdirAll(filepath.Dir(tokenFile), 0o700); err != nil {
		panic(err)
	}
	temporary := tokenFile + ".tmp"
	// A leftover from a crash may have other rights: remove it, then create the file anew.
	_ = os.Remove(temporary)
	file, err := os.OpenFile(temporary, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
	if err != nil {
		panic(err)
	}
	if _, err := file.WriteString(token + "\n"); err != nil {
		panic(err)
	}
	if err := file.Close(); err != nil {
		panic(err)
	}
	if err := os.Rename(temporary, tokenFile); err != nil {
		panic(err)
	}
}

func showCode(code string, expiresAt time.Time) {
	// The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
	// For a QR code on a display, a package such as github.com/skip2/go-qrcode draws this link.
	parsed, _ := url.Parse(baseURL)
	host := parsed.Host
	if strings.HasPrefix(host, "api.") {
		host = "app." + host[4:]
	}
	fmt.Println()
	fmt.Printf(text.code, code[:3], code[3:], expiresAt.Local().Format("15:04"))
	fmt.Printf(text.link, "https://"+host+"/verbinden?code="+code)
	fmt.Println(text.enter)
	fmt.Println()
}

func fail(result answer) {
	detail := result.problem.Detail
	if detail == "" {
		detail = text.unexpected
	}
	fmt.Fprintf(os.Stderr, text.error, result.status, result.problem.Code, detail)
	os.Exit(1)
}

func uuid() string {
	b := make([]byte, 16)
	_, _ = rand.Read(b)
	b[6] = b[6]&0x0f | 0x40
	b[8] = b[8]&0x3f | 0x80
	return fmt.Sprintf("%x-%x-%x-%x-%x", b[0:4], b[4:6], b[6:8], b[8:10], b[10:])
}

func env(name, fallback string) string {
	if value := os.Getenv(name); value != "" {
		return value
	}
	return fallback
}

func home() string {
	dir, _ := os.UserHomeDir()
	return dir
}

func mustFloat(value string) float64 {
	number, err := strconv.ParseFloat(value, 64)
	if err != nil {
		return 5
	}
	return number
}

func sleep(seconds float64) {
	time.Sleep(time.Duration(seconds * float64(time.Second)))
}
```

#### Java (java/PairDevice.java)

```java
// Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
// someone enters the code in the app. Java 17 or newer, java.net.http, no libraries.
//
//   java PairDevice.java
//
// PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
// PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
// PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
//
// The answers are read with a small helper to stay without libraries; in a real device take a
// JSON library such as Jackson or Gson.

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.nio.file.attribute.PosixFilePermissions;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Optional;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PairDevice {
    /** What the device shows, in the language of the location. */
    static final class Text {
        static final String CODE = "Code am Tisch: %s %s  (gilt bis %s Uhr)";
        static final String LINK = "QR-Code mit diesem Link: %s";
        static final String ENTER = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.";
        static final String EXPIRED = "Der Code ist abgelaufen. Ich hole einen neuen.";
        static final String UNPAIRED = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.";
        static final String OFF = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.";
        static final String OFFLINE = "Keine Verbindung (%s), neuer Versuch in %s s";
        static final String PAIRED = "Verbunden mit %s";
        static final String ERROR = "Fehler %d %s: %s";
        static final String UNEXPECTED = "unerwartete Antwort";
    }

    // Every request names the device: product and firmware.
    static final String USER_AGENT = "Kickertisch-Beispiel/1.0";
    static final String BASE_URL = env("PACKEROO_BASE_URL", "https://api.qm.packeroo.com/api/v1").replaceAll("/+$", "");
    static final Path TOKEN_FILE = Path.of(env("PACKEROO_TOKEN_FILE", Path.of(System.getProperty("user.home"), ".config", "packeroo", "device-token").toString()));
    static final double POLL_SECONDS = Double.parseDouble(env("PACKEROO_POLL_SECONDS", "5"));
    /** After errors in a row the pause doubles, up to this many seconds. */
    static final double MAX_PAUSE_SECONDS = 60;
    static final HttpClient HTTP = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(30)).build();

    record Answer(int status, String body, long retryAfterSeconds) {}

    record Pairing(String token, Instant expiresAt) {}

    public static void main(String[] args) throws Exception {
        String token = readToken();
        // With a stored token, ask first whether it still signs in; null after a 401.
        String device = token == null ? null : waitForPairing(token, null);

        while (device == null) {
            Pairing pairing = requestCode(token);
            token = pairing.token();
            device = waitForPairing(token, pairing.expiresAt());
            if (device == null && pairing.expiresAt() == null) {
                // Paired a moment ago, unpaired now: this token is of no use any more.
                System.out.println(Text.UNPAIRED);
                token = null;
            } else if (device == null) {
                System.out.println(Text.EXPIRED);
            }
        }

        String table = field(device, "\"table\"\\s*:\\s*\\{[^}]*?\"name\"").orElse("?");
        System.out.println(String.format(Text.PAIRED, table));
    }

    /** One request to the API. Network errors are retried. */
    static Answer call(String method, String path, String token, String json, String idempotencyKey) throws InterruptedException {
        HttpRequest.Builder builder = HttpRequest.newBuilder(URI.create(BASE_URL + path))
            .timeout(Duration.ofSeconds(30))
            .header("User-Agent", USER_AGENT)
            .header("Accept", "application/json")
            .header("Accept-Language", "de")
            .method(method, json == null ? HttpRequest.BodyPublishers.noBody() : HttpRequest.BodyPublishers.ofString(json));
        if (token != null) builder.header("Authorization", "Bearer " + token);
        if (json != null) builder.header("Content-Type", "application/json");
        // A write carries an Idempotency-Key; a retry of the same request sends the same key.
        if (idempotencyKey != null) builder.header("Idempotency-Key", idempotencyKey);
        HttpRequest request = builder.build();

        for (int failures = 1; ; failures++) {
            try {
                HttpResponse<String> response = HTTP.send(request, HttpResponse.BodyHandlers.ofString());
                long retryAfter = response.headers().firstValue("Retry-After").map(PairDevice::retryAfterSeconds).orElse(60L);
                // A body that is no JSON, such as the error page of a proxy, has no fields: field() finds none.
                return new Answer(response.statusCode(), response.body(), retryAfter);
            } catch (IOException error) {
                pauseAfterError(failures, error.getMessage());
            }
        }
    }

    /**
     * Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
     * error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
     */
    static void pauseAfterError(int failures, String reason) throws InterruptedException {
        double seconds = Math.min(POLL_SECONDS * Math.pow(2, failures - 1), MAX_PAUSE_SECONDS);
        System.err.println(String.format(Text.OFFLINE, reason, seconds));
        sleep(seconds);
    }

    /** Retry-After is a number of seconds or an HTTP date such as "Wed, 21 Oct 2026 07:28:00 GMT". */
    static long retryAfterSeconds(String value) {
        try {
            return Math.max(1, Long.parseLong(value.trim()));
        } catch (NumberFormatException notANumber) {
            try {
                ZonedDateTime date = ZonedDateTime.parse(value.trim(), DateTimeFormatter.RFC_1123_DATE_TIME);
                return Math.max(1, Duration.between(Instant.now(), date.toInstant()).getSeconds());
            } catch (DateTimeParseException notADate) {
                return 60;
            }
        }
    }

    /** Asks for a code. expiresAt is null when the token is paired already. */
    static Pairing requestCode(String token) throws Exception {
        String key = UUID.randomUUID().toString();
        int failures = 0;
        while (true) {
            Answer result = call("POST", "/device-pairings", token, "{\"model\":\"Kickertisch-Beispiel\",\"firmware\":\"1.0\"}", key);
            if (result.status() == 201) {
                String newToken = field(result.body(), "\"token\"").orElseThrow();
                // Shown only this once: keep it before anything else.
                saveToken(newToken);
                String code = field(result.body(), "\"code\"").orElseThrow();
                Instant expiresAt = Instant.parse(field(result.body(), "\"expires_at\"").orElseThrow());
                showCode(code, expiresAt);
                return new Pairing(newToken, expiresAt);
            }
            String problem = field(result.body(), "\"code\"").orElse("");
            if (result.status() == 409 && problem.equals("device_already_paired")) return new Pairing(token, null);
            if (result.status() == 409 && problem.equals("table_devices_off")) {
                System.out.println(Text.OFF);
                sleep(60);
            } else if (result.status() == 429) {
                sleep(result.retryAfterSeconds());
            } else if (result.status() >= 500) {
                // The API is busy or being deployed: the same request with the same key, after a pause.
                pauseAfterError(++failures, "HTTP " + result.status());
            } else {
                fail(result);
            }
        }
    }

    /**
     * GET /device until it answers 200. Null once the code has run out, or at once when no code is
     * waiting (expiresAt null) and the token does not sign in: the device was unpaired.
     * Only 401 means "not paired"; on a 5xx it keeps the code and asks again, another answer is an error.
     */
    static String waitForPairing(String token, Instant expiresAt) throws InterruptedException {
        int failures = 0;
        while (true) {
            Answer result = call("GET", "/device", token, null, null);
            if (result.status() == 200) return result.body();
            if (result.status() == 429) {
                sleep(result.retryAfterSeconds());
                continue;
            }
            // A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
            if (result.status() >= 400 && result.status() < 500 && result.status() != 401) fail(result);
            if (result.status() != 401) {
                // Someone may be typing the code right now: keep it, ask again after a pause.
                pauseAfterError(++failures, "HTTP " + result.status());
                continue;
            }
            failures = 0;
            if (expiresAt == null || !Instant.now().isBefore(expiresAt)) return null;
            sleep(POLL_SECONDS);
        }
    }

    static String readToken() throws IOException {
        if (!Files.exists(TOKEN_FILE)) return null;
        String token = Files.readString(TOKEN_FILE).trim();
        return token.isEmpty() ? null : token;
    }

    /** Keeps the token in a file only this user can read, written in one step. */
    static void saveToken(String token) throws IOException {
        Path directory = TOKEN_FILE.toAbsolutePath().getParent();
        Files.createDirectories(directory);
        Path temporary = directory.resolve(TOKEN_FILE.getFileName() + ".tmp");
        Files.deleteIfExists(temporary);
        try {
            Files.createFile(temporary, PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rw-------")));
        } catch (UnsupportedOperationException windows) {
            Files.createFile(temporary);
        }
        Files.writeString(temporary, token + "\n");
        Files.move(temporary, TOKEN_FILE, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
    }

    static void showCode(String code, Instant expiresAt) {
        // The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
        // For a QR code on a display, a library such as ZXing draws this link.
        String host = URI.create(BASE_URL).getAuthority();
        if (host.startsWith("api.")) host = "app." + host.substring(4);
        String until = DateTimeFormatter.ofPattern("HH:mm").withZone(ZoneId.systemDefault()).format(expiresAt);
        System.out.println();
        System.out.println(String.format(Text.CODE, code.substring(0, 3), code.substring(3), until));
        System.out.println(String.format(Text.LINK, "https://" + host + "/verbinden?code=" + code));
        System.out.println(Text.ENTER);
        System.out.println();
    }

    /** The string value after a key, such as "\"code\"" in {"code":"K7F4QX"}. */
    static Optional<String> field(String json, String key) {
        Matcher match = Pattern.compile(key + "\\s*:\\s*\"((?:[^\"\\\\]|\\\\.)*)\"").matcher(json == null ? "" : json);
        return match.find() ? Optional.of(match.group(1)) : Optional.empty();
    }

    static void fail(Answer result) {
        String problem = field(result.body(), "\"code\"").orElse("");
        String detail = field(result.body(), "\"detail\"").orElse(Text.UNEXPECTED);
        System.err.println(String.format(Text.ERROR, result.status(), problem, detail));
        System.exit(1);
    }

    static void sleep(double seconds) throws InterruptedException {
        Thread.sleep((long) (seconds * 1000));
    }

    static String env(String name, String fallback) {
        String value = System.getenv(name);
        return value == null || value.isEmpty() ? fallback : value;
    }
}
```

#### curl (shell/pair-device.sh)

```bash
#!/usr/bin/env bash
# Pair a table device with packeroo: ask for a code, show it, keep the token, wait until
# someone enters the code in the app. Needs bash, curl and jq.
#
#   bash pair-device.sh
#
# PACKEROO_BASE_URL      API address, default the sandbox https://api.qm.packeroo.com/api/v1
# PACKEROO_TOKEN_FILE    where the token is kept, default ~/.config/packeroo/device-token
# PACKEROO_POLL_SECONDS  seconds between two GET /device, default 5
set -euo pipefail

# What the device shows, in the language of the location.
TEXT_CODE='Code am Tisch: %s %s  (gilt bis %s UTC)\n'
TEXT_LINK='QR-Code mit diesem Link: %s\n'
TEXT_ENTER='Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.'
TEXT_EXPIRED='Der Code ist abgelaufen. Ich hole einen neuen.'
TEXT_UNPAIRED='Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.'
TEXT_OFF='Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.'
TEXT_OFFLINE='Keine Verbindung (%s), neuer Versuch in %s s\n'
TEXT_NO_KEY='Kein Idempotency-Key: weder /proc/sys/kernel/random/uuid noch uuidgen noch od gefunden.'
TEXT_PAIRED='"Verbunden mit \(.data.table.name) (\(.data.location.name // "ohne Standort"))"'
TEXT_ERROR='Fehler %s %s: %s\n'

BASE_URL="${PACKEROO_BASE_URL:-https://api.qm.packeroo.com/api/v1}"
BASE_URL="${BASE_URL%/}"
TOKEN_FILE="${PACKEROO_TOKEN_FILE:-$HOME/.config/packeroo/device-token}"
POLL_SECONDS="${PACKEROO_POLL_SECONDS:-5}"
MAX_PAUSE_SECONDS=60 # After errors in a row the pause doubles, up to this many seconds.
USER_AGENT="Kickertisch-Beispiel/1.0" # Every request names the device: product and firmware.

BODY_FILE="$(mktemp)"
HEADER_FILE="$(mktemp)"
trap 'rm -f "$BODY_FILE" "$HEADER_FILE"' EXIT

# call METHOD PATH [TOKEN] [IDEMPOTENCY_KEY] [JSON]: prints the status, the body is in $BODY_FILE.
# Network errors are retried.
call() {
  local method="$1" path="$2" token="${3:-}" key="${4:-}" json="${5:-}"
  local args=(-sS -X "$method" -o "$BODY_FILE" -D "$HEADER_FILE" -w '%{http_code}' --max-time 30
    -H "User-Agent: $USER_AGENT" -H 'Accept: application/json' -H 'Accept-Language: de')
  # A write carries an Idempotency-Key; a retry of the same request sends the same key.
  [[ -n "$key" ]] && args+=(-H "Idempotency-Key: $key")
  [[ -n "$json" ]] && args+=(-H 'Content-Type: application/json' --data "$json")
  local status error failures=0
  # The token reaches curl on stdin (--config -), not on the command line, where ps would show it.
  until status="$(curl "${args[@]}" --config - "$BASE_URL$path" <<< "${token:+header = \"Authorization: Bearer $token\"}")"; do
    error=$?
    failures=$((failures + 1))
    pause_after_error "$failures" "curl $error"
  done
  echo "$status"
}

# Waits after a network error, a 5xx or an unexpected answer: POLL_SECONDS, doubled with every
# error in a row, at most MAX_PAUSE_SECONDS. A device never asks again without a pause.
pause_after_error() {
  local seconds
  seconds="$(awk -v poll="$POLL_SECONDS" -v n="$1" -v max="$MAX_PAUSE_SECONDS" 'BEGIN { s = poll * 2 ^ (n - 1); print (s > max ? max : s) }')"
  printf "$TEXT_OFFLINE" "$2" "$seconds" >&2
  sleep "$seconds"
}

# Seconds to wait after a 429, from Retry-After: a number of seconds or an HTTP date.
retry_after() {
  local value seconds
  value="$(grep -i '^retry-after:' "$HEADER_FILE" | cut -d: -f2- | tr -d '\r' | sed 's/^ *//' || true)"
  if [[ "$value" =~ ^[0-9]+$ ]]; then seconds="$value"
  elif [[ -n "$value" ]] && date -d "$value" +%s >/dev/null 2>&1; then seconds=$(( $(date -d "$value" +%s) - $(date +%s) ))
  else seconds=60
  fi
  (( seconds < 1 )) && seconds=1
  echo "$seconds"
}

problem() { jq -r '.code // empty' "$BODY_FILE" 2>/dev/null || true; }

fail() {
  printf "$TEXT_ERROR" "$1" "$(problem)" "$(jq -r '.detail // "unerwartete Antwort"' "$BODY_FILE" 2>/dev/null)" >&2
  exit 1
}

new_key() {
  if [[ -r /proc/sys/kernel/random/uuid ]]; then cat /proc/sys/kernel/random/uuid
  elif command -v uuidgen >/dev/null; then uuidgen | tr 'A-Z' 'a-z'
  elif command -v od >/dev/null; then od -An -N16 -tx1 /dev/urandom | tr -d ' \n' | sed -E 's/(.{8})(.{4}).(.{3}).(.{3})(.{12})/\1-\2-4\3-a\4-\5/'
  fi
}

# Keeps the token in a file only this user can read, written in one step.
save_token() {
  mkdir -p "$(dirname "$TOKEN_FILE")"
  chmod 700 "$(dirname "$TOKEN_FILE")" 2>/dev/null || true
  # A leftover from a crash may have other rights: remove it, then create the file anew
  # (with noclobber, > fails instead of writing into a file that is there).
  rm -f "$TOKEN_FILE.tmp"
  (umask 077 && set -o noclobber && printf '%s\n' "$1" > "$TOKEN_FILE.tmp")
  mv -f "$TOKEN_FILE.tmp" "$TOKEN_FILE"
}

show_code() {
  local code="$1" host
  # The app address for the QR code: api.qm.packeroo.com becomes app.qm.packeroo.com.
  # For a QR code in the terminal, qrencode -t ansiutf8 draws this link.
  host="$(printf '%s' "$BASE_URL" | sed -E 's#^[a-z]+://([^/]+).*#\1#; s#^api\.#app.#')"
  printf '\n'
  printf "$TEXT_CODE" "${code:0:3}" "${code:3}" "$2"
  printf "$TEXT_LINK" "https://$host/verbinden?code=$code"
  printf '%s\n\n' "$TEXT_ENTER"
}

TOKEN=""
[[ -s "$TOKEN_FILE" ]] && TOKEN="$(tr -d '[:space:]' < "$TOKEN_FILE")"
PAIRED=""
EXPIRES=0

# With a stored token, ask first whether it still signs in; only 401 means it does not.
if [[ -n "$TOKEN" ]]; then
  failures=0
  while :; do
    status="$(call GET /device "$TOKEN")"
    case "$status" in
      200) PAIRED=1; break ;;
      401) break ;;
      429) sleep "$(retry_after)" ;;
      # A request the API refuses, such as a wrong PACKEROO_BASE_URL: asking again changes nothing.
      4??) fail "$status" ;;
      *) failures=$((failures + 1)); pause_after_error "$failures" "HTTP $status" ;;
    esac
  done
fi

while [[ -z "$PAIRED" ]]; do
  # Ask for a code. Without a key the API answers 400, so stop here instead.
  key="$(new_key)"
  if [[ -z "$key" ]]; then echo "$TEXT_NO_KEY" >&2; exit 1; fi
  failures=0
  while :; do
    status="$(call POST /device-pairings "$TOKEN" "$key" '{"model":"Kickertisch-Beispiel","firmware":"1.0"}')"
    if [[ "$status" == 201 ]]; then
      TOKEN="$(jq -r '.data.token' "$BODY_FILE")"
      # Shown only this once: keep it before anything else.
      save_token "$TOKEN"
      expires_at="$(jq -r '.data.expires_at' "$BODY_FILE")"
      EXPIRES="$(jq -r '.data.expires_at | fromdateiso8601' "$BODY_FILE")"
      show_code "$(jq -r '.data.code' "$BODY_FILE")" "${expires_at:11:5}"
      break
    elif [[ "$status" == 409 && "$(problem)" == device_already_paired ]]; then
      EXPIRES=0
      break
    elif [[ "$status" == 409 && "$(problem)" == table_devices_off ]]; then
      echo "$TEXT_OFF"
      sleep 60
    elif [[ "$status" == 429 ]]; then
      sleep "$(retry_after)"
    elif (( status >= 500 )); then
      # The API is busy or being deployed: the same request with the same key, after a pause.
      failures=$((failures + 1))
      pause_after_error "$failures" "HTTP $status"
    else
      fail "$status"
    fi
  done

  # GET /device until it answers 200. Without a waiting code (EXPIRES 0) a 401 means the device
  # was unpaired: drop the token and ask for a new code without it. Only 401 means "not paired";
  # on a 5xx someone may be typing the code: keep it, ask again after a pause. Another 4xx is an error.
  failures=0
  while :; do
    status="$(call GET /device "$TOKEN")"
    if [[ "$status" == 200 ]]; then PAIRED=1; break; fi
    if [[ "$status" == 429 ]]; then sleep "$(retry_after)"; continue; fi
    if [[ "$status" == 4?? && "$status" != 401 ]]; then fail "$status"; fi
    if [[ "$status" != 401 ]]; then
      failures=$((failures + 1))
      pause_after_error "$failures" "HTTP $status"
      continue
    fi
    failures=0
    if [[ "$EXPIRES" == 0 ]]; then
      echo "$TEXT_UNPAIRED"
      TOKEN=""
      break
    fi
    if [[ "$(date +%s)" -ge "$EXPIRES" ]]; then
      echo "$TEXT_EXPIRED"
      break
    fi
    sleep "$POLL_SECONDS"
  done
done

jq -r "$TEXT_PAIRED" "$BODY_FILE"
```

#### ESP32 (arduino/pair_device/pair_device.ino)

```cpp
// Pair an ESP32 with packeroo: ask for a code, show it, keep the token in flash, and ask
// GET /device every 5 seconds until someone enters the code in the app.
// Arduino core for ESP32 (2.x or 3.x) and the library ArduinoJson 7.
//
// Fill in WIFI_SSID and WIFI_PASSWORD. BASE_URL points at the sandbox. This sketch prints to the
// serial monitor; for a display, draw the same texts with a library such as TFT_eSPI or U8g2,
// and the link as a QR code with a library such as QRCode (ricmoo).

#include <Arduino.h>
#include <ArduinoJson.h>
#include <HTTPClient.h>
#include <Preferences.h>
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <esp_random.h>
#include <time.h>

// What the device shows, in the language of the location.
const char *TEXT_CODE = "Code am Tisch: %s %s\n";
const char *TEXT_LINK = "QR-Code mit diesem Link: %s/verbinden?code=%s\n";
const char *TEXT_ENTER = "Code eingeben in der packeroo-App unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“, oder den QR-Code mit dem Handy scannen.";
const char *TEXT_EXPIRED = "Der Code ist abgelaufen. Ich hole einen neuen.";
const char *TEXT_UNPAIRED = "Das gespeicherte Token gilt nicht mehr. Ich hole einen neuen Code.";
const char *TEXT_OFF = "Tischgeräte sind bei packeroo gerade ausgeschaltet. Neuer Versuch in 60 s.";
const char *TEXT_PAIRED = "Verbunden mit %s\n";
const char *TEXT_ERROR = "Fehler %d %s, neuer Versuch in %lu s\n";

const char *WIFI_SSID = "";
const char *WIFI_PASSWORD = "";
const char *BASE_URL = "https://api.qm.packeroo.com/api/v1";
const char *APP_URL = "https://app.qm.packeroo.com";
// Every request names the device: product and firmware.
const char *USER_AGENT = "Kickertisch-ESP32/1.0";
const unsigned long POLL_MS = 5000;
// After errors in a row the pause doubles, up to one minute.
const unsigned long MAX_PAUSE_MS = 60000;

// The roots api.packeroo.com and api.qm.packeroo.com chain up to (Let's Encrypt): ISRG Root X1
// (RSA, valid until 2035) and ISRG Root X2 (ECDSA, valid until 2040). If the chain of the API
// changes to a root not listed here, add it and ship a firmware update.
const char *ROOT_CERTIFICATES =
    "-----BEGIN CERTIFICATE-----\n"
    "MIIFazCCA1OgAwIBAgIRAIIQz7DSQONZRGPgu2OCiwAwDQYJKoZIhvcNAQELBQAw\n"
    "TzELMAkGA1UEBhMCVVMxKTAnBgNVBAoTIEludGVybmV0IFNlY3VyaXR5IFJlc2Vh\n"
    "cmNoIEdyb3VwMRUwEwYDVQQDEwxJU1JHIFJvb3QgWDEwHhcNMTUwNjA0MTEwNDM4\n"
    "WhcNMzUwNjA0MTEwNDM4WjBPMQswCQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJu\n"
    "ZXQgU2VjdXJpdHkgUmVzZWFyY2ggR3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBY\n"
    "MTCCAiIwDQYJKoZIhvcNAQEBBQADggIPADCCAgoCggIBAK3oJHP0FDfzm54rVygc\n"
    "h77ct984kIxuPOZXoHj3dcKi/vVqbvYATyjb3miGbESTtrFj/RQSa78f0uoxmyF+\n"
    "0TM8ukj13Xnfs7j/EvEhmkvBioZxaUpmZmyPfjxwv60pIgbz5MDmgK7iS4+3mX6U\n"
    "A5/TR5d8mUgjU+g4rk8Kb4Mu0UlXjIB0ttov0DiNewNwIRt18jA8+o+u3dpjq+sW\n"
    "T8KOEUt+zwvo/7V3LvSye0rgTBIlDHCNAymg4VMk7BPZ7hm/ELNKjD+Jo2FR3qyH\n"
    "B5T0Y3HsLuJvW5iB4YlcNHlsdu87kGJ55tukmi8mxdAQ4Q7e2RCOFvu396j3x+UC\n"
    "B5iPNgiV5+I3lg02dZ77DnKxHZu8A/lJBdiB3QW0KtZB6awBdpUKD9jf1b0SHzUv\n"
    "KBds0pjBqAlkd25HN7rOrFleaJ1/ctaJxQZBKT5ZPt0m9STJEadao0xAH0ahmbWn\n"
    "OlFuhjuefXKnEgV4We0+UXgVCwOPjdAvBbI+e0ocS3MFEvzG6uBQE3xDk3SzynTn\n"
    "jh8BCNAw1FtxNrQHusEwMFxIt4I7mKZ9YIqioymCzLq9gwQbooMDQaHWBfEbwrbw\n"
    "qHyGO0aoSCqI3Haadr8faqU9GY/rOPNk3sgrDQoo//fb4hVC1CLQJ13hef4Y53CI\n"
    "rU7m2Ys6xt0nUW7/vGT1M0NPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
    "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBR5tFnme7bl5AFzgAiIyBpY9umbbjANBgkq\n"
    "hkiG9w0BAQsFAAOCAgEAVR9YqbyyqFDQDLHYGmkgJykIrGF1XIpu+ILlaS/V9lZL\n"
    "ubhzEFnTIZd+50xx+7LSYK05qAvqFyFWhfFQDlnrzuBZ6brJFe+GnY+EgPbk6ZGQ\n"
    "3BebYhtF8GaV0nxvwuo77x/Py9auJ/GpsMiu/X1+mvoiBOv/2X/qkSsisRcOj/KK\n"
    "NFtY2PwByVS5uCbMiogziUwthDyC3+6WVwW6LLv3xLfHTjuCvjHIInNzktHCgKQ5\n"
    "ORAzI4JMPJ+GslWYHb4phowim57iaztXOoJwTdwJx4nLCgdNbOhdjsnvzqvHu7Ur\n"
    "TkXWStAmzOVyyghqpZXjFaH3pO3JLF+l+/+sKAIuvtd7u+Nxe5AW0wdeRlN8NwdC\n"
    "jNPElpzVmbUq4JUagEiuTDkHzsxHpFKVK7q4+63SM1N95R1NbdWhscdCb+ZAJzVc\n"
    "oyi3B43njTOQ5yOf+1CceWxG1bQVs5ZufpsMljq4Ui0/1lvh+wjChP4kqKOJ2qxq\n"
    "4RgqsahDYVvTH9w7jXbyLeiNdd8XM2w9U/t7y0Ff/9yi0GE44Za4rF2LN9d11TPA\n"
    "mRGunUHBcnWEvgJBQl9nJEiU0Zsnvgc/ubhPgXRR4Xq37Z0j4r7g1SgEEzwxA57d\n"
    "emyPxgcYxn/eR44/KJ4EBs+lVDR3veyJm+kXQ99b21/+jh5Xos1AnX5iItreGCc=\n"
    "-----END CERTIFICATE-----\n"
    "-----BEGIN CERTIFICATE-----\n"
    "MIICGzCCAaGgAwIBAgIQQdKd0XLq7qeAwSxs6S+HUjAKBggqhkjOPQQDAzBPMQsw\n"
    "CQYDVQQGEwJVUzEpMCcGA1UEChMgSW50ZXJuZXQgU2VjdXJpdHkgUmVzZWFyY2gg\n"
    "R3JvdXAxFTATBgNVBAMTDElTUkcgUm9vdCBYMjAeFw0yMDA5MDQwMDAwMDBaFw00\n"
    "MDA5MTcxNjAwMDBaME8xCzAJBgNVBAYTAlVTMSkwJwYDVQQKEyBJbnRlcm5ldCBT\n"
    "ZWN1cml0eSBSZXNlYXJjaCBHcm91cDEVMBMGA1UEAxMMSVNSRyBSb290IFgyMHYw\n"
    "EAYHKoZIzj0CAQYFK4EEACIDYgAEzZvVn4CDCuwJSvMWSj5cz3es3mcFDR0HttwW\n"
    "+1qLFNvicWDEukWVEYmO6gbf9yoWHKS5xcUy4APgHoIYOIvXRdgKam7mAHf7AlF9\n"
    "ItgKbppbd9/w+kHsOdx1ymgHDB/qo0IwQDAOBgNVHQ8BAf8EBAMCAQYwDwYDVR0T\n"
    "AQH/BAUwAwEB/zAdBgNVHQ4EFgQUfEKWrt5LSDv6kviejM9ti6lyN5UwCgYIKoZI\n"
    "zj0EAwMDaAAwZQIwe3lORlCEwkSHRhtFcP9Ymd70/aTSVaYgLXTWNLxBo1BfASdW\n"
    "tL4ndQavEi51mI38AjEAi/V3bNTIZargCyzuFJ0nN6T5U6VR5CmD1/iQMVtCnwr1\n"
    "/q4AaOeMSQ+2b1tbFfLn\n"
    "-----END CERTIFICATE-----\n";

Preferences store;  // The token lives in NVS, never in the sketch.
String token;
unsigned long expiresAtMs = 0;  // millis() when the shown code runs out; 0 when no code is waiting
bool waitingForCode = false;
unsigned long pauseMs = POLL_MS;  // the next pause after an error, doubled with every error in a row

// Waits after a network error, a 5xx or an unexpected answer, and doubles the next pause up to
// MAX_PAUSE_MS. The sketch never asks the API again without a pause.
void pauseAfterError(int status, const char *problem) {
  Serial.printf(TEXT_ERROR, status, problem, pauseMs / 1000);
  delay(pauseMs);
  pauseMs = min(pauseMs * 2, MAX_PAUSE_MS);
}

WiFiClientSecure tls;

// One request. Returns the status (negative on a network error), the body in `body`.
int call(const char *method, const char *path, const String &json, const String &idempotencyKey, String &body, int &retryAfter) {
  HTTPClient http;
  http.begin(tls, String(BASE_URL) + path);
  http.setUserAgent(USER_AGENT);
  http.addHeader("Accept", "application/json");
  http.addHeader("Accept-Language", "de");
  if (token.length() > 0) http.addHeader("Authorization", "Bearer " + token);
  // A write carries an Idempotency-Key; a retry of the same request sends the same key.
  if (idempotencyKey.length() > 0) http.addHeader("Idempotency-Key", idempotencyKey);
  const char *wanted[] = {"Retry-After"};
  http.collectHeaders(wanted, 1);

  int status;
  if (json.length() > 0) {
    http.addHeader("Content-Type", "application/json");
    status = http.sendRequest(method, json);
  } else {
    status = http.sendRequest(method);
  }
  body = status > 0 ? http.getString() : "";
  // Retry-After in seconds; the API sends seconds, so an HTTP date falls back to 60.
  retryAfter = http.header("Retry-After").toInt();
  if (retryAfter <= 0) retryAfter = 60;
  http.end();
  return status;
}

String newKey() {
  uint8_t b[16];
  esp_fill_random(b, sizeof b);
  b[6] = (b[6] & 0x0f) | 0x40;
  b[8] = (b[8] & 0x3f) | 0x80;
  char key[37];
  snprintf(key, sizeof key, "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",
           b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7], b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]);
  return String(key);
}

// Show these on the display of the table: the code as two groups of three, and the link as a QR code.
void showCode(const String &code) {
  Serial.println();
  Serial.printf(TEXT_CODE, code.substring(0, 3).c_str(), code.substring(3).c_str());
  Serial.printf(TEXT_LINK, APP_URL, code.c_str());
  Serial.println(TEXT_ENTER);
  Serial.println();
}

// Asks for a code. Returns true when there is a code to wait for or the token is paired already;
// false on an answer the sketch cannot act on, after a pause.
bool requestCode() {
  String key = newKey();
  for (;;) {
    String body;
    int retryAfter;
    int status = call("POST", "/device-pairings", "{\"model\":\"Kickertisch-ESP32\",\"firmware\":\"1.0\"}", key, body, retryAfter);
    JsonDocument answer;
    deserializeJson(answer, body);
    const char *problem = answer["code"] | "";

    if (status == 201) {
      token = answer["data"]["token"].as<String>();
      // Shown only this once: keep it before anything else.
      store.putString("token", token);
      // The code is valid for 10 minutes; counted from now with millis(), a few seconds early.
      expiresAtMs = millis() + 10UL * 60UL * 1000UL - 5000UL;
      waitingForCode = true;
      pauseMs = POLL_MS;
      showCode(answer["data"]["code"].as<String>());
      return true;
    }
    if (status == 409 && strcmp(problem, "device_already_paired") == 0) {
      waitingForCode = false;
      pauseMs = POLL_MS;
      return true;
    }
    if (status == 409 && strcmp(problem, "table_devices_off") == 0) {
      Serial.println(TEXT_OFF);
      delay(60000);
    } else if (status == 429) {
      delay(retryAfter * 1000UL);
    } else if (status < 0 || status >= 500) {
      // No network, or the API is busy or being deployed: the same request with the same key.
      pauseAfterError(status, problem);
    } else {
      pauseAfterError(status, problem);
      return false;
    }
  }
}

// GET /device: 1 paired, 0 not yet, -1 the code ran out, -2 unpaired (401 with no code waiting),
// -3 no network, a 5xx or another answer. Only 401 means "not paired": after -3 the code stays,
// someone may be typing it right now. Unattended, the sketch has nobody to stop for: on an answer
// it cannot act on it prints the status and its problem code, and asks again after a pause.
int checkPaired() {
  String body;
  int retryAfter;
  int status = call("GET", "/device", "", "", body, retryAfter);
  if (status == 200) {
    JsonDocument device;
    deserializeJson(device, body);
    Serial.printf(TEXT_PAIRED, device["data"]["table"]["name"] | "?");
    return 1;
  }
  if (status == 429) {
    delay(retryAfter * 1000UL);
    return 0;
  }
  if (status == 401) {
    if (!waitingForCode) return -2;
    if ((long)(millis() - expiresAtMs) >= 0) return -1;
    return 0;
  }
  // No network, a 5xx or another answer: keep the code, ask again after a pause.
  JsonDocument problem;
  deserializeJson(problem, body);
  pauseAfterError(status, problem["code"] | "");
  return -3;
}

bool paired = false;
bool needCode = false;  // true while a new code has to be asked for

void setup() {
  Serial.begin(115200);
  WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) delay(250);

  // The certificate check needs the right time; take it from NTP before the first request.
  configTime(0, 0, "pool.ntp.org", "time.nist.gov");
  while (time(nullptr) < 1700000000) delay(250);
  tls.setCACert(ROOT_CERTIFICATES);

  store.begin("packeroo", false);
  token = store.getString("token", "");
  if (token.length() > 0) paired = checkPaired() == 1;
  // Not paired, or no answer yet: ask for a code with the stored token; a paired one gets 409.
  needCode = !paired;
}

void loop() {
  if (paired) {
    // From here the table reports to packeroo; the next operations are planned.
    delay(60000);
    return;
  }
  if (needCode) {
    // requestCode() has paused already when it gives up; loop() asks again with a new key.
    if (!requestCode()) return;
    needCode = false;
  }
  int state = checkPaired();
  if (state == 1) {
    paired = true;
  } else if (state == -2) {
    // Paired a moment ago, unpaired now: this token is of no use any more.
    Serial.println(TEXT_UNPAIRED);
    token = "";
    store.remove("token");
    needCode = true;
  } else if (state == -1) {
    Serial.println(TEXT_EXPIRED);
    needCode = true;
  } else if (state == 0) {
    pauseMs = POLL_MS;
    delay(POLL_MS);
  }
  // -3: checkPaired() has paused already.
}
```

Die Ausgaben der Beispiele sind deutsch, weil die App, in der der Code eingegeben wird, deutsch beschriftet ist. Für dein Gerät nimm die Sprache des Standorts.

## Code anfordern

```http
POST /api/v1/device-pairings
User-Agent: Kickertisch/1.2
Idempotency-Key: 0d1c6f8e-3b9a-4c55-9e1f-7a2b4c6d8e90
Content-Type: application/json
Accept-Language: de

{"model": "Kickertisch", "serial": "KT-0042", "firmware": "1.2"}
```

- **`User-Agent`** ist Pflicht und nennt Produkt und Firmware, etwa `Kickertisch/1.2`. Ohne ihn kommt `400` mit `user_agent_required`.
- **`Idempotency-Key`** ist Pflicht für jede schreibende Anfrage, eine UUID oder ULID, neu für jede Anfrage. Scheitert eine Anfrage am Netz, schick sie mit demselben Schlüssel noch einmal.
- **Der Body** ist freiwillig. `model` und `serial` dürfen je 80 Zeichen lang sein, `firmware` 40. Die App zeigt sie in der Liste des Tischs, damit man das Gerät wiedererkennt.
- **`Authorization: Bearer …`** schickt das Gerät nur mit, wenn es schon ein Token hat, etwa weil der letzte Code abgelaufen ist. Dann gibt es den alten Code auf und bekommt einen neuen.

Die Antwort mit `201`:

```json
{
  "data": {
    "code": "K7F4QX",
    "expires_at": "2026-11-22T14:15:00Z",
    "token": "pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD"
  }
}
```

Der Code gilt zehn Minuten, bis `expires_at` (UTC). Das Token bekommst du nur in dieser Antwort; sie trägt `Cache-Control: no-store`, und auch der Server hebt sie unter dem Idempotency-Key nicht auf. Schickst du dieselbe Anfrage noch einmal, bekommst du deshalb einen neuen Code und ein neues Token. Nimm immer das zuletzt erhaltene.

## Code und QR-Code zeigen

Zeig den Code als zwei Gruppen zu drei Zeichen: **K7F 4QX**. Codes bestehen aus Großbuchstaben und Ziffern ohne die leicht verwechselten Zeichen 0, O, 1, I, L, 5 und S. Wer tippt, darf Leerzeichen, Bindestriche und Kleinbuchstaben verwenden; die App rechnet das um.

Der QR-Code enthält einen Link in die App, der auf `/verbinden?code=` endet:

| Umgebung | Inhalt des QR-Codes |
| --- | --- |
| Live | `https://app.packeroo.com/verbinden?code=K7F4QX` |
| Sandbox | `https://app.qm.packeroo.com/verbinden?code=K7F4QX` |

Scannt man ihn mit der Kamera des Handys, öffnet sich in der App die Seite `/verbinden` mit dem Code schon eingetragen. Eine Bibliothek für QR-Codes gibt es für jede Sprache, etwa `qrcode` für Python, `qrcode` für Node.js oder `QRCoder` für .NET. Das Python-Beispiel zeichnet den QR-Code ins Terminal, wenn `qrcode` installiert ist (`pip install qrcode`), und zeigt sonst den Link.

## Token sicher ablegen

Das Token ist der Schlüssel deines Geräts. Wer es hat, meldet sich als dieses Gerät an.

- **Leg es in eine Datei, die nur der Benutzer des Geräts lesen kann**, unter Linux mit den Rechten `600` (`-rw-------`) in einem Verzeichnis mit `700`. Schreib erst eine temporäre Datei und benenn sie dann um, damit nach einem Stromausfall nie eine halbe Datei liegt. Die Beispiele machen genau das.
- **Nicht in den Quelltext, nicht ins Log, nicht in eine URL.** Wenn du es zur Fehlersuche zeigen willst, zeig die ersten 13 Zeichen, etwa `pkd_test_7Hq2`; so zeigt es auch die App.
- **Am Präfix erkennst du die Umgebung:** `pkd_live_` gilt nur live, `pkd_test_` nur in der Sandbox. Ein Token der falschen Umgebung lehnt die API ab, als gäbe es keins.
- **Nicht ins Repository.** Der Standardpfad `~/.config/packeroo/device-token` liegt außerhalb deines Projekts. Legst du die Datei in den Projektordner, trag sie in die `.gitignore` ein:

  ```text
  device-token
  device-token.tmp
  ```
- **Wer das Token sieht:** niemand im Ganzen. Wer den Standort verwaltet, sieht in der App beim Gerät seine Kennung, die ersten 13 Zeichen wie `pkd_test_7Hq2`, damit man Geräte auseinanderhält.
- **Die Prüfsumme** am Ende lässt Secret-Scanner ein geleaktes Token erkennen, etwa in einem veröffentlichten Repository.

### Warum das Token nicht abläuft

Ein Tischgerät läuft oft lange ohne Tastatur und ohne jemanden, der danebensteht. Ein Token mit Ablaufdatum würde den Tisch irgendwann aussperren, und wer ein Backup der SD-Karte zurückspielt, hätte ein veraltetes. Deshalb gilt das Token, bis das Gerät getrennt wird. Ein Austausch des Tokens im laufenden Betrieb ist geplant.

Setzt du das Gerät neu auf oder steckst eine neue SD-Karte ein, verbindest du es neu. Sobald das neue Gerät am Tisch verbunden ist, gilt das alte Token nicht mehr.

### Verloren oder gestohlen

Trenn das Gerät in der App: unter Profil › Organisation › Tische, dort am Tisch „Gerät verbinden“ beim Gerät „Trennen …“. Das Token gilt danach sofort nicht mehr. Ein Gerät, das sich 90 Tage nicht meldet, trennt packeroo von selbst.

## Auf die Verbindung warten

Frag `GET /device` alle fünf Sekunden, mit dem Token und dem `User-Agent`:

```http
GET /api/v1/device
User-Agent: Kickertisch/1.2
Authorization: Bearer pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD
```

- **`401`** mit `unauthenticated`: Der Code ist noch nicht eingegeben. Weiter warten.
- **`200`**: Das Gerät ist verbunden. Die Antwort nennt Tisch, Standort mit Zeitzone und Organisation.
- **Nach `expires_at`** kommt weiter `401`, weil niemand den alten Code mehr eingeben kann. Fordere einen neuen an und schick dabei das Token mit, das du gerade hast.

Ein Gerät darf `GET /device` 120-mal in der Minute fragen; alle fünf Sekunden sind zwölf. Eine Verbindung über einen Socket gibt es für Geräte noch nicht.

## Beim Neustart

Startet das Gerät neu, fragt es zuerst mit dem gespeicherten Token `GET /device`:

- `200`: Es ist verbunden und macht weiter.
- `401`: Es ist nicht oder nicht mehr verbunden. Es fordert einen neuen Code an und schickt dabei das gespeicherte Token mit.
- Keine Antwort, `5xx` oder eine andere Antwort: Es fragt nach einer Pause noch einmal. Nur `401` heißt „nicht verbunden“.

Ein Gerät wird getrennt, wenn jemand es in der App trennt, ein anderes Gerät an seinem Tisch verbindet, der Tisch archiviert wird oder es sich 90 Tage nicht meldet. Danach antwortet `GET /device` mit `401`, und das Gerät verbindet sich wie beim ersten Mal.

Still getrennt wird kein Gerät: Meldet es sich 24 Stunden nicht, bekommen alle, die den Standort verwalten, eine Benachrichtigung, und die App zeigt beim Gerät, an welchem Tag es getrennt wird, wenn es still bleibt. Mehr dazu unter [Sicherheit und Datenschutz](https://developers.packeroo.com/sicherheit-und-datenschutz/#wann-ein-geraet-getrennt-wird).

## Fehlerfälle

Jeder Fehler kommt als Problem nach RFC 9457 mit einem festen `code`. Verzweige immer nach `code`, nie nach dem Text in `detail`; der folgt der Sprache aus `Accept-Language` (Deutsch oder Englisch, ohne Angabe Deutsch).

| Fall | Antwort | Was das Gerät tut |
| --- | --- | --- |
| Code abgelaufen | `GET /device` bleibt nach `expires_at` bei `401` | neuen Code anfordern, mit dem aktuellen Token als Bearer |
| Schon verbunden | `POST /device-pairings` mit Token: `409` `device_already_paired` | das Token behalten und `GET /device` fragen |
| Tischgeräte ausgeschaltet | `POST`: `409` `table_devices_off`; `GET /device`: `401` | „Tischgeräte sind ausgeschaltet“ zeigen, in Abständen von einer Minute neu versuchen |
| Kein User-Agent | `400` `user_agent_required` | den Header setzen, das ist ein Fehler im Programm |
| Kein oder falscher Idempotency-Key | `400` `idempotency_key_required` | eine UUID oder ULID mitschicken |
| Gleicher Schlüssel, andere Anfrage | `422` `idempotency_key_reused` | für jede neue Anfrage einen neuen Schlüssel erzeugen |
| Gleiche Anfrage läuft noch | `409` `request_in_progress` | kurz warten, dann mit demselben Schlüssel noch einmal |
| Feld zu lang | `422` `validation_failed` mit `errors` je Feld | `model`, `serial`, `firmware` kürzen |
| Zu viele Anfragen | `429` `rate_limited` mit `Retry-After` | so viele Sekunden warten, wie `Retry-After` sagt |
| Keine Verbindung oder Serverfehler | Netzfehler oder `5xx`, oft ohne JSON (etwa während eines Deploys) | den Code behalten, nach einer Pause noch einmal fragen; die Pause verdoppelt sich bis 60 Sekunden |
| Gerät getrennt | `GET /device`: `401`, nachdem es `200` gab | neu verbinden, mit dem alten Token als Bearer |
| Schon verbunden, dann getrennt | `POST`: `409` `device_already_paired`, danach `GET /device`: `401` | das Token verwerfen und einen neuen Code ohne Token anfordern |

Tischgeräte schaltet der Owner einer Organisation in der App ein und aus. Solange sie aus sind, verbindet sich kein Gerät und keins meldet sich an.

## Rezept: Raspberry Pi am Tisch

Ein Raspberry Pi mit Display ist der schnellste Weg zu einem Tischgerät. Leg `pair_device.py` und `display.py` nebeneinander in `/home/pi/packeroo/`. `display.py` startet das Programm, zeigt den Code bildschirmfüllend und, wenn `python3-qrcode` und `python3-pil.imagetk` installiert sind, auch den QR-Code. Endet `pair_device.py` mit einem Fehler, startet `display.py` es nach 30 Sekunden neu.

raspberry-pi/display.py:

```python
"""Full-screen display for a Raspberry Pi at the table: runs pair_device.py next to this file and
shows what it prints, the code large, readable from two metres. With the packages qrcode and
Pillow installed (sudo apt install python3-qrcode python3-pil python3-pil.imagetk) it also shows
the QR code. Python 3.9 or newer with tkinter (sudo apt install python3-tk).

    python3 display.py

Should pair_device.py end with an error, display.py starts it again after RESTART_SECONDS and
shows until then what it printed last. Escape closes the window.
"""

import os
import queue
import re
import subprocess
import sys
import threading
import time
import tkinter as tk
from pathlib import Path

PAIR_DEVICE = Path(__file__).with_name("pair_device.py")
CODE = re.compile(r"Code am Tisch: ([A-Z0-9]{3} [A-Z0-9]{3})")
LINK = re.compile(r"https://\S+/verbinden\?code=[A-Z0-9]{6}")
# Seconds before pair_device.py starts again after it ended with an error.
RESTART_SECONDS = 30

# Light type on a dark ground, more than 4.5:1.
BACKGROUND, FOREGROUND, ACCENT = "#15160f", "#f6f6ef", "#d6d63a"

root = tk.Tk()
root.configure(background=BACKGROUND, cursor="none")
root.attributes("-fullscreen", True)
root.bind("<Escape>", lambda _: root.destroy())

height = root.winfo_screenheight()
code_label = tk.Label(root, text="", font=("DejaVu Sans Mono", height // 6, "bold"), fg=FOREGROUND, bg=BACKGROUND)
qr_label = tk.Label(root, bg=BACKGROUND)
status_label = tk.Label(root, text="", font=("DejaVu Sans", height // 28), fg=ACCENT, bg=BACKGROUND, wraplength=root.winfo_screenwidth() - 80, justify="center")
code_label.pack(expand=True)
qr_label.pack()
status_label.pack(expand=True)

def show_qr(link):
    try:
        import qrcode
        from PIL import ImageTk
    except ImportError:
        return
    image = qrcode.make(link, border=2).resize((height // 3, height // 3))
    qr_label.image = ImageTk.PhotoImage(image)
    qr_label.configure(image=qr_label.image)

def show(line):
    """One line of pair_device.py: the code, the link for the QR code, or a message in words."""
    if match := CODE.search(line):
        code_label.configure(text=match.group(1))
    elif match := LINK.search(line):
        show_qr(match.group(0))
    elif line.strip():
        if line.startswith("Verbunden"):
            code_label.configure(text="")
            qr_label.configure(image="")
        status_label.configure(text=line.strip())

def read_output():
    """Runs pair_device.py until it ends with 0, paired. After an error it waits and starts it again;
    without this the screen would keep the last line, and systemd would not notice."""
    # Unbuffered, so every line arrives as soon as pair_device.py prints it.
    environment = {**os.environ, "PYTHONUNBUFFERED": "1", "PYTHONIOENCODING": "utf-8"}
    while True:
        process = subprocess.Popen([sys.executable, str(PAIR_DEVICE)], stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding="utf-8", env=environment)
        for line in process.stdout:
            lines.put(line)
        if process.wait() == 0:
            return
        time.sleep(RESTART_SECONDS)

def show_waiting_lines():
    # tkinter belongs to its own thread; the reader hands the lines over through a queue.
    while not lines.empty():
        show(lines.get())
    root.after(200, show_waiting_lines)

lines = queue.Queue()
threading.Thread(target=read_output, daemon=True).start()
show_waiting_lines()
root.mainloop()
```

Damit der Pi nach jedem Start und nach einem Absturz von selbst wieder anzeigt, startet ihn systemd:

raspberry-pi/packeroo-device.service:

```ini
# Starts the display at the table after every boot and again after a crash of display.py.
# display.py itself starts pair_device.py again when that ends with an error.
# Copy to /etc/systemd/system/, then: sudo systemctl enable --now packeroo-device
[Unit]
Description=packeroo table device
Wants=network-online.target
# After the display manager, not graphical.target: that target wants this unit, so ordering
# after it would make a cycle that systemd breaks by dropping a job at boot.
After=network-online.target display-manager.service

[Service]
User=pi
WorkingDirectory=/home/pi/packeroo
Environment=PACKEROO_BASE_URL=https://api.qm.packeroo.com/api/v1
Environment=PACKEROO_TOKEN_FILE=/home/pi/.config/packeroo/device-token
Environment=DISPLAY=:0
ExecStart=/usr/bin/python3 /home/pi/packeroo/display.py
Restart=always
RestartSec=5

[Install]
WantedBy=graphical.target
```

```bash
sudo cp packeroo-device.service /etc/systemd/system/
sudo systemctl enable --now packeroo-device
```

**Nach einem Stromausfall** bleibt die Token-Datei liegen, weil sie in einem Schritt geschrieben wird. Der Pi startet, systemd startet `display.py`, das Programm fragt mit dem gespeicherten Token `GET /device` und meldet sich ohne neuen Code wieder an. Einen neuen Code zeigt es nur, wenn das Gerät inzwischen getrennt wurde.

## Lesbar am Tisch

Am Tisch wird im Stehen gelesen, aus zwei Metern, oft mitten im Spiel. Für die Anzeige deines Geräts gilt deshalb:

- **Kontrast nach WCAG 2.2 AA:** mindestens 4,5:1 für Text, 3:1 für große Schrift und Symbole.
- **Aus zwei Metern lesbar:** Der Code ist das Größte auf dem Bildschirm, in einer Schrift mit gleich breiten Ziffern, als zwei Dreiergruppen. Prüf es so, wie es benutzt wird: Stell dich zwei Meter vor das Display und lies den Code ab.
- **Nie nur Farbe:** „Verbunden“, „Code abgelaufen“ oder „Tischgeräte ausgeschaltet“ stehen als Wort auf dem Display, nicht nur als grüner oder roter Punkt.
- **Zeit zum Lesen:** Meldungen bleiben stehen, bis sich der Zustand ändert, oder so lange, wie man am Gerät einstellen kann.

## Was als Nächstes kommt

Geplant und noch nicht verfügbar: die Warteschlange eines Tischs lesen, ein Spiel am Tisch starten, Tore live melden, das Ergebnis vom Tisch melden und Spieler per Chip erkennen. Die Scopes dafür trägt das Token schon (`scopes` in `GET /device`), die Operationen kommen nach und nach. Jede neue steht im [Changelog](https://developers.packeroo.com/changelog/), am Tag, an dem sie öffentlich wird.

---

# Konzepte

> Wie die packeroo-API anmeldet, Wiederholungen sicher macht, Fehler meldet und begrenzt. Token-Präfixe, Idempotency-Key, Problemantworten nach RFC 9457, Ratenlimits, User-Agent, Zeiten und Versionen.

Diese Regeln gelten für jede öffentliche Operation. Was hier steht, ist gebaut; was geplant ist, ist so gekennzeichnet.

## Adressen

| Umgebung | Basisadresse | Tokens |
| --- | --- | --- |
| Live | `https://api.packeroo.com/api/v1` | `pkd_live_…` |
| Sandbox | `https://api.qm.packeroo.com/api/v1` | `pkd_test_…` |

Die Sandbox ist die Demo-Umgebung von packeroo. Sie kann zurückgesetzt werden; leg dort nichts ab, was du behalten willst. In der Sandbox verbindet sich ein Gerät selbst mit `POST /sandbox/device-pairings/confirm` an einem eigenen Testtisch, ohne dass jemand den Code in der App eingibt; siehe [Schnellstart](https://developers.packeroo.com/schnellstart/).

## Anmeldung und Token-Präfixe

Ein Gerät meldet sich mit seinem Token im Header an:

```http
Authorization: Bearer pkd_live_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD
```

Das Token ist eine zufällige Zeichenfolge, kein JWT: Es trägt keine Daten, und wird es getrennt, gilt es sofort nicht mehr. packeroo speichert nur seinen SHA-256-Hash und zeigt es genau einmal, in der Antwort auf `POST /device-pairings`.

Ein Token ist 47 Zeichen lang: ein Präfix, 32 zufällige Zeichen und eine Prüfsumme aus 6 Zeichen. Am Präfix erkennst du Art und Umgebung. Die Prüfsumme lässt Secret-Scanner ein geleaktes Token erkennen, und ein vertipptes lehnt die API ab, ohne nachzusehen.

| Präfix | Art | Stand |
| --- | --- | --- |
| `pkd_live_`, `pkd_test_` | Gerät an einem Tisch | verfügbar |
| `pko_live_`, `pko_test_` | Organisationsschlüssel für Intranet, Dashboards, Chat-Bots | geplant |
| `pkp_live_`, `pkp_test_` | persönliches Token | geplant |

Tokens gehören auf Geräte und Server, nie in eine Webseite. Die API nimmt Anfragen aus dem Browser nur von der packeroo-App an.

## Scopes

`GET /device` nennt in `scopes`, was das Token darf. Bei einem Gerätetoken ist das eine feste Menge: `leagues:read`, `standings:read`, `matches:read`, `matches:write`, `matches:live`. Sie enthält auch Scopes für Operationen, die geplant sind; wirksam werden diese erst, wenn es die Operationen gibt. Heute reicht das Token für `GET /device`. Kommt eine Operation dazu, muss ein verbundenes Gerät nicht neu verbunden werden: Sein Token hat die Scopes schon.

## Idempotency-Key

Jede schreibende Anfrage (`POST`, `PUT`, `PATCH`, `DELETE`) trägt den Header `Idempotency-Key` mit einer UUID oder ULID. Erzeug für jede neue Aktion einen neuen Schlüssel und schick bei einer Wiederholung, etwa nach einem Netzfehler, denselben.

- Dieselbe Anfrage mit demselben Schlüssel bekommt die erste Antwort noch einmal, mit dem Header `Idempotent-Replayed: true`, und wirkt nicht ein zweites Mal. Gespeichert werden nur erfolgreiche Antworten, 48 Stunden lang.
- Fehlt der Schlüssel oder ist er weder UUID noch ULID: `400` `idempotency_key_required`.
- Derselbe Schlüssel mit einer anderen Anfrage: `422` `idempotency_key_reused`.
- Läuft die erste Anfrage noch: `409` `request_in_progress`. Warte kurz und wiederhole sie mit demselben Schlüssel.
- Eine Antwort mit einem Geheimnis, wie das Token in `POST /device-pairings`, wird nie gespeichert. Eine Wiederholung läuft dort noch einmal und liefert einen neuen Code mit neuem Token.

## Fehlerantworten

Jeder Fehler kommt als Problem nach [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) mit dem Content-Type `application/problem+json`:

```json
{
  "type": "https://api.packeroo.com/problems/user-agent-required",
  "title": "User-Agent required",
  "status": 400,
  "detail": "Das Gerät nennt sich nicht. Jede Anfrage braucht einen User-Agent, zum Beispiel Kickertisch/1.2.",
  "code": "user_agent_required",
  "correlation_id": "01JD7R4X2Y3Z4A5B6C7D8E9F0G"
}
```

- **`code`** ist fest. Verzweige in deinem Programm nur nach `code`.
- **`title`** ist eine kurze englische Zusammenfassung, für jeden Code gleich.
- **`detail`** erklärt, was passiert ist und was zu tun ist, in der Sprache aus `Accept-Language`: `de` oder `en`, ohne Angabe Deutsch. Für die Anzeige gedacht, nicht zum Auswerten.
- **`correlation_id`** steht auch im Header `X-Correlation-Id` jeder Antwort. Nenn sie, wenn du uns wegen eines Fehlers schreibst.
- **`errors`** gibt es nur bei `validation_failed`: die Meldungen je Feld.

### Codes der öffentlichen Operationen

| Code | Status | Bedeutung |
| --- | --- | --- |
| `user_agent_required` | 400 | Der Anfrage fehlt der `User-Agent`. |
| `idempotency_key_required` | 400 | Der schreibenden Anfrage fehlt ein gültiger `Idempotency-Key`. |
| `bad_request` | 400 | Die Anfrage ist nicht lesbar, etwa kein gültiges UTF-8. |
| `unauthenticated` | 401 | Kein gültiges Token: noch nicht verbunden, getrennt, aus einer anderen Umgebung, oder Tischgeräte sind ausgeschaltet. |
| `not_found` | 404 | Die Operation gibt es hier nicht, etwa `POST /sandbox/device-pairings/confirm` außerhalb der Sandbox. |
| `device_already_paired` | 409 | Das Gerät, das einen Code anfordert, ist schon verbunden. Es behält sein Token. |
| `table_devices_off` | 409 | Tischgeräte sind ausgeschaltet; kein Gerät verbindet sich. |
| `request_in_progress` | 409 | Eine Anfrage mit demselben Idempotency-Key läuft noch. |
| `idempotency_key_reused` | 422 | Der Idempotency-Key gehört schon zu einer anderen Anfrage. |
| `validation_failed` | 422 | Ein Feld ist ungültig; `errors` nennt es. |
| `rate_limited` | 429 | Zu viele Anfragen; `Retry-After` nennt die Wartezeit in Sekunden. |
| `server_error` | 500 | Fehler bei packeroo. Die Ursache steht in unserem Log unter der `correlation_id`. |
| `unavailable` | 503 | packeroo ist kurz nicht erreichbar. Später noch einmal versuchen. |

## Ratenlimits

| Was | Grenze |
| --- | --- |
| `POST /device-pairings` | 60 in der Minute je IP-Adresse |
| `POST /sandbox/device-pairings/confirm` | 10 in der Stunde und 20 neue Testtische am Tag je IP-Adresse (IPv6 je /48) |
| `GET /device` | 120 in der Minute je Gerät |

Die Grenze für Codes zählt je IP-Adresse, die für `GET /device` je Gerät. Ein Beispiel: In einer Halle hängen 40 Tische hinter einer Adresse. Nach einem Stromausfall fordern alle gleichzeitig einen Code an, das sind 40 von 60 `POST` in der Minute. Danach fragt jedes Gerät alle fünf Sekunden `GET /device`, das sind 12 von 120 je Gerät; die 40 Geräte zählen dabei nicht zusammen. Bei mehr als 60 Tischen hinter einer Adresse bekommen die übrigen `429` mit `Retry-After` und fragen danach noch einmal; die Beispiele der Anleitung tun das von selbst. Wer die Grenze überschreitet, bekommt `429` mit `rate_limited` und dem Header `Retry-After` in Sekunden. Warte so lange, bevor du es noch einmal versuchst.

Geplant: die Header `RateLimit` und `RateLimit-Policy` nach dem IETF-Entwurf an jeder Antwort, und eigene Grenzen für Tore und Organisationsschlüssel, sobald es diese Operationen gibt.

## User-Agent

Jede Anfrage eines Geräts nennt im `User-Agent` sein Produkt und seine Firmware, etwa `Kickertisch/1.2` oder `Kickertisch-ESP32/0.9.3`. So lässt sich ein Gerät, das sich falsch verhält, in den Logs von den anderen unterscheiden, ohne dass jemand das Token ansehen muss. Ohne `User-Agent` antwortet die API mit `400` und `user_agent_required`.

## Zeiten

Zeiten kommen in ISO 8601 und immer in UTC, mit `Z` am Ende: `2026-11-22T14:15:00Z`. Zeig sie in der Zeitzone des Standorts an; `GET /device` nennt sie in `location.time_zone`, etwa `Europe/Berlin`. IDs sind ULIDs, 26 Zeichen, nach Zeit sortierbar.

## Versionierung

Die Version steht im Pfad: `/api/v1`. Innerhalb von `v1` kommen nur Ergänzungen dazu, neue Operationen, neue Felder, neue Fehlercodes. Programmiere so, dass unbekannte Felder in einer Antwort nichts kaputt machen. Was bestehende Programme brechen würde, kommt in eine neue Version `v2`.

Geplant: Was wegfällt, kündigen die Header `Deprecation` und `Sunset` an (RFC 8594), mindestens sechs Monate vorher. Für Operationen von Geräten, deren Firmware lange im Einsatz bleibt, zwölf Monate vorher und frühestens 24 Monate nach ihrer Veröffentlichung.

Neue Operationen und Änderungen stehen im [Changelog](https://developers.packeroo.com/changelog/), auch als RSS-Feed.

---

# Referenz

> Jede öffentliche Operation der packeroo-API mit Parametern, Antworten, Fehlercodes und Codebeispielen in curl, Python, JavaScript, PHP, Java, Kotlin, C#, Go, Ruby, Swift, Dart, Rust und PowerShell.

Die öffentlichen Operationen:

- [`POST /sandbox/device-pairings/confirm`](https://developers.packeroo.com/referenz/#tag/sandbox/POST/sandbox/device-pairings/confirm): Pair this device in the sandbox
- [`POST /device-pairings`](https://developers.packeroo.com/referenz/#tag/table-devices/POST/device-pairings): Ask to pair this device
- [`GET /device`](https://developers.packeroo.com/referenz/#tag/table-devices/GET/device): This device

Dieselben als Datei: [openapi.json](https://developers.packeroo.com/openapi.json), [openapi.yaml](https://developers.packeroo.com/openapi.yaml), diese Seite als [Markdown](https://developers.packeroo.com/referenz.md). Die interaktive Referenz darunter ist erzeugt aus [openapi.json](https://developers.packeroo.com/openapi.json), dem Vertrag, den packeroo aus dem Code der API erzeugt. Der Vertrag ist englisch, darum sind es auch die Texte der Referenz; die Anleitungen dieser Seite gibt es auf Deutsch. Bei jeder Operation wählst du die Sprache für das Codebeispiel, und oben steht die Sandbox als Server. Anfragen schickst du aus deinem eigenen Programm, nicht aus dieser Seite; wie das geht, steht im [Schnellstart](https://developers.packeroo.com/schnellstart/).

---

# Postman und OpenAPI

> Die öffentliche packeroo-API als OpenAPI 3.1 in JSON und YAML, die Postman-Collection mit Sandbox-Umgebung und der Import in Insomnia, Bruno und Hoppscotch.

Alle Dateien entstehen bei jedem Release aus demselben Vertrag wie die Referenz. Sie enthalten nur die öffentlichen Operationen und bleiben unter diesen Adressen.

## OpenAPI

| Datei | Adresse |
| --- | --- |
| OpenAPI 3.1, JSON | [/openapi.json](https://developers.packeroo.com/openapi.json) |
| OpenAPI 3.1, YAML | [/openapi.yaml](https://developers.packeroo.com/openapi.yaml) |

Ein offizielles SDK gibt es nicht. Für die Operationen von heute reicht ein HTTP-Client, wie ihn die [Beispiele](https://developers.packeroo.com/anleitung/tischgeraet-verbinden/#das-vollstaendige-programm) zeigen. Willst du trotzdem einen Client mit Typen, erzeugst du ihn aus der OpenAPI-Datei, etwa mit OpenAPI Generator (braucht Java):

```bash
npx @openapitools/openapi-generator-cli generate -i https://developers.packeroo.com/openapi.yaml -g python -o packeroo-client
```

Statt `python` nimmst du für deine Sprache `typescript-fetch`, `csharp`, `php`, `go` oder `java`. Erzeug den Client neu, wenn im [Changelog](https://developers.packeroo.com/changelog/) eine Operation dazukommt.

## Postman

| Datei | Adresse |
| --- | --- |
| Collection | [packeroo.postman_collection.json](https://developers.packeroo.com/packeroo.postman_collection.json) |
| Umgebung Sandbox | [packeroo-sandbox.postman_environment.json](https://developers.packeroo.com/packeroo-sandbox.postman_environment.json) |

So schickst du die erste Anfrage:

1. Lade beide Dateien herunter.
2. In Postman: **Import**, beide Dateien hineinziehen.
3. Oben rechts die Umgebung **packeroo Sandbox** wählen.
4. Unter **Table devices** die Anfrage **Ask to pair this device** öffnen und senden. Den `Idempotency-Key` erzeugt Postman bei jedem Senden neu (`{{$guid}}`).
5. Das `token` aus der Antwort in der Umgebung bei **token** einsetzen. Ab dann schickt jede Anfrage der Collection es als Bearer-Token.

Die Umgebung legt `token` als geheimen Wert an, damit Postman es nicht offen anzeigt. Teil die Umgebung nicht mit eingetragenem Token.

## Insomnia, Bruno, Hoppscotch

Diese Werkzeuge lesen die OpenAPI-Datei direkt:

- **Insomnia:** Import, dann „From URL“ mit `https://developers.packeroo.com/openapi.json` oder die heruntergeladene Datei.
- **Bruno:** Import Collection, dann „OpenAPI V3 Spec“ und die Datei wählen.
- **Hoppscotch:** Import, dann „OpenAPI“ und Datei oder Adresse angeben.

Die Basisadresse der Sandbox ist `https://api.qm.packeroo.com/api/v1`. Setz `User-Agent` auf den Namen deines Geräts, sonst antwortet die API mit `400`.

---

# Changelog

> Was sich an der öffentlichen packeroo-API ändert, mit Datum. Auch als RSS-Feed.

Neue Operationen, neue Felder und alles, was du an deinem Programm ändern musst. Den Feed abonnierst du unter [/changelog/feed.xml](https://developers.packeroo.com/changelog/feed.xml).

## 22. November 2026: Entwicklerseite und Tischgeräte verbinden

developers.packeroo.com ist online, auf Deutsch und Englisch. Die ersten drei Operationen sind öffentlich: `POST /device-pairings` fordert einen Code für ein Tischgerät an, `GET /device` nennt dem verbundenen Gerät seinen Tisch, Standort und seine Organisation, und in der Sandbox verbindet sich ein Gerät mit `POST /sandbox/device-pairings/confirm` selbst an einem eigenen Testtisch. Dazu gibt es die [Anleitung](https://developers.packeroo.com/anleitung/tischgeraet-verbinden/) mit dem vollständigen Programm in acht Sprachen, die [Referenz](https://developers.packeroo.com/referenz/), die Postman-Collection und den Vertrag als OpenAPI 3.1.

---

# Für KI-Assistenten

> llms.txt, llms-full.txt, jede Seite als Markdown und der OpenAPI-Vertrag an festen Adressen, damit Assistenten und Coding-Agents die packeroo-API richtig erklären.

Wenn du mit einem KI-Assistenten oder einem Coding-Agent programmierst, gib ihm diese Adressen. Sie ändern sich nicht und enthalten nur, was es wirklich gibt; geplante Teile sind als geplant markiert.

| Was | Adresse |
| --- | --- |
| Überblick mit Links | [/llms.txt](https://developers.packeroo.com/llms.txt) |
| Alle Seiten in einer Datei, mit OpenAPI | [/llms-full.txt](https://developers.packeroo.com/llms-full.txt) |
| Der Vertrag | [/openapi.json](https://developers.packeroo.com/openapi.json), [/openapi.yaml](https://developers.packeroo.com/openapi.yaml) |
| Jede Seite als Markdown | Adresse der Seite mit `.md`, etwa [/schnellstart.md](https://developers.packeroo.com/schnellstart.md) |

## So fragst du gut

Schreib in die Anfrage an den Assistenten, wofür du baust und in welcher Sprache, und häng die OpenAPI-Datei oder `llms-full.txt` an. Zum Beispiel:

```text
Lies https://developers.packeroo.com/llms-full.txt.
Schreib mir in Rust ein Programm für einen Raspberry Pi, das sich als Tischgerät mit packeroo verbindet:
Code anfordern, Token in einer Datei mit Rechten 600 ablegen, alle 5 Sekunden GET /device fragen.
Behandle alle Fehlercodes aus der Doku.
```

Prüf, was der Assistent schreibt, gegen die [Referenz](https://developers.packeroo.com/referenz/). Operationen, die dort nicht stehen, gibt es nicht.

---

# Sicherheit und Datenschutz

> Was ein Tischgerät an packeroo schickt, was packeroo davon speichert und wie lange, wie Tokens geschützt sind und wie du eine Sicherheitslücke meldest. Für Entwickler, IT und Datenschutz.

Diese Seite beschreibt, was die öffentliche API heute tut. Sie ergänzt die [Datenschutzerklärung von packeroo](https://packeroo.com/datenschutzerklaerung/), sie ersetzt sie nicht.

## Was ein Gerät sieht

Ein verbundenes Gerät liest mit `GET /device` nur, womit es verbunden ist: seinen Namen, den Tisch, den Standort mit Zeitzone, die Organisation und seine Scopes. Es sieht keine Personen, keine Spiele und keine Wertungen. Weitere Operationen kommen erst, wenn sie im [Changelog](https://developers.packeroo.com/changelog/) stehen.

## Was packeroo über ein Gerät speichert

| Was | Woher | Wie lange |
| --- | --- | --- |
| Hash des Tokens (SHA-256) und seine ersten Zeichen | `POST /device-pairings` | solange das Gerät verbunden ist, danach 30 Tage |
| `model`, `serial`, `firmware`, wenn das Gerät sie schickt | `POST /device-pairings` | wie oben |
| Name des Geräts | wer den Code in der App eingibt | wie oben |
| Zeit der letzten Anfrage | jede Anfrage mit dem Token | wie oben |
| Wer das Gerät verbunden oder getrennt hat, mit den ersten Zeichen des Tokens | die App, packeroo selbst | im Prüfprotokoll der Organisation, 24 Monate |
| Ein Code, der noch nicht eingegeben ist | `POST /device-pairings` | gilt zehn Minuten, gelöscht spätestens am nächsten Tag |

In der Sandbox vergibt packeroo den Namen des Geräts selbst, und das Prüfprotokoll hält dort einen Monat.

Das Token selbst speichert packeroo nicht. Es steht genau einmal in der Antwort auf `POST /device-pairings`. Geht es verloren, fordert das Gerät einen neuen Code an.

Die IP-Adresse einer Anfrage zählt für das Ratenlimit von `POST /device-pairings` und verfällt mit ihm nach einer Minute, bei `POST /sandbox/device-pairings/confirm` nach einer Stunde, und als Hash für die Testtische eines Tages nach einem Tag. Eine Antwort, die ein Gerät mit `Idempotency-Key` bekommen hat, hält packeroo 48 Stunden für eine Wiederholung bereit; eine Antwort mit einem Token nie.

## Wann ein Gerät getrennt wird

- Wer den Standort verwaltet, trennt es in der App. Das Token gilt sofort nicht mehr.
- An seinem Tisch wird ein anderes Gerät verbunden, oder der Tisch wird archiviert.
- In der Sandbox: Kommt ein neuer Testtisch dazu, wenn es schon 100 gibt, wird der älteste mit seinem Gerät getrennt.
- Das Gerät meldet sich 90 Tage nicht. Vorher erfährt es niemand überraschend: Meldet sich ein Gerät 24 Stunden nicht, bekommen alle, die den Standort verwalten, eine Benachrichtigung, und die App zeigt beim Gerät, an welchem Tag es getrennt wird, wenn es still bleibt.

Schaltet die Organisation Tischgeräte aus, trennt das kein Gerät: Solange sie aus sind, antwortet jedes Token mit `401`, danach meldet es sich wieder an. Die 90 Tage laufen in der Zeit nicht weiter.

## Tokens schützen

- Speichere das Token nur auf dem Gerät, in einer Datei, die nur das Programm lesen darf. Die [Beispiele](https://developers.packeroo.com/anleitung/tischgeraet-verbinden/) legen sie mit den Rechten `0600` an.
- Schick es nur über HTTPS an die Adressen aus den [Konzepten](https://developers.packeroo.com/konzepte/#adressen). Die Beispiele prüfen das Zertifikat, auch der ESP32-Sketch.
- Ein Token gehört nicht in eine Webseite, ein Repository oder ein Log. Die Prüfsumme am Ende lässt Secret-Scanner ein geleaktes Token erkennen.
- Ist ein Token in falsche Hände geraten, trenn das Gerät in der App und verbinde es neu.

## Eine Sicherheitslücke melden

Schreib an [info@packeroo.com](mailto:info@packeroo.com) mit dem Betreff „Sicherheit“. Beschreib, was du gefunden hast und wie es sich nachstellen lässt, und nenn die `correlation_id` einer Antwort, wenn du eine hast. Teste nur in der Sandbox und nur mit deinen eigenen Geräten.

---

# Glossar

> Die Begriffe der packeroo-API kurz erklärt, von Organisation und Standort über Tisch und Tischgerät bis zu Token, Scope, Sandbox und Idempotency-Key.

## Organisation, Standort, Tisch

- **Organisation:** Eine Firma, ein Verein oder eine Kneipe bei packeroo. Ihr gehören Standorte, Ligen und Geräte. `GET /device` nennt sie in `organization`.
- **Standort:** Ein Ort der Organisation mit Adresse und Zeitzone, etwa ein Büro oder eine Halle. Wer ihn verwaltet, verbindet dort Geräte. Im Vertrag `location`.
- **Tisch:** Ein Kickertisch, eine Dartscheibe oder ein anderer Spielort an einem Standort. Im Vertrag `table`, in der App „Tisch“.
- **Tischgerät:** Ein Gerät, das zu genau einem Tisch gehört und sich mit einem Gerätetoken anmeldet, etwa ein Raspberry Pi mit Display oder ein Kicker mit Torerkennung. Ein Tisch hat höchstens ein Gerät.

## Verbinden

- **Code:** Sechs Zeichen, die ein Gerät nach `POST /device-pairings` zeigt, zehn Minuten gültig. Wer den Standort verwaltet, gibt ihn in der App ein.
- **Verbinden, Trennen:** Verbinden macht ein Gerät zum Gerät eines Tischs, Trennen nimmt ihm sein Token. Siehe [Ein Tischgerät verbinden](https://developers.packeroo.com/anleitung/tischgeraet-verbinden/).
- **Tischgeräte ausschalten:** Eine Organisation kann alle ihre Geräte auf einmal ausschalten. Solange sie aus sind, verbindet sich keines, und jedes Token bekommt `401`.

## Anmeldung

- **Token:** Die geheime Zeichenfolge, mit der sich ein Gerät anmeldet, als `Authorization: Bearer …`. Gerätetokens beginnen mit `pkd_live_` oder in der Sandbox mit `pkd_test_`. Siehe [Konzepte](https://developers.packeroo.com/konzepte/#anmeldung-und-token-praefixe).
- **Scope:** Ein Recht eines Tokens, etwa `matches:write`. `GET /device` nennt sie in `scopes`.
- **Organisationsschlüssel:** Geplant. Ein Token für Server einer Organisation, etwa für Intranet oder Dashboards, mit dem Präfix `pko_`.

## Anfragen

- **Idempotency-Key:** Eine UUID oder ULID im gleichnamigen Header jeder schreibenden Anfrage. Dieselbe Anfrage mit demselben Schlüssel wirkt nur einmal.
- **Problem:** Eine Fehlerantwort nach RFC 9457 mit festem `code`. Siehe [Fehlerantworten](https://developers.packeroo.com/konzepte/#fehlerantworten).
- **correlation_id:** Die Kennung einer Anfrage, in jeder Fehlerantwort und im Header `X-Correlation-Id`. Nenn sie, wenn du uns schreibst.
- **Sandbox:** Die Demo-Umgebung unter `https://api.qm.packeroo.com/api/v1` mit `pkd_test_`-Tokens, zum Ausprobieren. Sie kann zurückgesetzt werden.

---

# OpenAPI (YAML)

```yaml
openapi: 3.1.2
info:
  title: packeroo API
  version: "1"
  description: "The public part of the packeroo API. Today it pairs a table device, such as a scoring table, with a table of a location; more operations follow. Guides, examples and the sandbox: https://developers.packeroo.com"
  contact:
    name: packeroo for developers
    email: info@packeroo.com
    url: https://developers.packeroo.com
servers:
  - url: https://api.qm.packeroo.com/api/v1
    description: Sandbox (test keys, pkd_test_…)
  - url: https://api.packeroo.com/api/v1
    description: Live
tags:
  - name: Sandbox
  - name: Table devices
paths:
  /sandbox/device-pairings/confirm:
    servers:
      - url: https://api.qm.packeroo.com/api/v1
        description: Sandbox (test keys, pkd_test_…)
    post:
      operationId: device.pairInSandbox
      description: |-
        Only in the sandbox (https://api.qm.packeroo.com/api/v1): instead of somebody entering the
        code in the app, the device claims it itself. It sends the token it got from
        `POST /device-pairings` as `Authorization: Bearer …` and is paired at once with a table of its
        own at the sandbox location; the answer is the device as `GET /device` gives it, which answers
        from now on. Live, and everywhere but the sandbox, the answer is 404 `not_found`, but only for
        an otherwise valid request: the `User-Agent` (400 `user_agent_required`) and the
        `Idempotency-Key` (400 `idempotency_key_required`) are checked first.

        A device paired in the sandbox already gets itself back, at the same table. A token with no
        code waiting, because it ran out or was never asked for, gets 401 `unauthenticated`: ask for a
        code again. So does the token of a device paired at a table outside the sandbox, which this
        operation never moves or shows: it asks `GET /device`. 409 `table_devices_off` while table
        devices are off. While the sandbox itself is not ready (it is being set up again),
        the answer is 503 `unavailable`: try again later.

        The sandbox keeps the latest 100 tables; when a new one comes, the oldest that no league plays
        at is archived and its device unpaired. It takes 10 requests an hour and makes 20 new tables a
        day per IP address (an IPv6 address by its /48); above that the answer is 429 `rate_limited`
        with `Retry-After`.
      summary: Pair this device in the sandbox
      tags:
        - Sandbox
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          description: "A ULID or UUID the client creates for this action. Repeating the request with the same key returns the first answer again, with `Idempotent-Replayed: true`, and has no second effect."
          schema:
            type: string
        - name: User-Agent
          in: header
          required: true
          description: The product and firmware of the device, such as `Kickertisch/1.2`, so a misbehaving one can be told apart. Without it the answer is 400 `user_agent_required`.
          schema:
            type: string
          example: Kickertisch/1.2
      responses:
        "200":
          description: "`DeviceResource`"
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: "#/components/schemas/DeviceResource"
                required:
                  - data
        "400":
          description: Malformed request, or the idempotency key is missing (`idempotency_key_required`), or the device sends no `User-Agent` (`user_agent_required`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "401":
          description: "Unauthenticated, or no code waits for the token and no device of the sandbox is paired with it: its code ran out or was never asked for, or the device belongs to a table outside the sandbox (`unauthenticated`)"
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "404":
          description: "Not the sandbox: this operation answers only at https://api.qm.packeroo.com/api/v1 (`not_found`)"
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "409":
          description: Conflict with the current state, or a request with the same idempotency key is still running (`request_in_progress`), or table devices are switched off, for the platform or by the owner of the sandbox (`table_devices_off`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "422":
          description: Validation failed (`validation_failed`), or the idempotency key was used for another request (`idempotency_key_reused`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "429":
          description: Too many requests (`rate_limited`), with `Retry-After`
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "503":
          description: The sandbox is being set up again; try again later (`unavailable`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
      security:
        - deviceToken: []
      x-public: true
      x-sandbox-only: true
  /device-pairings:
    post:
      operationId: device.pair
      description: |-
        For a device such as a scoring table: a code of six characters to show, valid for
        ten minutes, and its token, given only this once. Whoever looks after the location enters the
        code at a table in the packeroo app; from then on the token signs the
        device in as `Authorization: Bearer …`, and `GET /device` answers. A device that asks again
        with its earlier token gives up its earlier code; one whose code was claimed meanwhile gets
        409 `device_already_paired` and keeps its token, or 409 `table_devices_off` while its
        organization has table devices switched off, and waits. Every request of a device names it in its
        `User-Agent`, such as `Kickertisch/1.2`, or gets 400 `user_agent_required`.
      summary: Ask to pair this device
      tags:
        - Table devices
      parameters:
        - name: Idempotency-Key
          in: header
          required: true
          description: "A ULID or UUID the client creates for this action. Repeating the request with the same key returns the first answer again, with `Idempotent-Replayed: true`, and has no second effect."
          schema:
            type: string
        - name: User-Agent
          in: header
          required: true
          description: The product and firmware of the device, such as `Kickertisch/1.2`, so a misbehaving one can be told apart. Without it the answer is 400 `user_agent_required`.
          schema:
            type: string
          example: Kickertisch/1.2
      requestBody:
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/StartDevicePairingRequest"
      responses:
        "201":
          description: "`DevicePairingResource`"
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: "#/components/schemas/DevicePairingResource"
                required:
                  - data
        "400":
          description: Malformed request, or the idempotency key is missing (`idempotency_key_required`), or the device sends no `User-Agent` (`user_agent_required`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "409":
          description: Conflict with the current state, or a request with the same idempotency key is still running (`request_in_progress`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "422":
          description: Validation failed (`validation_failed`), or the idempotency key was used for another request (`idempotency_key_reused`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "429":
          description: Too many requests (`rate_limited`), with `Retry-After`
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
      security:
        - {}
        - deviceToken: []
      x-public: true
  /device:
    get:
      operationId: device.show
      description: |-
        The paired device that asks: its table, location and organization, and what its token may
        do. A device that is not paired, or no longer, gets 401 and asks to be paired again; so does
        every device while table devices are switched off for its organization.
      summary: This device
      tags:
        - Table devices
      parameters:
        - name: User-Agent
          in: header
          required: true
          description: The product and firmware of the device, such as `Kickertisch/1.2`, so a misbehaving one can be told apart. Without it the answer is 400 `user_agent_required`.
          schema:
            type: string
          example: Kickertisch/1.2
      responses:
        "200":
          description: "`DeviceResource`"
          content:
            application/json:
              schema:
                type: object
                properties:
                  data:
                    $ref: "#/components/schemas/DeviceResource"
                required:
                  - data
        "400":
          description: The device sends no `User-Agent` (`user_agent_required`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "401":
          description: The token is unknown or revoked, the device is not paired yet, or its organization has table devices switched off (`unauthenticated`)
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
        "429":
          description: Too many requests (`rate_limited`), with `Retry-After`
          content:
            application/problem+json:
              schema:
                $ref: "#/components/schemas/Problem"
      security:
        - deviceToken: []
      x-public: true
components:
  securitySchemes:
    deviceToken:
      type: http
      description: "The token a device got when it asked for a pairing code, sent as `Authorization: Bearer pkd_live_…` (`pkd_test_…` in the sandbox). It is shown once and stays valid until the device is unpaired."
      scheme: bearer
  schemas:
    DevicePairingResource:
      type: object
      properties:
        code:
          type: string
          description: Six capital letters and digits; the device shows them as two groups of three, and as a QR code.
        expires_at:
          type: string
        token:
          type: string
          description: |-
            The token the device sends as `Authorization: Bearer …` from now on. It is shown only
            this once; keep it in a file only the device's user reads. It signs in once the code is
            claimed: until then `GET /device` answers 401.
          examples:
            - pkd_test_7Hq2xV9pLm3RtY6wQz8NbC4kDf1Gs5Je0aB3cD
      required:
        - code
        - expires_at
        - token
      title: DevicePairingResource
    DeviceResource:
      type: object
      properties:
        id:
          type: string
        name:
          type: string
          description: What it is called at its table, such as "Kickertisch Halle".
        table:
          type: object
          properties:
            id:
              type: string
            name:
              type: string
          required:
            - id
            - name
        location:
          type: object
          properties:
            id:
              type: string
            name:
              type:
                - string
                - "null"
            time_zone:
              type: string
              description: For the times it shows.
          required:
            - id
            - name
            - time_zone
        organization:
          type: object
          properties:
            id:
              type: string
            name:
              type:
                - string
                - "null"
          required:
            - id
            - name
        scopes:
          type: array
          description: What its token may do, the fixed set of a device.
          items:
            type: string
      required:
        - id
        - name
        - table
        - location
        - organization
        - scopes
      title: DeviceResource
    Problem:
      type: object
      description: An error, following RFC 9457.
      properties:
        type:
          type: string
          description: A URL that names the kind of error.
        title:
          type: string
          description: Short English summary, the same for every occurrence of a code.
        status:
          type: integer
          description: The HTTP status.
        detail:
          type: string
          description: What happened and what to do, in the language of the request.
        code:
          type: string
          description: Stable code of the error; clients branch on it.
        correlation_id:
          type: string
          description: The ID of the request, also in the header `X-Correlation-Id`.
        errors:
          type: object
          description: "For `validation_failed`: the messages by field."
          additionalProperties:
            type: array
            items:
              type: string
      required:
        - type
        - title
        - status
        - detail
        - code
        - correlation_id
      title: Problem
    StartDevicePairingRequest:
      type: object
      properties:
        model:
          type:
            - string
            - "null"
          description: |-
            What the device says of itself, shown in the list of its table; all optional. Sent
            without signing in, so held to what every shown text may hold.
          maxLength: 80
        serial:
          type:
            - string
            - "null"
          maxLength: 80
        firmware:
          type:
            - string
            - "null"
          maxLength: 40
      title: StartDevicePairingRequest
```
