Skip to main content

Module reference

Tetra provides Starlark modules for fetching and parsing data, formatting values, protecting secrets, and rendering the final display. Import a module with load before using it:

load("render.star", "render")

The second argument selects an exported symbol. Assign it to another local name when an alias reads better:

load("render.star", r = "render")

Starlib modules​

Tetra includes a subset of the Starlib standard library.

ModulePurpose
bsoup.starParse and traverse HTML with a Beautiful Soup-style API.
compress/gzip.starDecompress gzip data.
compress/zipfile.starRead compressed ZIP archives.
encoding/base64.starEncode and decode Base64 data.
encoding/csv.starDecode CSV data.
encoding/json.starEncode and decode JSON data.
hash.starGenerate MD5, SHA-1, and SHA-256 hashes.
html.starQuery HTML with a jQuery-style API.
math.starUse mathematical functions and constants.
re.starMatch and transform text with regular expressions.
time.starParse, format, and calculate with dates and times.

Time​

time.star creates, parses, formats, and calculates with time values. Formatting uses Go's reference date (Mon Jan 2 15:04:05 MST 2006), not strftime tokens.

FunctionPurpose
now()Return the current time.
from_timestamp(seconds, nanoseconds?)Create a time from a Unix timestamp.
parse_time(value, format?, location?)Parse a time; RFC 3339 and UTC are the defaults.
parse_duration(value)Parse a duration such as "30s", "2h45m", or "-24h".
time(year?, month?, day?, hour?, minute?, second?, …)Construct a time from individual components.
is_valid_timezone(location)Check an IANA time zone such as "America/Lima".

Time values expose fields including year, month, day, hour, minute, second, unix, and unix_nano. Use in_location() to convert an instant to another time zone and format() to produce text.

Tetra supplies the installation's IANA timezone in the reserved $tz config key. Always provide a fallback for previews or older clients that do not send it.

load("render.star", "render")
load("time.star", "time")

DEFAULT_TIMEZONE = "America/New_York"

def clock_data(config):
timezone = config.get("$tz", DEFAULT_TIMEZONE)
local_now = time.now().in_location(timezone)
event = time.parse_time("2026-12-31T23:00:00Z").in_location(timezone)
refresh_after = local_now + time.parse_duration("15m")

return {
"timezone": timezone,
"clock": local_now.format("15:04"),
"event": event.format("Jan 02 15:04"),
"refresh_unix": refresh_after.unix,
}

def main(config):
data = clock_data(config)
return render.Root(
child = render.Column(
children = [
render.Text(data["clock"], color = "#ffffff"),
render.Text(data["event"], color = "#22c55e"),
],
),
)

Time arithmetic supports adding or subtracting durations and subtracting one time from another. See the Weather & Sun Clock for a complete display using time zones and formatted times.

Beautiful Soup​

bsoup.star parses imperfect HTML and provides Beautiful Soup-style traversal. Use xpath.star for XML feeds where exact paths are more useful.

APIPurpose
bsoup.parseHtml(markup)Parse HTML and return its root node.
node.find(name, attrs?, recursive?, …)Return the first matching descendant.
node.find_all(name, attrs?, recursive?, …)Return all matching descendants.
node.get_text()Return all text below the node.
node.attrs()Return the element attributes as a mapping.
node.contents()Return the node's direct children.
node.child(name)Return a direct child with the given tag.
node.parent()Return the parent node.
node.next_sibling() / prev_sibling()Traverse between neighboring sibling nodes.
load("bsoup.star", "bsoup")

ARTICLE_HTML = """
<article>
<h2>Pixel displays brighten the commute</h2>
<a href="/stories/commute">Read more</a>
</article>
"""

def article_data():
document = bsoup.parseHtml(ARTICLE_HTML)
link = document.find("a")
return {
"headline": document.find("h2").get_text(),
"url": link.attrs().get("href"),
}

See the News & RSS Ticker for a complete display that combines bsoup, HTML selectors, and an RSS feed.

Base64​

encoding/base64.star converts between raw data and Base64 text.

