'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";