### Device Setup API Source: https://github.com/oetiker/byonk/blob/main/docs/src/concepts/architecture.md The setup endpoint allows devices to register and receive an API key. ```APIDOC ## GET /api/setup ### Description Device registers and receives an API key. ### Method GET ### Endpoint /api/setup ### Parameters #### Query Parameters - **device_id** (string) - Required - Unique identifier for the device. ### Request Example ``` GET /api/setup?device_id=some-unique-device-id ``` ### Response #### Success Response (200) - **api_key** (string) - The API key for the device. #### Response Example ```json { "api_key": "generated-api-key-string" } ``` ``` -------------------------------- ### Complete Configuration Example Source: https://github.com/oetiker/byonk/blob/main/docs/src/guide/configuration.md An example of a complete Byonk configuration file, illustrating the structure for screens, devices, and other settings. ```APIDOC ## Example: Complete Configuration ```yaml # Byonk Configuration screens: # Default screen - shows time and a message default: script: default.lua template: default.svg default_refresh: 300 # Public transport departures transit: script: transit.lua template: transit.svg default_refresh: 60 # Room booking display floerli: script: floerli.lua template: floerli.svg default_refresh: 900 devices: # Kitchen display - bus departures "94:A9:90:8C:6D:18": screen: transit params: station: "Olten, Südwest" limit: 8 # Office display - room booking "AA:BB:CC:DD:EE:FF": screen: floerli params: room: "Rosa" # Lobby display - different bus stop "BB:CC:DD:EE:FF:00": screen: transit params: station: "Olten, Bahnhof" limit: 6 default_screen: default ``` ``` -------------------------------- ### Bash Command to Start Byonk Development Mode Source: https://github.com/oetiker/byonk/blob/main/docs/src/guide/dev-mode.md This bash command starts Byonk in development mode, specifying external directories for screens and configuration files, enabling live reload and easier development. ```bash SCREENS_DIR=./screens CONFIG_FILE=./config.yaml byonk dev ``` -------------------------------- ### Complete Byonk Configuration Example (YAML) Source: https://github.com/oetiker/byonk/blob/main/docs/src/guide/configuration.md This is a comprehensive example of a Byonk configuration file. It defines multiple screens (default, transit, floerli), maps specific devices by MAC address to these screens with custom parameters, and sets a default screen. ```yaml # Byonk Configuration screens: # Default screen - shows time and a message default: script: default.lua template: default.svg default_refresh: 300 # Public transport departures transit: script: transit.lua template: transit.svg default_refresh: 60 # Room booking display floerli: script: floerli.lua template: floerli.svg default_refresh: 900 devices: # Kitchen display - bus departures "94:A9:90:8C:6D:18": screen: transit params: station: "Olten, Südwest" limit: 8 # Office display - room booking "AA:BB:CC:DD:EE:FF": screen: floerli params: room: "Rosa" # Lobby display - different bus stop "BB:CC:DD:EE:FF:00": screen: transit params: station: "Olten, Bahnhof" limit: 6 default_screen: default ``` -------------------------------- ### YAML Configuration Example for Byonk Source: https://github.com/oetiker/byonk/blob/main/docs/src/guide/dev-mode.md This YAML snippet demonstrates how to configure panels and devices within Byonk, including color definitions, dithering algorithms, and calibration tuning parameters. ```yaml panels: my_panel: name: "My Panel" colors: "#000000,#FFFFFF,#FF0000,#FFFF00" colors_actual: "#303030,#D0D0C8,#C04040,#D0D020" # from dev mode calibration devices: "ABCDE-FGHJK": screen: gphoto panel: my_panel dither: floyd-steinberg error_clamp: 0.08 # from dev mode tuning noise_scale: 0.5 # from dev mode tuning ``` -------------------------------- ### Byonk Configuration File Example (config.yaml) Source: https://context7.com/oetiker/byonk/llms.txt Provides a comprehensive example of the Byonk configuration file (config.yaml), detailing settings for screen definitions, panel profiles, and dithering options for accurate e-ink display rendering. ```yaml # Screen definitions screens: default: script: default.lua template: default.svg default_refresh: 300 transit: script: transit.lua template: transit.svg default_refresh: 60 weather: script: weather.lua template: weather.svg default_refresh: 900 # Panel profiles with measured colors for accurate dithering panels: trmnl_og_4grey: name: "TRMNL OG (4-grey)" match: "trmnl_og_4grey" width: 800 height: 480 colors: "#000000,#555555,#AAAAAA,#FFFFFF" colors_actual: "#383838,#787878,#B8B8B0,#D8D8C8" dither: error_clamp: 0.1 noise_scale: 5.0 floyd-steinberg: error_clamp: 0.08 trmnl_og_4clr: name: "TRMNL OG (4-color)" match: "trmnl_og_4clr" colors: "#000000,#FFFFFF,#FF0000,#FFFF00" colors_actual: "#303030,#D0D0C8,#C04040,#D0D020" ``` -------------------------------- ### Example Device Registration and MAC Address Mapping (YAML) Source: https://github.com/oetiker/byonk/blob/main/docs/src/guide/configuration.md This YAML snippet illustrates how to configure devices in Byonk. It shows examples of registering devices using both a derived registration code and a MAC address, assigning them to specific screens and parameters. ```yaml registration: enabled: true devices: # By registration code (read from device screen) "ABCDE-FGHJK": screen: transit params: station: "Olten" # By MAC address (found in logs) "AA:BB:CC:DD:EE:FF": screen: weather ``` -------------------------------- ### Making HTTP GET Requests in Lua Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/lua-scripting.md Shows how to perform HTTP GET requests to fetch data from a URL using the 'http_get' function. Includes an example of error handling using 'pcall' and logging. ```lua local response = http_get("https://api.example.com/data") ``` ```lua local ok, response = pcall(function() return http_get("https://api.example.com/data") end) if not ok then log_error("Request failed: " .. tostring(response)) return { data = { error = "Failed to fetch data" }, refresh_rate = 60 } end ``` -------------------------------- ### Lua HTTP GET Requests Source: https://context7.com/oetiker/byonk/llms.txt Provides examples of making HTTP GET requests using the `http_get` function in Lua. It covers basic requests, requests with query parameters, authentication headers, basic authentication, response caching, accepting invalid certificates, and mutual TLS authentication. ```lua -- Basic GET request local response = http_get("https://api.example.com/data") -- With query parameters (auto URL-encoded) local response = http_get("https://api.example.com/search", { params = { query = "hello world", limit = 10 } }) -- With authentication headers local response = http_get("https://api.example.com/data", { headers = { ["Authorization"] = "Bearer " .. params.api_token } }) -- With basic auth local response = http_get("https://api.example.com/data", { basic_auth = { username = params.user, password = params.pass } }) -- With response caching (5 minutes) local response = http_get("https://api.weather.com/current", { params = { city = "Zurich" }, cache_ttl = 300 }) -- Accept self-signed certificates (insecure) local response = http_get("https://internal.example.com/data", { danger_accept_invalid_certs = true }) -- Mutual TLS authentication local response = http_get("https://secure-api.example.com/data", { ca_cert = "/path/to/ca.pem", client_cert = "/path/to/client.pem", client_key = "/path/to/client-key.pem" }) ``` -------------------------------- ### Set Up Byonk Workspace (Docker) Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/first-screen.md Launches the Byonk server using Docker, mapping local directories for screens and configuration into the container. It also exposes the necessary port for server access. This is the recommended setup for Docker users. ```bash docker run -d --pull always -p 3000:3000 \ -e SCREENS_DIR=/data/screens \ -e CONFIG_FILE=/data/config.yaml \ -v ./data:/data \ ghcr.io/oetiker/byonk ``` -------------------------------- ### Set Up Byonk Workspace (Bash) Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/first-screen.md Configures the Byonk environment by setting environment variables for screen and configuration file paths, then starts the Byonk server. This is essential for users running Byonk directly from a binary. ```bash # Set paths and start server (auto-seeds empty directories) export SCREENS_DIR=./screens export CONFIG_FILE=./config.yaml byonk serve ``` -------------------------------- ### GET /api/setup Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/http-api.md Register a new device or retrieve existing registration. The device sends its MAC address and receives an API key for future requests. ```APIDOC ## GET /api/setup ### Description Register a new device or retrieve existing registration. The device sends its MAC address and receives an API key for future requests. ### Method GET ### Endpoint /api/setup ### Parameters #### Header Parameters - **ID** (string) - Required - Device MAC address (e.g., 'AA:BB:CC:DD:EE:FF') - **FW-Version** (string) - Required - Firmware version (e.g., '1.7.1') - **Model** (string) - Required - Device model ('og' or 'x') ### Response #### Success Response (200) - **api_key** (string) - API key for the device. - **friendly_id** (string) - A user-friendly identifier for the device. - **image_url** (string) - URL for a default image. - **message** (string) - A status message. - **status** (integer) - Status code, 0 for success. #### Response Example ```json { "api_key": null, "friendly_id": null, "image_url": null, "message": null, "status": 0 } ``` #### Error Response (400) - Missing required header ``` -------------------------------- ### http_request Function Documentation Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/lua-api.md This section details the `http_request` function, its parameters, options, and provides examples for common HTTP methods like GET, POST, PUT, and DELETE. ```APIDOC ## http_request Function ### Description Core HTTP function with full control over the request method and options. ### Method This function supports all standard HTTP methods (GET, POST, PUT, DELETE, PATCH, HEAD). ### Endpoint Dynamic, determined by the `url` parameter. ### Parameters #### Path Parameters None #### Query Parameters - **url** (string) - Required - The URL to fetch. - **options** (table) - Optional - Request options. #### Request Body Not directly applicable as a top-level parameter, but handled via `options.body` or `options.json`. ### Options Table Details #### Query Parameters (within `options.params`) - **param_name** (any) - Required/Optional - Key-value pairs for query parameters (automatically URL-encoded). #### Headers (within `options.headers`) - **header_name** (string) - Required/Optional - Key-value pairs of HTTP headers. #### Request Body (via `options.body` or `options.json`) - **body** (string) - Optional - Request body as a raw string. - **json** (table) - Optional - Request body as a Lua table, which will be auto-serialized to JSON. Automatically sets `Content-Type` to `application/json`. #### Other Options - **method** (string) - Optional - HTTP method: "GET", "POST", "PUT", "DELETE", "PATCH", "HEAD". Defaults to "GET". - **basic_auth** (table) - Optional - Basic authentication: `{ username = "...", password = "..." }`. - **timeout** (number) - Optional - Request timeout in seconds. Defaults to 30. - **follow_redirects** (boolean) - Optional - Whether to follow HTTP redirects. Defaults to true. - **max_redirects** (number) - Optional - Maximum number of redirects to follow. Defaults to 10. - **danger_accept_invalid_certs** (boolean) - Optional - Accept self-signed/expired certificates (insecure!). Defaults to false. - **ca_cert** (string) - Optional - Path to CA certificate PEM file for server verification. - **client_cert** (string) - Optional - Path to client certificate PEM file for mTLS. - **client_key** (string) - Optional - Path to client private key PEM file for mTLS. - **cache_ttl** (number) - Optional - Cache response for N seconds. Defaults to no caching. ### Request Example ```lua -- GET request (default) local response = http_request("https://api.example.com/data") -- POST with JSON body local response = http_request("https://api.example.com/users", { method = "POST", json = { name = "Alice", email = "alice@example.com" } }) -- PUT request with headers local response = http_request("https://api.example.com/users/123", { method = "PUT", headers = { ["Authorization"] = "Bearer " .. params.token }, json = { name = "Alice Updated" } }) -- DELETE request local response = http_request("https://api.example.com/users/123", { method = "DELETE", headers = { ["Authorization"] = "Bearer " .. params.token } }) ``` ### Response #### Success Response (200 OK) - **response body** (string) - The response body from the server. #### Response Example ``` "Success!" ``` ### Error Handling Throws an error if the request fails (e.g., network issues, server errors). ``` -------------------------------- ### Configuration Example for Lua Script Parameters Source: https://github.com/oetiker/byonk/blob/main/docs/src/concepts/content-pipeline.md The `config.yaml` file defines device-specific parameters that are passed to the Lua scripts. This allows for customization of script behavior based on the device. ```yaml devices: "94:A9:90:8C:6D:18": screen: transit params: station: "Olten, Bahnhof" limit: 8 ``` -------------------------------- ### Example: Scraping Table Data in Lua Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/lua-scripting.md A comprehensive example demonstrating how to fetch HTML, parse it, select table rows and cells, extract text content, and structure the data into a Lua table. ```lua local html = http_get("https://example.com/data") local doc = html_parse(html) local rows = {} doc:select("table tbody tr"):each(function(row) local cells = {} row:select("td"):each(function(cell) table.insert(cells, cell:text()) end) if #cells >= 2 then table.insert(rows, { name = cells[1], value = cells[2] }) end end) return { data = { rows = rows }, refresh_rate = 900 } ``` -------------------------------- ### Responsive Screen Layout Example (Lua) Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/lua-api.md Illustrates the transition from manual boilerplate code for responsive screen layouts to using helper functions like `scale_font` and `scale_pixel`. It highlights the benefits of using layout helpers for consistency. ```lua -- Before (manual boilerplate): local width = device and device.width or 800 local height = device and device.height or 480 local scale = math.min(width / 800, height / 480) local font_size = math.floor(48 * scale) -- Wrong: shouldn't floor fonts local header_y = math.floor(70 * scale) -- Correct: pixel-aligned -- After (using helpers): local font_size = scale_font(48) -- Preserves precision for fonts local header_y = scale_pixel(70) -- Pixel-aligned position local margin = layout.margin -- Pre-computed pixel margin local colors = layout.colors -- Display palette colors ``` -------------------------------- ### Device Log Entry Example Source: https://github.com/oetiker/byonk/blob/main/docs/src/concepts/device-mapping.md An example log message from Byonk indicating that a device has been registered. This log entry includes the unique `device_id` (MAC address) of the connected device. ```text INFO Device registered device_id="94:A9:90:8C:6D:18" ``` -------------------------------- ### HTML Parsing Setup in Lua Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/lua-scripting.md Shows the initial steps for parsing HTML content obtained from an HTTP request using 'html_parse' to create a document object for querying. ```lua local html = http_get("https://example.com") local doc = html_parse(html) ``` -------------------------------- ### Byonk CLI Commands Source: https://context7.com/oetiker/byonk/llms.txt Illustrates various command-line interface commands for Byonk, including showing configuration, starting the server in different modes, rendering screens for testing, and extracting embedded assets. ```bash # Show current configuration ./byonk # Start HTTP server ./byonk serve # Start development mode with live reload SCREENS_DIR=./screens CONFIG_FILE=./config.yaml byonk dev # Render a screen to PNG for testing ./byonk render --mac "00:00:00:00:00:00" --output test.png --battery=4.12 --rssi=-67 # Extract embedded assets for customization ./byonk init --all # Extract everything ./byonk init --screens # Extract screens only ./byonk init --list # List embedded assets ``` -------------------------------- ### Device Mapping Configuration (YAML) Source: https://github.com/oetiker/byonk/blob/main/docs/src/concepts/device-mapping.md An example of the `config.yaml` file used for mapping devices to specific screens. It demonstrates how to associate MAC addresses with screen names and parameters, and defines a `default_screen`. ```yaml devices: "94:A9:90:8C:6D:18": screen: transit params: station: "Olten, Bahnhof" "AA:BB:CC:DD:EE:FF": screen: weather params: city: "Zurich" default_screen: default ``` -------------------------------- ### YAML Parameters Example for Byonk Source: https://github.com/oetiker/byonk/blob/main/docs/src/guide/configuration.md Illustrates various data types that can be used within the `params` section of the Byonk YAML configuration. These parameters are passed to the associated Lua scripts for customization. ```yaml params: # Strings station: "Olten, Bahnhof" # Numbers limit: 8 temperature_offset: -2.5 # Booleans show_delays: true # Lists rooms: - "Rosa" - "Flora" ``` -------------------------------- ### Configure Google Photos Album Display in YAML Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/advanced.md YAML configuration example for displaying a Google Photos album on a device. It specifies the screen type (`gphoto`), the album URL, and optional parameters like `show_status` and `refresh_rate`. ```yaml # config.yaml devices: "XX:XX:XX:XX:XX:XX": screen: gphoto params: album_url: "https://photos.app.goo.gl/YOUR_ALBUM_ID" show_status: true # Show battery/signal overlay refresh_rate: 1800 # 30 minutes (default: 3600) ``` -------------------------------- ### Device Setup Response JSON Source: https://github.com/oetiker/byonk/blob/main/docs/src/concepts/device-mapping.md The JSON structure returned by Byonk's `/api/setup` endpoint. It includes a status code, an `api_key` for authentication, and a `friendly_id` for human-readable identification. ```json { "status": 200, "api_key": "a1b2c3d4e5f6...", "friendly_id": "abc123def456" } ``` -------------------------------- ### Reading Dither Tuning Values in Lua Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/lua-api.md Shows how to read pre-script resolved dither tuning values from the 'device.dither' sub-table. It provides examples of accessing algorithm, error clamp, and noise scale, and demonstrates selectively overriding values when returning configuration. ```lua -- Read current tuning local algo = device.dither.algorithm -- "floyd-steinberg" (resolved algorithm) local ec = device.dither.error_clamp -- 0.08 (from panel/device config) local ns = device.dither.noise_scale -- 4.0 local cc = device.dither.chroma_clamp -- nil (not set) local st = device.dither.strength -- 1.0 (default) -- Selectively override: halve the error clamp, keep everything else return { data = { ... }, refresh_rate = 300, error_clamp = (device.dither.error_clamp or 0.1) * 0.5, -- noise_scale not returned -> keeps panel/device value } ``` -------------------------------- ### Fetch Transit Departures API Example (Lua) Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/lua-scripting.md Fetches public transport departure data for a given station from the OpenData transport API. Includes URL encoding, error handling, JSON parsing, data transformation, and smart refresh rate calculation. ```lua -- transit.lua - Fetch public transport departures local station = params.station or "Olten" local limit = params.limit or 8 log_info("Fetching departures for: " .. station) -- URL encode the station name local encoded = station:gsub(" ", "%%20"):gsub(",", "%%2C") local url = "https://transport.opendata.ch/v1/stationboard" .. "?station=" .. encoded .. "&limit=" .. limit -- Fetch with error handling local ok, response = pcall(function() return http_get(url) end) if not ok then log_error("API request failed: " .. tostring(response)) return { data = { station = station, error = "Failed to fetch departures", departures = {} }, refresh_rate = 60 } end -- Parse JSON local json = json_decode(response) -- Transform data for template local departures = {} local now = time_now() for i, dep in ipairs(json.stationboard or {}) do local departure_time = dep.stop and dep.stop.departure or "" local hour, min = departure_time:match("T(%d+):(%d+)") table.insert(departures, { time = hour and (hour .. ":" .. min) or "??:??", line = (dep.category or "") .. (dep.number or ""), destination = dep.to or "Unknown", delay = dep.stop and dep.stop.delay or 0 }) end -- Calculate smart refresh rate local refresh_rate = 300 if #departures > 0 and json.stationboard[1].stop then local first_dep = json.stationboard[1].stop.departureTimestamp if first_dep then local seconds_until = first_dep - now refresh_rate = math.max(30, math.min(seconds_until + 30, 900)) end end log_info("Found " .. #departures .. " departures, refresh in " .. refresh_rate .. "s") return { data = { station = json.station and json.station.name or station, departures = departures, updated_at = time_format(now, "%H:%M") }, refresh_rate = refresh_rate } ``` -------------------------------- ### Render Screen Directly with CLI (Rust) Source: https://github.com/oetiker/byonk/blob/main/CHANGES.md The `byonk render` subcommand allows for direct screen rendering to a file without starting a server. It requires the device's MAC address and an output file path. This functionality was introduced to simplify testing and sample generation. ```rust /// Renders a screen directly to a file without starting a server. /// /// # Arguments /// /// * `--mac ` - The MAC address of the device. /// * `--output ` - The path to the output PNG file. /// /// # Example /// /// ```bash /// byonk render --mac 00:11:22:33:44:55 --output screen.png /// ``` ``` -------------------------------- ### HTTP GET Request Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/lua-scripting.md Fetches data from a given URL and returns the response body as a string. Includes examples for error handling and URL encoding. ```APIDOC ## HTTP Requests ### http_get(url) Fetches a URL and returns the response body as a string. ```lua local response = http_get("https://api.example.com/data") ``` **Error handling:** ```lua local ok, response = pcall(function() return http_get("https://api.example.com/data") end) if not ok then log_error("Request failed: " .. tostring(response)) return { data = { error = "Failed to fetch data" }, refresh_rate = 60 } end ``` **URL encoding:** ```lua local city = "Zürich, Schweiz" local encoded = city:gsub(" ", "%%20"):gsub(",", "%%2C") local url = "https://api.example.com/city?name=" .. encoded ``` ``` -------------------------------- ### Byonk API: Device Registration Source: https://context7.com/oetiker/byonk/llms.txt Demonstrates how to register a new e-ink device with the Byonk server using a GET request to the /api/setup endpoint. It includes example headers and the expected JSON response. ```bash curl -X GET "http://localhost:3000/api/setup" \ -H "ID: AA:BB:CC:DD:EE:FF" \ -H "FW-Version: 1.7.1" \ -H "Model: og" ``` -------------------------------- ### Configure Device with Parameters in config.yaml (YAML) Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/first-screen.md Assigns the 'hello' screen to a device and provides a specific 'name' parameter ('Alice') to be used by the Lua script. This demonstrates how to customize screen behavior per device. ```yaml devices: "YOUR:MAC:AD:DR:ES:S0": screen: hello params: name: "Alice" ``` -------------------------------- ### SVG Template Filters for Data Manipulation Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/svg-templates.md Showcases the use of Tera filters within SVG templates to modify and format data before display. Examples include truncating long strings, formatting timestamps, and getting the length of arrays or strings. ```svg {{ data.description | truncate(length=50) }} {{ data.updated_at | format_time(format="%H:%M") }} {{ data.items | length }} items ``` -------------------------------- ### Build Documentation with mdBook Source: https://github.com/oetiker/byonk/blob/main/CLAUDE.md This code snippet shows how to build and serve the project's documentation locally using mdBook. It requires navigating to the 'docs' directory and running the 'mdbook serve' command. This allows developers to preview documentation changes before committing. ```bash cd docs && mdbook serve ``` -------------------------------- ### Perform HTTP GET Requests with Lua Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/lua-api.md Convenience wrapper for GET requests, similar to http_request with method set to 'GET'. Supports various options like query parameters, authentication, custom certificates, and response caching. ```lua -- Simple usage local response = http_get("https://api.example.com/data") -- With query parameters (auto URL-encoded) local response = http_get("https://api.example.com/search", { params = { query = "hello world", -- becomes ?query=hello%20world&limit=10 limit = 10 } }) -- With authentication header local response = http_get("https://api.example.com/data", { headers = { ["Authorization"] = "Bearer " .. params.api_token } }) -- With basic auth local response = http_get("https://api.example.com/data", { basic_auth = { username = params.user, password = params.pass } }) -- Accept self-signed certificates (for internal APIs) local response = http_get("https://internal.example.com/data", { danger_accept_invalid_certs = true }) -- Use custom CA certificate for server verification local response = http_get("https://internal.example.com/data", { ca_cert = "/path/to/ca.pem" }) -- Mutual TLS (mTLS) with client certificate local response = http_get("https://secure-api.example.com/data", { ca_cert = "/path/to/ca.pem", client_cert = "/path/to/client.pem", client_key = "/path/to/client-key.pem" }) -- Cache response for 5 minutes (300 seconds) -- Useful for APIs with rate limits or data that doesn't change frequently local response = http_get("https://api.weather.com/current", { params = { city = "Zurich" }, cache_ttl = 300 -- Cache for 5 minutes }) ``` ```lua -- First call fetches from API, subsequent calls within 60s use cache local data = http_get("https://api.example.com/data", { cache_ttl = 60 }) ``` -------------------------------- ### GET /api/display Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/http-api.md Get display content for a device. Returns JSON with an image_url that the device should fetch separately. ```APIDOC ## GET /api/display ### Description Get display content for a device. Returns JSON with an image_url that the device should fetch separately. The firmware expects status=0 for success (not HTTP 200). ### Method GET ### Endpoint /api/display ### Parameters #### Header Parameters - **ID** (string) - Required - Device MAC address - **Access-Token** (string) - Required - API key from /api/setup - **Width** (integer) - Optional - Display width in pixels (default: 800) - **Height** (integer) - Optional - Display height in pixels (default: 480) - **Refresh-Rate** (number) - Optional - Current refresh rate in seconds - **Battery-Voltage** (number) - Optional - Battery voltage - **RSSI** (integer) - Optional - WiFi signal strength - **FW-Version** (string) - Optional - Firmware version - **Model** (string) - Optional - Device model ('og' or 'x') - **Board** (string) - Optional - Board identifier (e.g., 'trmnl_og_4clr') - **Colors** (string) - Optional - Display palette as comma-separated hex RGB (e.g., '#000000,#FFFFFF,#FF0000,#FFFF00'). Defaults to 4-grey palette if absent. ### Response #### Success Response (200) - **filename** (string) - The name of the content file. - **firmware_url** (string) - URL to update firmware (null if not applicable). - **image_url** (string) - URL of the image to display. - **refresh_rate** (integer) - Recommended refresh rate in seconds. - **reset_firmware** (boolean) - Flag to reset firmware. - **special_function** (string) - Special function to execute (null if none). - **status** (integer) - Status code, 0 for success. - **temperature_profile** (string) - Temperature profile information (null if not applicable). - **update_firmware** (boolean) - Flag to indicate firmware update is available. #### Response Example ```json { "filename": "string", "firmware_url": null, "image_url": null, "refresh_rate": 0, "reset_firmware": true, "special_function": null, "status": 0, "temperature_profile": null, "update_firmware": true } ``` #### Error Response (400) - Missing required header #### Error Response (404) - Device not found ``` -------------------------------- ### HTTP GET Requests Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/lua-api.md Convenience wrapper for making GET requests. Supports query parameters, authentication, custom certificates, and response caching. ```APIDOC ## GET /api/data ### Description Performs an HTTP GET request to the specified URL. ### Method GET ### Endpoint `/api/data` ### Parameters #### Query Parameters - **params** (table) - Optional - A table of query parameters to be appended to the URL. These will be URL-encoded automatically. - **headers** (table) - Optional - A table of HTTP headers to include in the request. - **basic_auth** (table) - Optional - A table containing `username` and `password` for basic authentication. - **danger_accept_invalid_certs** (boolean) - Optional - If true, accepts self-signed or invalid SSL certificates. - **ca_cert** (string) - Optional - Path to a custom CA certificate file for server verification. - **client_cert** (string) - Optional - Path to a client certificate file for mutual TLS (mTLS). - **client_key** (string) - Optional - Path to a client private key file for mutual TLS (mTLS). - **cache_ttl** (number) - Optional - Time-to-live in seconds for caching the response. Responses are cached in memory. ### Request Example ```lua -- Simple GET request local response = http_get("https://api.example.com/data") -- GET request with query parameters and cache local response = http_get("https://api.example.com/search", { params = { query = "hello world", limit = 10 }, cache_ttl = 300 }) -- GET request with authentication header local response = http_get("https://api.example.com/data", { headers = { ["Authorization"] = "Bearer " .. params.api_token } }) ``` ### Response #### Success Response (200) - **response** (any) - The response body from the server, parsed if possible (e.g., JSON). #### Response Example ```json { "data": "example data" } ``` ``` -------------------------------- ### Configure PNG Output Optimization (Command Line) Source: https://github.com/oetiker/byonk/blob/main/CHANGES.md This command line example shows how to use `oxipng` to optimize PNG output. It utilizes zopfli compression and adaptive filter selection, resulting in approximately 27% smaller file sizes for the generated images. This is a post-processing step applied after the initial image generation. ```bash oxipng -o 6 --zopfli --lossy-compress input.png -o output.png ``` -------------------------------- ### Getting Current Unix Timestamp in Lua Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/lua-scripting.md Demonstrates how to get the current Unix timestamp (seconds since epoch) using the 'time_now()' function. ```lua local now = time_now() -- e.g., 1703672400 ``` -------------------------------- ### GET /api/image/{hash}.png Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/http-api.md Get rendered PNG image by content hash. Returns the actual PNG image data rendered from SVG with dithering applied. ```APIDOC ## GET /api/image/{hash}.png ### Description Get rendered PNG image by content hash. Returns the actual PNG image data rendered from SVG with dithering applied. The content hash is provided in the `/api/display` response and ensures clients can detect when content has changed. ### Method GET ### Endpoint /api/image/{hash}.png ### Parameters #### Path Parameters - **hash** (string) - Required - Content hash from `/api/display` response ### Response #### Success Response (200) - PNG image data #### Error Response (404) - Content not found (cache miss or invalid hash) #### Error Response (500) - Rendering error ``` -------------------------------- ### Initialize Byonk Project Assets Source: https://github.com/oetiker/byonk/blob/main/docs/src/guide/installation.md Extract embedded assets for customization using the 'byonk init' command. Options include extracting all assets, screens only, or listing available assets. No external dependencies are required for this command. ```bash ./byonk init --all # Extract everything ./byonk init --screens # Extract screens only ./byonk init --list # List embedded assets ``` -------------------------------- ### Assign Screen to Device in config.yaml (YAML) Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/first-screen.md Assigns the 'hello' screen to a specific device identified by its MAC address in the Byonk configuration. It also allows for device-specific parameters, shown here as an empty object. ```yaml devices: "YOUR:MAC:AD:DR:ES:S0": screen: hello params: {} ``` -------------------------------- ### Configure Screen in config.yaml (YAML) Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/first-screen.md Defines a new screen named 'hello' within the Byonk configuration. It specifies the associated Lua script (`hello.lua`) and SVG template (`hello.svg`), along with a default refresh rate. ```yaml screens: # ... existing screens ... hello: script: hello.lua template: hello.svg default_refresh: 60 ``` -------------------------------- ### Byonk API: Get Rendered Image Source: https://context7.com/oetiker/byonk/llms.txt Illustrates how to fetch the actual rendered PNG image from the Byonk server using its content hash. This is done via a GET request to the /api/image/{hash}.png endpoint. ```bash curl -X GET "http://localhost:3000/api/image/abc123def456.png" \ --output screen.png ``` -------------------------------- ### SVG Templating: Loops and Conditionals Source: https://context7.com/oetiker/byonk/llms.txt Demonstrates how to use Jinja-like templating syntax within SVG to create dynamic content. It shows how to loop through data items, apply conditional styling based on loop index or data values, and handle empty states. ```svg {% for item in data.items %} {% if loop.index0 is odd %} {% endif %} {{ item.time }} - {{ item.destination }} {% if item.delay > 0 %}+{{ item.delay }}{% endif %} {% endfor %} {% if data.items | length == 0 %} No items found {% endif %} ``` -------------------------------- ### Create Hello World Lua Script (Lua) Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/first-screen.md A Lua script that generates dynamic data for a Byonk screen. It captures the current time, formats it, and prepares a greeting message. The script returns a table containing `data` for the template and a `refresh_rate`. ```lua -- Hello World screen -- Displays a greeting with the current time local now = time_now() return { data = { greeting = "Hello, World!", time = time_format(now, "%H:%M:%S"), date = time_format(now, "%A, %B %d, %Y") }, refresh_rate = 60 -- Refresh every minute } ``` -------------------------------- ### GET /health Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/http-api.md Health check endpoint for the API. ```APIDOC ## GET /health ### Description Health check endpoint for the API. ### Method GET ### Endpoint /health ### Parameters None ### Response #### Success Response (200) - Typically returns an empty body or a simple status message indicating the API is healthy. ``` -------------------------------- ### Time Functions Source: https://github.com/oetiker/byonk/blob/main/docs/src/tutorial/lua-scripting.md Provides functions to get the current Unix timestamp and format timestamps into human-readable strings. ```APIDOC ## Time Functions ### time_now() Returns the current Unix timestamp (seconds since 1970). ```lua local now = time_now() -- e.g., 1703672400 ``` ### time_format(timestamp, format) Formats a timestamp into a string using strftime patterns. ```lua local now = time_now() time_format(now, "%H:%M") -- "14:32" time_format(now, "%H:%M:%S") -- "14:32:05" time_format(now, "%Y-%m-%d") -- "2024-12-27" time_format(now, "%A") -- "Friday" time_format(now, "%B %d, %Y") -- "December 27, 2024" ``` **Common format codes:** | Code | Description | Example | |------|-------------|---------| | `%H` | Hour (24h) | 14 | | `%M` | Minute | 32 | | `%S` | Second | 05 | | `%Y` | Year | 2024 | | `%m` | Month | 12 | | `%d` | Day | 27 | | `%A` | Weekday name | Friday | | `%B` | Month name | December | | `%a` | Short weekday | Fri | | `%b` | Short month | Dec | ``` -------------------------------- ### Basic Lua Script Structure Source: https://context7.com/oetiker/byonk/llms.txt Demonstrates the fundamental structure of a Lua script for Byonk. It shows how to access parameters, retrieve the current time, format it, and return a table containing data and a refresh rate. This is the entry point for custom screen logic. ```lua -- screens/hello.lua local now = time_now() local name = params.name or "World" return { data = { greeting = "Hello, " .. name .. "!", time = time_format(now, "%H:%M:%S"), date = time_format(now, "%A, %B %d, %Y") }, refresh_rate = 60 } ``` -------------------------------- ### Get Rendered Image API Source: https://context7.com/oetiker/byonk/llms.txt Fetch the actual PNG image by its content hash. ```APIDOC ## GET /api/image/{hash}.png ### Description Fetch the actual PNG image by content hash. ### Method GET ### Endpoint /api/image/{hash}.png ### Parameters #### Path Parameters - **hash** (string) - Required - The content hash of the image to retrieve. ### Response #### Success Response (200) - The response body will be the PNG image data. ### Request Example ```bash curl -X GET "http://localhost:3000/api/image/abc123def456.png" \ --output screen.png ``` ``` -------------------------------- ### Docker Deployment for Byonk Source: https://context7.com/oetiker/byonk/llms.txt Provides instructions for deploying Byonk using Docker. The basic deployment uses embedded assets, while the custom deployment allows mounting volumes for screens, fonts, and configuration files. ```bash # Basic deployment - uses embedded screens, fonts, and config docker run -d --pull always \ --name byonk \ -p 3000:3000 \ ghcr.io/oetiker/byonk:latest ``` ```bash # Docker with Custom Screens docker run -d --pull always \ --name byonk \ -p 3000:3000 \ -e SCREENS_DIR=/data/screens \ -e FONTS_DIR=/data/fonts \ -e CONFIG_FILE=/data/config.yaml \ -v ./data:/data \ ghcr.io/oetiker/byonk:latest ``` -------------------------------- ### CLI Render Command Source: https://github.com/oetiker/byonk/blob/main/CHANGES.md The `byonk render` CLI command allows rendering screens directly to a file without starting a server. ```APIDOC ## CLI Render Command ### Description Renders a screen to a file using the Byonk CLI. ### Method CLI Command ### Endpoint `byonk render` ### Parameters #### Command Line Arguments - **--mac** (string) - Required - The MAC address of the device. - **--output** (string) - Required - The output file path (e.g., `file.png`). - **--screen** (string) - Optional - The name of the screen to render. ### Request Example ```bash byonk render --mac XX:XX:XX:XX:XX:XX --output file.png --screen hello ``` ### Response #### Success Response - A PNG file is created at the specified output path. #### Response Example ``` (No direct response, file is generated) ``` ``` -------------------------------- ### HTTP Functions Source: https://github.com/oetiker/byonk/blob/main/docs/src/api/lua-api.md Provides functions for making HTTP requests, including a general-purpose function and shorthands for GET and POST requests. ```APIDOC ## HTTP Functions ### Description Byonk provides three HTTP functions: `http_request` (full control), `http_get` (GET shorthand), and `http_post` (POST shorthand). ### `http_request(options)` Performs an HTTP request with full control over options. ### Method Function Call ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **options** (table) - Required - Table containing request options (e.g., url, method, headers, body). ### Request Example ```lua local response = http_request({ url = "http://example.com/api/data", method = "POST", headers = { ["Content-Type"] = "application/json" }, body = json.encode({ key = "value" }) }) ``` ### Response #### Success Response (200) - **response** (table) - The HTTP response object. ### `http_get(url, options)` Shorthand for making an HTTP GET request. ### Method Function Call ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None **Parameters:** - **url** (string) - Required - The URL to send the GET request to. - **options** (table) - Optional - Table containing additional options for the request. ### Request Example ```lua local data = http_get("http://example.com/api/items") ``` ### Response #### Success Response (200) - **response** (table) - The HTTP response object. ### `http_post(url, data, options)` Shorthand for making an HTTP POST request. ### Method Function Call ### Endpoint N/A ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None **Parameters:** - **url** (string) - Required - The URL to send the POST request to. - **data** (any) - Required - The data to send in the request body. - **options** (table) - Optional - Table containing additional options for the request. ### Request Example ```lua local result = http_post("http://example.com/api/users", { name = "John Doe" }) ``` ### Response #### Success Response (200) - **response** (table) - The HTTP response object. ```