FunctionPurpose
encode(data, encoding?)Encode raw data as Base64 text.
decode(value, encoding?)Decode Base64 text to raw data.

The optional encoding is "standard" by default. It also accepts "standard_raw", "url", and "url_raw"; raw variants omit padding and URL variants use the URL-safe alphabet.

load("encoding/base64.star", "base64")

encoded = base64.encode("hello")
decoded = base64.decode(encoded)

# URL-safe Base64 without trailing = padding.
token = base64.encode("hello friend!", encoding = "url_raw")

Image selectors and many image APIs provide Base64 text. Decode it before passing the bytes to render.Image:

load("encoding/base64.star", "base64")
load("render.star", "render")

def image_from_config(config):
return render.Image(src = base64.decode(config["photo"]))

See the Photo & GIF Frame for a complete app using PhotoSelect, Base64 decoding, and render.Image.

Starlib HTTP​

Tetra includes a caching-aware version of Starlib's HTTP client. Pass ttl_seconds to cache a response and keep outgoing request rates reasonable.

ModulePurpose
http.starMake HTTP requests with response caching.

For example, cache a JSON response for one hour:

load("http.star", "http")
load("encoding/json.star", "json")

def fetch_status():
response = http.get(
"https://status.example.com/api/status",
ttl_seconds = 3600,
)
if response.status_code != 200:
fail("Status request failed: %d" % response.status_code)

return json.decode(response.body())

Starlark is Python-like, but it does not support try/except or other Python exception-handling statements. Check response.status_code before reading the response and either return a fallback widget from main() or call fail(). response.json() is also available as a shorter equivalent. Use either form to work with structured values; never compare response.body() with serialized JSON text because harmless whitespace, key-order, or additional-field changes would break that comparison. Only decode when the endpoint contract guarantees JSON because decoding errors cannot be caught inside the app.

Cache​

cache.star stores string values between app executions. Prefer HTTP's built-in response caching for requests; use this module for derived or non-HTTP values. Serialize structured data before storing it.

FunctionReturnsPurpose
get(key)str or NoneRead an unexpired value.
set(key, value, ttl_seconds=60)—Store a string value with a TTL in seconds.
Shared cache

The cache belongs to the app, not an individual installation. Include any installation-specific inputs in the key to prevent values from colliding.

load("cache.star", "cache")

def next_counter():
stored = cache.get("counter")
current = int(stored) if stored != None else 0
current += 1
cache.set("counter", str(current), ttl_seconds = 3600)
return current

HMAC​

hmac.star authenticates a string with a secret key using HMAC.

FunctionReturnsPurpose
md5(key, string)strGenerate an HMAC-MD5 digest.
sha1(key, string)strGenerate an HMAC-SHA-1 digest.
sha256(key, string)strGenerate an HMAC-SHA-256 digest.
load("hmac.star", "hmac")

signature = hmac.sha256("secret", "message")

Humanize​

humanize.star converts dates, quantities, byte counts, and number values into display-friendly strings.

FunctionPurpose
time(date)Format a date relative to now.
relative_time(date1, date2, label1?, label2?)Describe the difference between two dates, optionally using labels.
time_format(format, date?)Convert a Java-style date format to a Go layout and optionally format a date.
day_of_week(date)Return the weekday from 0 for Sunday through 6 for Saturday.
bytes(size, iec?)Format a byte count with SI or optional IEC units.
parse_bytes(formatted_size)Convert a formatted byte value back to a number.
comma(num)Add thousands separators to a number.
float(format, num)Format a floating-point value with a pattern.
int(format, num)Format an integer with a pattern.
ordinal(num)Format a number as an ordinal such as 1st.
ftoa(num, digits?)Convert a float to text without trailing zeros.
plural(quantity, singular, plural?)Combine a quantity with the correct singular or plural label.
plural_word(quantity, singular, plural?)Return the correct singular or plural word.
word_series(words, conjunction)Join words into an English list.
oxford_word_series(words, conjunction)Join words into an English list with an Oxford comma.
url_encode(str)Percent-encode text for a URL.
url_decode(str)Decode percent-encoded URL text.
load("humanize.star", "humanize")

