CalmPilot
App guide

Everything an app can do, in one page, for you and for an agent writing it with you. New to this? How to make an app follows one from a sentence to ScriptoHub.

Writing an app for CalmPilot

CalmPilot turns a small e-paper reader (the Xteink X4 Pro, the BOOX Picco) into a calm one. An app for it is a folder with a little Python in it. This guide is for you, and for an agent writing the app with you.

There is a small app at the end to copy and change. Real apps are worth reading too: every one on ScriptoHub has its source. Stocks gets prices from the network, Weather has tiles, Chess is a game.

The folder

File What it is
manifest.json What the app is called and what it needs
main.py The app
tile.py Its tiles for Home, if it has any
assets/ Pictures it draws, as PNG
data/ Text it reads, such as a word list
SKILL.md Its page on ScriptoHub, once you share it
manifest.json
{
  "app_id": "hello",
  "display_name": "Hello",
  "version": "1.0.0",
  "author": "You",
  "description": "Counts your taps.",
  "entry": "main.py",
  "api": "2.4",
  "icon": "hand-finger"
}
  • app_id: lowercase letters and digits. Name the folder the same, and use the same name on ScriptoHub.
  • api: the app API it is written to. "2.4" is right for most apps, "2.18" if you redraw part of the screen (below). Without it the app doesn't run.
  • icon: the name of any icon on tabler.io/icons.
  • "permissions": ["net"], if it uses the network.
  • "orientation": "landscape" opens it on its side. "header": false gives it the whole screen, without CalmPilot's top row.

Trying it on your reader

Put the folder on the reader's SD card as /sd/apps/hello/. It is in Apps at once. An agent connected to the reader can do this for you: in CalmPilot Studio, choose About, Show all of Studio, then the gear and Agent, and paste the line it gives you into a terminal. After a change, close the app and open it again.

If an app fails, the reader says what went wrong in place of it, and Studio's terminal has the rest. print() and ctx.log.info("...") go to that terminal as well.

How an app runs

CalmPilot calls functions in main.py. Write the ones you need:

Function When
on_load(ctx) Once, as the app opens
on_draw(ctx, g) To draw a frame: when it opens, and after ctx.invalidate()
on_input(ctx, ev) A tap, a swipe or a key
on_tick(ctx, dt) Every so often, if you asked with ctx.set_tick(ms)
on_pause(ctx), on_resume(ctx) The keyboard opens over the app, and closes
on_leave(ctx) As the app closes

Nothing is drawn until you ask. Change what you keep, then call ctx.invalidate(), and on_draw is called with a clean chance to draw it all.

main.py
taps = 0


def on_draw(ctx, g):
    g.clear()
    g.text(240, 300, "Tapped %d times" % taps, align="center")


def on_input(ctx, ev):
    global taps
    if ev.type == "pointer" and ev.phase == "up":
        taps += 1
        ctx.invalidate()
        return True
    return False

It is MicroPython, not full Python: no pip packages, and a smaller standard library. The app can have several .py files and import its own.

The screen

480 wide and 748 high, under CalmPilot's top row, which shows the time, the app's name and the battery. (0, 0) is the top left of your part. It is black ink on white paper: no greys, no colour.

g draws:

Call What it draws
g.clear() White over everything
g.text(x, y, s, font=, align=, valign=, bold=) A line. align: left, center, right. valign: top, middle, baseline, bottom
g.text_box(x, y, w, h, s, font=, align=, overflow=) Text wrapped in a box. overflow="ellipsis" ends it with …
g.line(x0, y0, x1, y1, line_width=) A line
g.rect(x, y, w, h, fill=, radius=, line_width=) A box, outlined, or filled with fill=True
g.circle(cx, cy, r, fill=, line_width=) A circle
g.polyline([x0, y0, x1, y1, ...], line_width=) Joined lines, such as a chart
g.polygon([...], fill=True) A shape
g.icon(name, cx, cy, size=) Any icon from tabler.io, centred
g.image(picture, x, y) A picture, from ctx.package.image("name") for assets/name.png

To draw in white over something filled, pass color=0; ink is the default.

