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