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