Fonts are ctx.fonts.small, ctx.fonts.medium and ctx.fonts.large (20, 24 and 30 pixels a line), or ctx.fonts.size(72) for any size from 8 to 200. font.measure("text") gives its width.

CalmPilot's own buttons and rows

Use these and your app looks at home on the reader:

main.py
from lib.ext.calmpilot import parts as ui

done = None


def on_draw(ctx, g):
    global done
    g.clear()
    ui.info(g, "Score 40", "Best 112")                 # the line under the top row
    ui.row(g, 0, ui.INFO_H, 480, ui.ROW_H, "Fremont", "California")
    done = ui.button(g, ui.PAD, 676, 432, ui.BUTTON_H, "Done", primary=True)


def on_input(ctx, ev):
    if ev.type == "pointer" and ev.phase == "up" and ui.hit(done, ev.x, ev.y):
        ctx.quit()
    return ev.type == "pointer"
Part What it is
ui.info(g, left, right) The line at the top. Your part starts below ui.INFO_H
ui.button(g, x, y, w, h, label, primary=, enabled=) A button. Gives its rectangle, for ui.hit
ui.buttons(g, x, y, w, h, [labels]) A row of them. Gives a list of rectangles
ui.tabs(g, x, y, w, h, [labels], current=) A choice of a few
ui.row(g, x, y, w, h, heading, sub) A row of a list
ui.rule(g, x, y, w) A thin line between things
ui.box(g, x, y, w, h) A rounded box
ui.tile(g, x, y, w, h, text) A square of a board
ui.dialog(g, heading, text, [labels]) A question. Gives the buttons' rectangles
ui.hint(g, text) A line at the foot, saying how it works
ui.hit(rectangle, x, y) Whether a tap was in it

Taps, swipes and keys

ev in on_input(ctx, ev) is one of these:

  • A touch, ev.type == "pointer". ev.phase is "down", then "up". At "up", ev.gesture is "tap", "double_tap", "swipe_left", "swipe_right", "swipe_up" or "swipe_down". ev.x and ev.y are where. Act on "up".
  • A key, ev.type == "key". ev.key is "up" or "down" for the side keys, or "back", which is a short press of the power key or a swipe in from the right edge.

Back matters. When "back" comes with ev.phase == "up", return True if you stepped back a screen inside the app. Return False and the app closes. An app that always returns True can't be left that way. A swipe up from the bottom edge goes Home and closes the app without asking, so keep what matters in ctx.state as it changes.

To ask for some text, with the reader's keyboard:

main.py
def ask(ctx):
    def typed(ctx, text):              # None if they cancelled
        if text:
            ctx.state["name"] = text
        ctx.invalidate()
    ctx.input.text({"title": "Your name", "text": ""}, typed)

Keeping things

  • ctx.state is a dict that is saved as the app closes, and is there when it opens again. Keep plain values in it: text, numbers, lists, dicts. ctx.save_state() saves it now.
  • ctx.storage is the app's own files: write(name, text), read(name) (None if there isn't one), remove(name), list(). They stay when the app is updated, or removed and got again.
  • ctx.json: encode(value) and decode(text).

Calls that fail give None, and ctx.err says why.

The network

With "permissions": ["net"] in the manifest. One request at a time; the answer comes to your function later, and the app goes on meanwhile:

main.py
def fetch(ctx):
    def done(ctx, resp):
        if resp.ok and resp.status == 200:
            ctx.storage.write("last.json", resp.body)
        ctx.invalidate()
    ctx.net.request({"url": "https://example.com/data.json", "timeout_ms": 20000}, done)

resp.ok is False when nothing came, and resp.err is then "no_network", "timeout" or another short word. resp.body is text, up to 128 KB. method, headers and body can be given too.

Keep what you fetch, and show that first. The app then opens at once, with no network, and its tile on Home has something to show.

Anything in an app can be read by everyone who gets it, so never put a password or a key of yours in one.

Time

ctx.clock.now() gives year, month, day, hour, minute, second, weekday (Sunday is 0) and epoch_sec. Check valid first: a reader that has never been online may not know the time. ctx.clock.millis() is for measuring how long something took.

