# 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.