storage = humanize.bytes(82854982)
visits = humanize.comma(123456)
position = humanize.ordinal(3)

XPath​

xpath.star parses XML and extracts text or nested nodes with XPath queries.

FunctionReturnsPurpose
loads(doc)xpath objectParse an XML string.

Parsed XPath objects provide these methods:

MethodReturnsPurpose
query(path)strRead the first matching node's text.
query_all(path)[str]Read text from all matching nodes.
query_node(path)xpath objectRead the first matching node for further queries.
query_all_nodes(path)[xpath]Read all matching nodes for further queries.
load("xpath.star", "xpath")

FEED = """
<forecast>
<day><high>24</high></day>
<day><high>27</high></day>
</forecast>
"""

def forecast_highs():
document = xpath.loads(FEED)
return document.query_all("/forecast/day/high")

Render​

render.star contains the widgets used to compose the 64 × 32 display. Every app returns a render.Root from main.

load("render.star", "render")

def main(config):
return render.Root(
child = render.Box(
width = 64,
height = 32,
color = "#111827",
child = render.Text("Hello", color = "#f9fafb"),
),
)

See the widget reference for every available render primitive.

Schema​

schema.star declares the settings displayed when someone configures an app. The saved values are passed to main(config) under each field's identifier.

load("render.star", "render")
load("schema.star", "schema")

def main(config):
return render.Root(
child = render.Text(config.get("message", "Hello")),
)

def get_schema():
return schema.Schema(
version = "1",
fields = [
schema.Text(
id = "message",
name = "Message",
desc = "Text shown on the display",
icon = "message",
default = "Hello",
),
],
)

Secret​

secret.star decrypts values created with tetra encrypt. A secret decrypts in the SolidPixels render environment for its intended app. Local rendering returns None, so accept a development value through config when needed.

FunctionReturnsPurpose
decrypt(value)str or NoneDecrypt an app-bound encrypted value.
load("secret.star", "secret")

ENCRYPTED_API_KEY = "..."

def api_key(config):
return secret.decrypt(ENCRYPTED_API_KEY) or config.get("dev_api_key")

Never commit a plaintext production secret to an app.

Sunrise​

sunrise.star calculates solar events and elevation for a location.

FunctionPurpose
sunrise(lat, lng, date)Calculate sunrise for a location and date.
sunset(lat, lng, date)Calculate sunset for a location and date.
elevation(lat, lng, time)Calculate the sun's elevation at a point in time.
elevation_time(lat, lng, elev, date)Return the two times the sun reaches an elevation, or None when it does not.
load("sunrise.star", "sunrise")
load("time.star", "time")

def solar_times(latitude, longitude):
today = time.now()
return (
sunrise.sunrise(latitude, longitude, today),
sunrise.sunset(latitude, longitude, today),
)

Random​

random.star generates pseudorandom integers. Tetra automatically seeds the generator for each execution; call seed when you need a repeatable sequence.

FunctionReturnsPurpose
seed(value)—Replace the current seed.
number(min, max)intReturn a value between min and max; min must be non-negative and lower than max.
load("random.star", "random")

def choose_message():
messages = ["Hello", "Welcome", "Good day"]
return messages[random.number(0, len(messages))]

QR code​

qrcode.star creates compact QR codes as image data that can be passed to render.Image. Keep the encoded value short because the display supports only small QR versions.

FunctionReturnsPurpose
generate(url, size, color?, background?)image dataGenerate a QR code from a short URL or text value.

Supported sizes are "small" (21 × 21), "medium" (25 × 25), and "large" (29 × 29).

app.star
load("qrcode.star", "qrcode")
load("render.star", "render")

def main(config):
image = qrcode.generate(
url = "https://solidpixels.io?utm_source=tetra_example",
size = "large",
color = "#ffffff",
background = "#000000",
)

return render.Root(
child = render.Box(
width = 64,
height = 32,
child = render.Image(src = image),
),
)
QR code generated by the qrcode module example