ctx.after(ms, fn) calls fn(ctx) once, later. ctx.set_tick(ms) calls on_tick again and again; ctx.set_tick(0) stops it.

Being good on e-paper

  • Draw when something changed. Each frame takes part of a second and a little battery.
  • Keep black areas small. Large ones leave a ghost behind. CalmPilot clears ghosts itself every so often; ctx.invalidate("full") asks for it now.
  • Redraw a part with ctx.invalidate(x, y, w, h) ("api": "2.18"). Only that rectangle is cleared and refreshed, and ctx.dirty says which it is.
  • Make things to tap at least 48 pixels each way.
  • Stay calm. No badges, nothing that ticks for its own sake, nothing that calls for attention.

Settings in CalmPilot Studio

Typing is slow on e-paper, so your app can be set from CalmPilot Studio. Say what can be set in the manifest, and Studio draws the form, in Get apps under the app's Settings:

manifest.json
"settings": [
  {"key": "symbols", "label": "Stocks", "type": "list", "max": 8, "upper": true,
   "placeholder": "ANT", "hint": "Ticker symbols."}
]

type is "list" (short texts, max of them), "text", or "choice" with its "choices". What is set is the file settings.json in ctx.storage, such as {"symbols": ["ANT"]}. Read it as the app opens, and have a default for when it isn't there.

Sharing it

Add a SKILL.md to the folder. It is the app's page, and the lines at its top say what it is:

SKILL.md
---
name: "Hello"
description: "Counts your taps."
version: 1.0.0
category: Apps
requires:
  needs: [display, touch]
---

Counts your taps, and remembers them.

category: Apps is what puts it in Get apps. Then open scriptohub.ai/upload, sign in with GitHub, drop the folder on the page and press Publish ScriptO. It is checked for malware first, which takes from a minute to an hour or more, and then every CalmPilot reader can get it. Each update is checked too, and the app is hidden meanwhile.

To update it, raise version in both manifest.json and SKILL.md, and upload it again.

The upload page takes text files only for now, so leave pictures out of the folder. An app that needs pictures to run can't be shared that way yet.

Tiles for Home

Home on a CalmPilot reader is a grid of tiles, two across and four down, which its owner arranges in CalmPilot Studio. Every app has a plain tile, its icon and its name. Yours can also offer tiles that say something: the weather now, today's word count, three share prices. A tap on one opens the app.

A tile only shows. It can't be tapped in parts, and it doesn't call for attention.

Offer it in the manifest

manifest.json
"tiles": [
  {"name": "count", "title": "Taps", "sizes": ["1x1", "2x1"], "every": "data"}
]
  • name: yours to choose, lowercase.
  • title: what Studio calls it.
  • sizes: those it comes in. Across, then down.
  • every: when it may change, and so when Home draws it again.
  • opts, if you like: choices for its owner, such as {"look": ["digits", "flip"]}. The first is the default.
Size Room you draw in
1x1 202 x 154 One thing
2x1 432 x 154 One thing and a little more, or three short rows
1x2 202 x 336 A narrow list
2x2 432 x 336 Something worth the space. If it is the 2x1 again, leave it out
every Home draws it again
"data" When the app's own files change
"minute", "hour", "day" That often
"never" Only with the rest of Home

Write tile.py

Beside main.py, with one function. The short way is to give CalmPilot a few words, and it lays them out as it does every app's:

tile.py
def tile(ctx, name, size, opts):
    n = ctx.state.get("taps", 0)
    return {"label": "Hello", "value": str(n), "line": "taps so far", "icon": "hand-finger"}

value is large, label small above it, line under it, and icon at the top right. Leave out any you don't need.

Or draw it yourself, with the same g as in main.py, and return None:

