packerooDevelopers Deutsch

Pair a table device

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

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

The flow

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

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

The complete program

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

Runs in a test against a stand-in of the API. Download file · Run: python3 pair_device.py

"""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()

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

Ask for a code

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

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

The answer with 201:

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

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

Show the code and a QR code

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

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

EnvironmentContent of the QR code
Livehttps://app.packeroo.com/verbinden?code=K7F4QX
Sandboxhttps://app.qm.packeroo.com/verbinden?code=K7F4QX

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

Keep the token safe

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

Why the token does not expire

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

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

Lost or stolen

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

Wait for the pairing

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

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

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

On restart

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

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

No device is unpaired without notice: when it has not reported for 24 hours, everyone who looks after the location gets a notification, and the app shows at the device on which day it is unpaired if it stays silent. More under Security and privacy.

Error cases

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

CaseAnswerWhat the device does
Code ran outGET /device stays 401 after expires_atask for a new code, with the current token as bearer
Paired alreadyPOST /device-pairings with a token: 409 device_already_pairedkeep the token and ask GET /device
Table devices switched offPOST: 409 table_devices_off; GET /device: 401show "Table devices are switched off", try again once a minute
No User-Agent400 user_agent_requiredset the header; this is a bug in the program
Missing or wrong idempotency key400 idempotency_key_requiredsend a UUID or ULID
Same key, other request422 idempotency_key_reusedmake a new key for every new request
Same request still running409 request_in_progresswait a moment, then send again with the same key
Field too long422 validation_failed with errors per fieldshorten model, serial, firmware
Too many requests429 rate_limited with Retry-Afterwait as many seconds as Retry-After says
No connection or server errornetwork error or 5xx, often without JSON (during a deploy, say)keep the code, ask again after a pause; the pause doubles up to 60 seconds
Device unpairedGET /device: 401 after there was 200pair again, with the old token as bearer
Paired, then unpairedPOST: 409 device_already_paired, then GET /device: 401drop the token and ask for a new code without it

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

Recipe: a Raspberry Pi at the table

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

"""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()

Download file · display.py

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

# 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

Download file · packeroo-device.service

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

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

Readable at the table

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

What comes next

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

This page as Markdown