// 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 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 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; } }