tile.py
def tile(ctx, name, size, opts):
    g, w, h = ctx.g, ctx.screen.width, ctx.screen.height
    g.text(w // 2, h // 2, "Hello", font=ctx.fonts.large, align="center", valign="middle")
    return None

Its box is drawn for you. You can do both, by size.

What a tile has

ctx.g, ctx.screen, ctx.fonts, ctx.clock, ctx.json, ctx.package, and ctx.state and ctx.storage to read.

It has no network and can't save. Home loads tile.py alone, never main.py, and the tile shows what was kept. Two things follow:

  • Say something useful when nothing is kept yet, such as "Waiting for prices".
  • If what is kept can be old, say how old.

Put what main.py and tile.py share in a file of its own, and import it from both. Stocks does this with quotes.py.

Keep it quick: it runs while Home is being drawn.

Fetch what it shows

A tile from the network should fill by itself, without its app being opened. Put a second function in tile.py, and "permissions": ["net"] in the manifest:

main.py
def fetch(ctx, name):
    now = ctx.clock.now()
    kept = ctx.json.decode(ctx.storage.read("last.json") or "{}")
    if not now.valid or now.epoch_sec - kept.get("at", 0) < 3600:
        return

    def done(ctx, resp):
        if resp.ok and resp.status == 200:
            ctx.storage.write("last.json", ctx.json.encode({"at": int(now.epoch_sec), "text": resp.body}))
    ctx.net.request({"url": "https://example.com/data.json", "timeout_ms": 20000}, done)

Home calls it about once a minute while it is showing and the reader is on Wi-Fi, so return at once if what you have is fresh enough. Once the answer is in, Home draws the tile again. After a request it waits five minutes before it calls again, and nothing is fetched while the reader sleeps. ctx has net, storage to read and write, state to read, clock and json, and nothing to draw on.

A picture of it for Studio

In Studio, where Home is arranged, your tile is shown by a picture of it that comes with the app on ScriptoHub: studio/tile-<name>-<size>.png, such as studio/tile-count-1x1.png. Make it look as the tile does with something in it.

Size Picture, in pixels
1x1 218 x 170
2x1 448 x 170
1x2 218 x 352
2x2 448 x 352

At most 40 KB each. For another choice of an option, add it to the name: studio/tile-clock-1x1-flip.png. Without a picture, Studio shows the app's icon and the tile's title. ScriptoHub's upload page takes text files only for now, so that is what an app shared from there shows.

A small app to start from

Hello counts your taps and remembers them, with a tile for Home. Make a folder called hello with these three files in it, put it in /sd/apps/ on the reader's card, and open it from Apps.

hello/manifest.json
{
  "app_id": "hello",
  "display_name": "Hello",
  "version": "1.0.0",
  "author": "You",
  "description": "Counts your taps, and remembers them.",
  "entry": "main.py",
  "api": "2.4",
  "icon": "hand-finger",
  "tiles": [
    {"name": "count", "title": "Taps", "sizes": ["1x1", "2x1"], "every": "data"}
  ]
}
hello/main.py
# Hello: counts your taps, and remembers them. A small app to start from.
from lib.ext.calmpilot import parts as ui      # CalmPilot's own buttons and rows

again = None                                    # where the button was last drawn


def on_draw(ctx, g):
    global again
    taps = ctx.state.get("taps", 0)
    g.clear()
    ui.info(g, "Tap anywhere")
    g.text(240, 240, str(taps), font=ctx.fonts.size(120), align="center")
    g.text(240, 400, "tap" if taps == 1 else "taps", font=ctx.fonts.large, align="center")
    again = ui.button(g, ui.PAD, 676, 432, ui.BUTTON_H, "Start again", enabled=taps > 0)


def on_input(ctx, ev):
    if ev.type != "pointer":
        return False                            # Back closes the app
    if ev.phase == "up":
        if ui.hit(again, ev.x, ev.y):
            ctx.state["taps"] = 0
        else:
            ctx.state["taps"] = ctx.state.get("taps", 0) + 1
        ctx.invalidate()                        # draw it again
    return True
hello/tile.py
# Hello's tile on Home: the taps so far, from what the app keeps.
def tile(ctx, name, size, opts):
    n = ctx.state.get("taps", 0)
    return {"label": "Hello", "value": str(n), "line": "tap so far" if n == 1 else "taps so far", "icon": "hand-finger"}