# Script reference (https://docs.palpable.technology/docs/developers/script-reference)

Every script gets one object, `p`, and everything a script can do on your board goes through it. This page lists all of it, read from the same file PAL's scripts are checked against. It describes the newest version: a board on older software, and ESP32 boards, can do less. See [Scripts](/docs/developers/scripts) for which.

The code under each heading shows how it is written in a script, often with notes after `//` that PAL reads too. Some say `Promise`: put `await` in front of those, or the script carries on before the answer arrives.

## p.config [#pconfig]

Current param values. Read inside loops/callbacks for live tweaking.

```ts
readonly config: Record<string, any>           // Current param values — read inside loops/callbacks
```

## p.onConfigChange [#ponconfigchange]

Called when user tweaks params. Prevents script restart.

```ts
onConfigChange(cb: (config: any) => void): void // Live param updates without restart
```

## p.read [#pread]

Read a cached sensor value.

```ts
// Cached sensor value. THE TWO FORMS RETURN DIFFERENT SHAPES:
//   read(id, cap) -> that capability's value:  p.read("modulino-buttons", "buttons")  -> 3
//   read(id)      -> a { cap: value } MAP:     p.read("modulino-buttons")             -> { buttons: 3 }
// It is NEVER an array and never objects with a .state field. EMPTY until the first poll
// lands (undefined on the current bridge, null on older ones) — so always guard with
// "?? default", never "=== undefined". Prefer the two-arg form — it is unambiguous.
read(moduleId: string, cap?: string): any
```

## p.write [#pwrite]

Send a command to a module. The command and its params come from the module's own declared
`encoding`, so only commands the module understands can be written here.

```ts
write(moduleId: string, cmd: string, params?: any): void  // Hardware command
```

## p.writeRaw [#pwriteraw]

Send raw bytes straight to a module. A last resort: use `p.write`, or a frame builder such as
`p.pixels.frame`, whenever the module has one.

```ts
writeRaw(moduleId: string, data: number[]): void // Raw I2C bytes. LAST RESORT — see the builders below
```

## p.pixels [#ppixels]

Drive an addressable LED strip. Builds the exact frame the module declares — LED count,
channel order and brightness header all come from `@palpable/modules`, so you state neither a
byte count nor a colour order. Synchronous, like `p.writeRaw`. Prefer this over `p.writeRaw`
for any module that has it: a hand-rolled frame is the 2026-07-31 Mood Light defect, where
25 bytes in RGB reached a strip that needed 32 in BGR, nothing errored, and it stayed dark.

```ts
// Frame BUILDERS. Use these instead of writeRaw for any module that has one: the LED count,
// the channel order and the brightness header come from the module catalogue, so you state
// neither a byte count nor a colour order and cannot get either wrong. Both are synchronous.
pixels: { frame(colorOrPixels, opts?: { brightness?: number }): void } // whole strip, or per-LED array
```

## p.matrix [#pmatrix]

Draw on a single-colour LED matrix. Rows top-to-bottom; in a row string use `#` for lit and `.`
for dark. Every other character also lights ONE pixel (space and `0` are dark), so a letter
typed into a row is a dot, never a letter — draw letters as shapes. A row may instead be an
array of brightness cells 0-255; a grayscale panel shows only a few states (the UNO Q: off plus
five lit levels; see the module's guidance for the named levels). Synchronous.

```ts
matrix: { frame(rows: Array<string | number[]>): void }                // rows top-to-bottom; '#' lit, '.' dark (any other char is ONE dot, not a letter); or 0-255 per pixel
//   & icon(name) text(s) scroll(s) number(n, { unit }) compose(icon, text) glyph(name): string[] icons() — see "LED matrix"
//   p.pixels.frame('#ff6600', { brightness: 12 })
//   p.pixels.frame([{ r: 255 }, { g: 255 }, { b: 255 }])
//   p.matrix.number(23)    p.matrix.frame(['..##..', '.####.', '######'])
```

## p.onSensorChange [#ponsensorchange]

Subscribe to sensor changes. Returns unsubscribe function.

```ts
onSensorChange(moduleId: string, cap: string, cb: (v: any) => void): () => void
```

## p.sleep [#psleep]

Async delay (cancellable via p.signal).

```ts
sleep(ms: number): Promise<void>                // Async delay (cancellable)
```

## p.waitUntilStopped [#pwaituntilstopped]

Keep script alive for event-driven patterns. REQUIRED at end.

```ts
waitUntilStopped(): Promise<void>               // Keep alive (REQUIRED at end)
```

## p.signal [#psignal]

Aborted when the script stops. A `ScriptSignal` — the part of the DOM `AbortSignal` every engine
actually implements — not `AbortSignal` itself.

`p.signal` — aborted when the script stops.

```ts
readonly signal: ScriptSignal                   // Aborted when the script stops: .aborted, .reason, .addEventListener('abort', cb), .throwIfAborted()
```

### p.signal.aborted [#psignalaborted]

True once the script has been told to stop. Read it as the condition of a polling loop.

```ts
readonly aborted: boolean;
```

### p.signal.reason [#psignalreason]

Why it stopped — an `Error` named `AbortError`. `undefined` until then.

```ts
readonly reason: any;
```

### p.signal.onabort [#psignalonabort]

Called once when the script stops, like the DOM property.

```ts
onabort: ((event: { type: 'abort' }) => void) | null;
```

### p.signal.addEventListener [#psignaladdeventlistener]

Run `listener` once when the script stops. Only `'abort'` exists. A listener added after the
script has already stopped never runs — check `aborted` first if that matters.

```ts
addEventListener(type: 'abort', listener: (event: { type: 'abort' }) => void, options?: { once?: boolean }): void;
```

### p.signal.removeEventListener [#psignalremoveeventlistener]

```ts
removeEventListener(type: 'abort', listener: (event: { type: 'abort' }) => void): void;
```

### p.signal.throwIfAborted [#psignalthrowifaborted]

Throw `reason` if the script has been stopped — a one-line guard at the top of a long loop body.

```ts
throwIfAborted(): void;
```

## p.onStop [#ponstop]

Register cleanup callback for when script stops.

```ts
onStop(cb: () => void): void                    // Cleanup callback
```

## p.log [#plog]

Script log (forwarded to cloud).

```ts
log(msg: string): void                          // Script log
//   numbers: p.log(`${t.toFixed(1)} °C`) — the board has no Intl / toLocaleString
```

## p.notify [#pnotify]

Push notification to user's device.

```ts
notify(msg: string): void                       // Push notification
```

## p.getVariable [#pgetvariable]

Get shared variable value.

```ts
getVariable(name: string): any
```

## p.setVariable [#psetvariable]

Set shared variable value.

```ts
// A screen's view reads each value as variables.<name>.
setVariable(name: string, value: any): void
```

## p.onVariableChange [#ponvariablechange]

Subscribe to shared variable changes.

```ts
onVariableChange(name: string, cb: (v: any) => void): void
```

## p.loadState [#ploadstate]

Load persistent state (survives restarts). SYNCHRONOUS — it returns the merged object, not a
promise: the engine has the persisted state in hand before the script body runs and
`p_load_state` is registered `from_fn_ptr`, not `from_async_fn`
(`palpable-bridge-rs/crates/scripting/src/lib.rs:1940`).

```ts
// SYNCHRONOUS — returns the merged object, not a promise. `await` also works (awaiting a
// non-promise yields the same object), so both forms are correct and neither needs changing.
loadState(defaults: Record<string, any>): Record<string, any>
```

## p.saveState [#psavestate]

Save persistent state.

```ts
saveState(state: Record<string, any>): void
```

## p.random [#prandom]

A random number, in two forms — and the difference between them is the whole point.

```ts
// p.random(min, max) with whole numbers is an INTEGER, both ends included; p.random() is a FLOAT in [0, 1).
// So list[p.random(0, list.length - 1)] is a correct pick, p.random(1, 6) is a die, and p.random(0, 1)
// is a coin (0 or 1), never a probability: `if (p.random() < 0.1)` is true one time in ten.
random(): number
random(min: number, max: number): number
```

## p.connector [#pconnector]

Call cloud connector. Times out after 30s. Resolves to the tool's parsed fields; `{}` on failure;
`{ error: 'location_not_set', message }` when the tool needs a place and none is set (the
container's `connectorResultForScripts` — the only failure a script can tell apart).

```ts
// ALWAYS await. Resolves within 30s; {} on failure; { error: 'location_not_set' } with no place set.
// Without await you hold a pending Promise and every field reads undefined — silently.
connector(connectorId: string, toolName: string, params?: any): Promise<any>
```

## p.waitFor [#pwaitfor]

Wait for sensor condition.

```ts
// Wait for ONE reading and resolve with it — ALWAYS await. Two things the signature cannot say:
// (1) EDGE-TRIGGERED. It rides the same change gate as onSensorChange, so a value that ALREADY
//     satisfies the condition resolves NOTHING — only a reading that CHANGES does. A button
//     already held, a door already open: read the current value first, then wait for the change.
// (2) It resolves `null` on timeout instead of throwing, and `timeout` defaults to 30000ms —
//     there is no way to wait forever. A null is indistinguishable from a reading unless you
//     check for it, so an unchecked result silently means "it never happened".
//   const b = await p.waitFor('modulino-buttons', 'buttons', { timeout: 5000 })
//   if (b === null) p.log('nobody pressed it')
waitFor(moduleId: string, cap: string, opts?: { timeout?: number; condition?: (v: any) => boolean }): Promise<any>
```

## p.stateMachine [#pstatemachine]

Create a state machine.

```ts
stateMachine(config: { initial: string; states: Record<string, any> }): { current: string; send: (event: string) => void; on: (event: 'transition', cb: (t: { from: string; to: string; event: string }) => void) => void }
```

## p.map [#pmap]

Linear re-map of a value from one numeric range to another.

```ts
// Linear re-map between two numeric ranges. USE THIS — do not hand-roll
//   outMin + (value - inMin) / (inMax - inMin) * (outMax - outMin)
// The input bounds are handed to you in physical_context as `[range lo..hi]`, so there is
// nothing to guess; hand-rolled versions get the input span subtly wrong (off-by-one between
// the wrap modulus and the divisor) and the error is invisible until it runs on hardware.
map(value: number, inMin: number, inMax: number, outMin: number, outMax: number): number
```

## p.clamp [#pclamp]

Confine a value to a range. Reversed bounds are tolerated.

```ts
clamp(value: number, min: number, max: number): number // Confine to a range. Use instead of Math.max(lo, Math.min(hi, v))
```

## p.hsl [#phsl]

Colour from hue, saturation and lightness. Returns `{ r, g, b }` in 0-255 — exactly the shape
`p.pixels.frame` accepts, so the result passes straight through.

```ts
// Colour from hue/saturation/lightness -> { r, g, b } in 0-255, the shape p.pixels.frame takes.
// Hue is DEGREES and wraps both ways, so `hue += 30` needs no modulus. s/l accept EITHER scale
// (0.85 and 85 are the same colour) and default to a vivid mid colour, so p.hsl(200) is complete
// on its own.  p.pixels.frame(p.hsl(hue))
hsl(hue: number, saturation?: number, lightness?: number): { r: number, g: number, b: number }
```

## p.bind [#pbind]

Wire a sensor capability straight to an actuator parameter. Returns an unbind function.

```ts
// Wire a sensor straight to an actuator parameter. Returns an unbind function. PREFER THIS over a
// while-loop whenever the job is "keep this output following that input" — there is no interval to
// choose (it rides the sensor sweep) and it writes only when the OUTPUT changes, so it cannot
// flood the I2C bus. source: "moduleId:capability". target: "moduleId:command.param" or "var:name".
//   p.bind('modulino-knob:encoder', 'modulino-buzzer:tone.frequency', v => p.map(v, 0, 127, 200, 2000))
// Register bindings BEFORE the keep-alive, like listeners.
bind(source: string, target: string, transform?: (value: any) => any): () => void
```

## p.every [#pevery]

Run `callback` on a FIXED GRID every `intervalMs`. Returns a cancel function.

```ts
// Run a callback on a FIXED GRID. Returns a cancel function. THIS IS HOW A SCRIPT GETS A TEMPO.
// Every deadline is measured from one anchor taken when the timer starts, so the period is
// intervalMs no matter what the callback costs — a "500ms" beat stays 500ms while the body does
// an I2C write, and stays in phase with any other p.every on the board. If the callback outlasts
// its interval the missed slots are DROPPED (never queued into a burst) and reported as
// tick.dropped; tick.lateMs is how far past its slot the tick actually started.
// The callback is SYNCHRONOUS — nothing awaits it.
//   p.every(500, () => p.write('modulino-buzzer', 'tone', { frequency: 880, duration_ms: 40 }))
// Register timers BEFORE the keep-alive, like listeners.
every(intervalMs: number, callback: (tick: { count: number; lateMs: number; dropped: number }) => void): () => void
```

## p.animate [#panimate]

Animate a number from `from` to `to` over `ms` along a named curve, calling `onValue` once per
frame (every `frameMs`, default 50) and once more with exactly `to`. What the value means is the
script's: brightness, hue, a pixel offset, an angle. Resolves when the motion ends; stops at the
next frame when the script stops. The curves are the servo's (@palpable/motion).

```ts
// Move any output along a curve; the callback gets each frame's value. Resolves at the end.
// What the value means is yours: brightness, hue, a pixel offset. Frames every frameMs (default
// 50), the last call is exactly `to`, and it stops at the next frame when the script stops.
// curve: 'natural' (default, alive) | 'easeOut' (arriving) | 'easeIn' (leaving) | 'easeInOut'
//        | 'spring' | 'bounce' | 'elastic' | 'anticipate' (wind-up) | 'linear' (machine)
//   await p.animate({ from: 0, to: 1, ms: 800, curve: 'easeOut' }, (v) => p.pixels.frame(p.hsl(30, 1, 0.5 * v)))
animate(opts: { from: number; to: number; ms: number; curve?: Curve; frameMs?: number }, onValue: (value: number) => void): Promise<void>
```

## p.gesture [#pgesture]

One of the servo's five gestures on any output: `onValue` gets a value around `center`
(default 0), `amount` wide (defaults: nod 25, wave 45, shake 10, point 50, breathe 15).
Resolves when the gesture ends; with `loop: true` it never does, until the script stops.

```ts
// The servo's gestures on any output; the callback gets values around `center` (default 0).
// nod = "yes, I heard you"; shake = "no"; wave = hello/bye (count, default 3); point = "look
// there" (holds holdMs, default 2000); breathe = resting (bpm, default 12). amount defaults:
// nod 25, wave 45, shake 10, point 50, breathe 15. loop: true never resolves: await it last.
//   await p.gesture('nod', { center: 0.5, amount: 0.5 }, (v) => p.pixels.frame(p.hsl(30, 1, 0.5 * v)))
gesture(name: Gesture, opts: { center?: number; amount?: number; count?: number; bpm?: number; holdMs?: number; loop?: boolean; frameMs?: number }, onValue: (value: number) => void): Promise<void>
```

## p.smoother [#psmoother]

Build an exponential smoother with a time constant in ms. Returns a function you call with
each new reading; it returns the smoothed value.

```ts
// Exponential smoothing with a TIME CONSTANT. Returns a function — call it with each reading.
// Use instead of `x = x * s + next * (1 - s)`: that moves a fixed fraction PER CALL, so how much
// it smooths depends on how fast your loop happens to run. This one depends only on the time
// constant. A non-number reading holds the last good value instead of returning NaN.
//   const smooth = p.smoother(300); p.onSensorChange(id, cap, (v) => { const steady = smooth(v) })
smoother(timeConstantMs: number): (value: number) => number
```

## p.booleanizer [#pbooleanizer]

Build an analogue→boolean converter with a dead band. Returns a function you call with each
reading; it returns a boolean.

```ts
// Analogue → boolean with a dead band: true at threshold + hysteresis/2, false again only at
// threshold - hysteresis/2. Prevents the chatter you get from a bare `v > threshold` when the
// reading sits on the line (flickering dusk lights, buzzing relays). Returns a function.
//   const isDark = p.booleanizer(120, 20); ... if (isDark(lux)) p.write(...)
booleanizer(threshold: number, hysteresis?: number): (value: number) => boolean
```

## p.detector [#pdetector]

Build a detector that learns what this sensor normally reads, and reports departures from it.

```ts
// Learns what this sensor normally reads and reports DEPARTURES from it. Use instead of a
// threshold whenever "normal" belongs to the room rather than the sensor — ambient light moves
// what an APDS9960 calls proximity, so a doorbell tuned this morning misfires this afternoon and
// no better constant fixes it. Answers { active, confidence, baseline, deviation, learning }.
// `confidence` and `deviation` are DIFFERENT QUANTITIES: confidence is HOW SURE it is (0.5 means
// undecided, NOT "medium-sized"), deviation is HOW FAR OUT the reading is, in typical spreads.
// Gate on confidence to decide WHETHER to act; read deviation when you need HOW MUCH.
// `seed` carries the script until the baseline is trusted; confidence is capped at 0.4 until then.
// It stops adapting while active, so a person in the doorway never becomes "normal".
// On-device, offline, no model. `learned()` snapshots it for p.saveState; pass back as `restore`.
// `name` labels it in the day story: each earned (settled) inactive→active change is reported once (max 1/min).
//   const near = p.detector({ seed: 150, name: 'someone at the door' }); ... const d = near(prox); if (d.active) ring()
detector(options?: { id?: string; seed?: number; sensitivity?: 'twitchy' | 'balanced' | 'certain' | number; direction?: 'above' | 'below' | 'either'; learnMs?: number; adaptMs?: number; spreadFloor?: number; name?: string }): ((value: number) => { active: boolean; confidence: number; baseline: number | null; deviation: number; learning: boolean; settled: boolean; stuck: boolean }) & { learned(): object }
```

## p.audio [#paudio]

Whole sound files from this project's library — alarms, clips, loops — mixed with `p.chime`
at the board's speaker. See `Audio`.

`p.audio` — whole files, played by the board itself and mixed with `p.chime`.

```ts
readonly audio: Audio                            // Sound files: await p.audio.play('ding').ended(); or c = p.audio.play('x', {loop:true}); c.stop()
```

### p.audio.play [#paudioplay]

Start a file. `asset` is the key of an `audio` param (looked up via p.config) or an asset id.

```ts
play(asset: string, opts?: { gain?: number; loop?: boolean }): AudioClip;
```

#### p.audio.play(…).stop [#paudioplaystop]

Stop this clip (a short fade, never a click).

```ts
stop(): void;
```

#### p.audio.play(…).ended [#paudioplayended]

Resolves once the clip has finished sounding. A `loop: true` clip ends only when stopped.

```ts
ended(): Promise<void>;
```

### p.audio.stopAll [#paudiostopall]

Stop every clip THIS script started (other scripts' clips keep playing).

```ts
stopAll(): void;
```

### p.audio.output [#paudiooutput]

What can play files right now:
- `'speaker'` a speaker or headphone card — files play.
- `'piezo'`   only a buzzer — files cannot play on it; use `p.chime` for feedback.
- `'none'`    nothing that makes sound.
A reading of NOW, not a fixed fact: a speaker that was unplugged or failed to open can come
back (reading this asks for it). Don't skip `play()` on it — play, and a failed play reports
itself on the script's error channel.

```ts
readonly output: 'speaker' | 'piezo' | 'none';
```

## p.chime [#pchime]

A short feedback sound — a tap, a confirm, an alert. A sound you STRIKE: there is no
note-off, no sustain and no volume, because the decay is the whole sound.
See `Chime` for why each of those is absent rather than missing.

`p.chime` — one voice for feedback: a struck wooden body, warm and short.

```ts
readonly chime: Chime                            // The struck feedback voice. See the Sound section — no volume and no note-off
```

### p.chime.strike [#pchimestrike]

Strike the voice once. Returns immediately — a struck sound has nothing to await.
`pitch` is semitones from the patch root (a number) or a note name (`'C3'`).
`soft` (0–1) is mallet hardness: 0 is a hard, knocky striker, 1 is soft and round.

```ts
strike(opts?: { pitch?: number | string; soft?: number }): void;
```

### p.chime.play [#pchimeplay]

Play a score, resolving once the LAST strike has decayed — not when it was dispatched.
Each step is semitones from the root (number), a note name (`'C3'`), or `'·'` for a rest.
The engine owns the clock, so the rhythm cannot drift however long the score runs.

```ts
play(score: Array<number | string>, opts?: { bpm?: number; soft?: number }): Promise<void>;
```

### p.chime.patch [#pchimepatch]

Shape the voice. Keys are a CLOSED set — an unknown one throws rather than being ignored:
`attackMs`, `releaseMs`, `cutoffHz`, `spaceMix`, `rootHz`, `mallet`, `pitchDrop`,
`partialRatio`, `partialGain`. Defaults are the house sound; you rarely need this.

```ts
patch(patch: {
    attackMs?: number;
    releaseMs?: number;
    cutoffHz?: number;
    spaceMix?: number;
    rootHz?: number;
    mallet?: number;
    pitchDrop?: number;
    partialRatio?: number;
    partialGain?: number;
  }): void;
```

### p.chime.stop [#pchimestop]

Silence now, and cancel a score that is still playing.

```ts
stop(): void;
```

### p.chime.backend [#pchimebackend]

What this board can actually do — never a guess.
- `'pcm'`   a speaker: the full voice.
- `'piezo'` a buzzer only: pitch and rhythm survive, timbre and dynamics do not. It plays an
alert instead, and says so once in the log.
- `'none'`  nothing that makes sound. Calls are safe no-ops.
Branch on this rather than assuming sound happened.

```ts
readonly backend: 'pcm' | 'piezo' | 'none';
```

## p.synth [#psynth]

The instrument: a preset you play and turn with four knobs, and a 16-step pattern the board
keeps in time. It plays on the board's speaker — call it, do not test for the speaker first
(what the board reports about its output is a reading of now, never a gate). See `Synth`.

`p.synth` — the instrument. Start from a preset and turn its knobs; give rhythm to a PATTERN so the
board keeps time (a `p.sleep` loop drifts). Every call returns at once — nothing to await. Every
note ends. One tempo per board: a second pattern must use the playing pattern's bpm and swing.

```ts
synth: Synth
//   The instrument (the synth skill teaches it): const v = p.synth.voice('cozy-pad'); v.note('C4', { length: 2 }); p.synth.pattern({ voice: v, bpm: 92, steps: ['C3', null, 'G3', null] }).play()
```

### p.synth.voice [#psynthvoice]

A playable voice from a preset, with optional starting knobs.

```ts
voice(preset: SynthPreset, knobs?: SynthKnobs): SynthVoice;
```

#### p.synth.voice(…).note [#psynthvoicenote]

Play one note. `length` in seconds (default 0.5, max 30), `velocity` 0–1 (default 0.8).

```ts
note(note: NoteName, opts?: { length?: number; velocity?: number }): void;
```

#### p.synth.voice(…).set [#psynthvoiceset]

Turn knobs (0–1). Sounding notes follow.

```ts
set(knobs: SynthKnobs): void;
```

#### p.synth.voice(…).stop [#psynthvoicestop]

Release this voice's notes (they fade by their own release).

```ts
stop(): void;
```

### p.synth.pattern [#psynthpattern]

Up to 16 steps (16th notes; 16 are one bar) the board loops at their own length until `.stop()`.
Nothing sounds until `.play()`: it starts then, or on the next bar if another pattern is playing.
`bpm` 40–240; `swing` 0–1 delays every other step.

```ts
pattern(opts: { voice: SynthVoice; bpm: number; swing?: number; steps: SynthStep[] }): SynthPattern;
```

#### p.synth.pattern(…).play [#psynthpatternplay]

```ts
play(): void;
```

#### p.synth.pattern(…).stop [#psynthpatternstop]

```ts
stop(): void;
```

### p.synth.stop [#psynthstop]

Stop every pattern and note THIS script started.

```ts
stop(): void;
```

## p.pal [#ppal]

Fire-and-forget message to PAL (the AI agent) via the cloud. One-way —
one-way, and there is no two-way equivalent — `p.askPal` was shelved.

```ts
pal(message: string): void                       // Fire-and-forget note to PAL. One-way, and there is no two-way form
```

## p.on [#pon]

Register a listener for a custom cross-script event (paired with p.emit).

```ts
on(event: string, cb: (data: any) => void): void // Custom cross-script event (paired with p.emit)
```

## p.emit [#pemit]

Broadcast a custom event to other scripts' p.on listeners.

```ts
emit(event: string, data?: any): void            // Broadcast to other scripts' p.on listeners
```

## p.fetch [#pfetch]

HTTP request relayed via the cloud. Resolves to the RESPONSE, not its body: `body` is the raw
text, so JSON must be parsed — `const r = await p.fetch(url); if (r.ok) data = JSON.parse(r.body)`.
Resolves to `{}`-shaped (no `ok`) on a timeout or with no cloud. Prefer `p.connector` whenever a
connector covers the service (weather, …): it returns parsed fields and it shows on the map.

```ts
fetch(url: string, opts?: { method?: string; headers?: Record<string, string>; body?: string }): Promise<{ ok?: boolean; status?: number; headers?: Record<string, string>; body?: string }> // HTTP relayed via the cloud. Resolves to the RESPONSE: `body` is TEXT — `JSON.parse(r.body)` after checking `r.ok`. A connector (weather…) beats p.fetch: parsed fields, and it shows on the map
```

What it gives back:

```ts
interface FetchResponse {
  /** HTTP 2xx. Absent when the request timed out or there was no cloud to relay it. */
  ok?: boolean;
  /** HTTP status; 0 when the request never reached the server. */
  status?: number;
  headers?: Record<string, string>;
  /** The response body as TEXT. Parse it yourself: `JSON.parse(r.body)`. */
  body?: string;
}
```

## p.servo [#pservo]

Servo motion control. Returns a channel handle for one servo.
Available when a servo controller (e.g. Pi Servo pHAT) is detected.

Servo channel handle returned by `p.servo(channel)`.

```ts
servo(channel: number): ServoChannel             // Only when a servo controller (e.g. Pi Servo pHAT) is detected — see the Servo section
```

### p.servo(…).move [#pservomove]

```ts
// Standard servo (positional, 0-180°). Every method that describes a MOTION OVER TIME is async
// and resolves when the motion ends — await it, or the next line runs while the arm is still
// moving and the sequence you wrote never plays.
move(angle: number, opts?: { duration?: number; speed?: number; easing?: string }): Promise<void>
```

### p.servo(…).sweep [#pservosweep]

```ts
sweep(from: number, to: number, opts?: { duration?: number; speed?: number; easing?: string; loop?: boolean }): Promise<void>
```

### p.servo(…).play [#pservoplay]

```ts
play(keyframes: ServoKeyframe[], opts?: { loop?: boolean; speed?: number }): Promise<void>
```

### p.servo(…).nod [#pservonod]

```ts
nod(opts?: { amplitude?: number; center?: number }): Promise<void>
```

### p.servo(…).wave [#pservowave]

```ts
wave(opts?: { amplitude?: number; center?: number; count?: number }): Promise<void>
```

### p.servo(…).shake [#pservoshake]

```ts
shake(opts?: { amplitude?: number; center?: number }): Promise<void>
```

### p.servo(…).point [#pservopoint]

```ts
point(angle: number, opts?: { holdMs?: number }): Promise<void>
```

### p.servo(…).breathe [#pservobreathe]

```ts
breathe(opts?: { min?: number; max?: number; bpm?: number }): Promise<void>
```

### p.servo(…).home [#pservohome]

```ts
home(): Promise<void>
```

### p.servo(…).spin [#pservospin]

```ts
// Continuous rotation servo (velocity, -1 to 1)
spin(velocity: number, opts?: { duration?: number }): Promise<void>  // -1.0 to 1.0, 0 = stop
```

### p.servo(…).ramp [#pservoramp]

```ts
ramp(velocity: number, opts?: { duration?: number }): Promise<void>  // smooth acceleration
```

### p.servo(…).track [#pservotrack]

```ts
// These three write one register and return — they are synchronous, do NOT await them.
track(angle: number): void                     // smooth tracking (exponential smoothing)
```

### p.servo(…).setMode [#pservosetmode]

```ts
setMode(mode: 'standard' | 'continuous'): void // switch channel mode
```

### p.servo(…).stop [#pservostop]

```ts
stop(): void                                   // stop motor (continuous) or hold position (standard)
```

## p.mqtt [#pmqtt]

MQTT client (Pro tier — no-ops with a log if unavailable).

MQTT client exposed on p.mqtt (Pro tier).

```ts
readonly mqtt: MqttClient                        // Pro tier only. No-ops with a log when unavailable — never assume it connected
```

### p.mqtt.connect [#pmqttconnect]

```ts
connect(broker: string, options?: Record<string, any>): Promise<any>;
```

### p.mqtt.publish [#pmqttpublish]

```ts
publish(topic: string, payload: any, options?: { qos?: number }): void;
```

### p.mqtt.subscribe [#pmqttsubscribe]

```ts
subscribe(topic: string, callback: (topic: string, payload: any) => void): void;
```

### p.mqtt.disconnect [#pmqttdisconnect]

```ts
disconnect(): void;
```

## p.midi [#pmidi]

Network MIDI: the board is a MIDI device on the local Wi-Fi, so a music app on a Mac or PC
(Logic, Ableton, GarageBand…) plays from it and sends notes back to it. No cloud in the path.
Every call is synchronous and fire-and-forget; sending with no app connected is not an error.

`p.midi` — the board as a MIDI device on the local Wi-Fi (RTP-MIDI today). A music app on a Mac or
PC connects to it; the script sends notes and controller moves and hears the app's notes back.

```ts
// MIDI with a music app on the same Wi-Fi. Values 0..1 (pitch bend -1..1), channel 1..16, synchronous: never await
readonly midi: Midi
```

### p.midi.note [#pmidinote]

```ts
// Values are 0..1, channel 1..16 (default 1). Every call is synchronous: never await.
// A note needs `duration` (ms; the board sends its note-off) or a paired noteOff, or it sticks.
note(note: number | string, velocity?: number, opts?: { channel?: number; duration?: number }): void // 60 or 'C4' is middle C; velocity defaults to 0.8
```

### p.midi.noteOff [#pmidinoteoff]

```ts
noteOff(note: number | string, opts?: { channel?: number }): void // Ends a note sent without a duration
```

### p.midi.cc [#pmidicc]

```ts
cc(controller: number, value: number, opts?: { channel?: number }): void // controller 0..127, value 0..1. Send only when the value CHANGES
```

### p.midi.pitchBend [#pmidipitchbend]

```ts
pitchBend(value: number, opts?: { channel?: number }): void // -1..1, 0 is centre
```

### p.midi.on [#pmidion]

```ts
// What the music app sends. React in the callback; never poll.
on(event: 'note', cb: (n: { note: number; velocity: number; on: boolean; channel: number }) => void): void
on(event: 'cc', cb: (c: { controller: number; value: number; channel: number }) => void): void
on(event: 'pitchBend', cb: (b: { value: number; channel: number }) => void): void
```

## p.camera [#pcamera]

The board's camera (a Raspberry Pi Camera Module 3 on the ribbon, or a USB webcam). Photos stay
on the board; the person sees them in the app's camera card. The camera must be ON (the person
turns it on in the app, or asks PAL to).

`p.camera` — the board's camera. ASYNC: always `await`.

```ts
// A photo: await p.camera.snapshot(). Throws when no camera is on
readonly camera: Camera
```

### p.camera.snapshot [#pcamerasnapshot]

```ts
// const photo = await p.camera.snapshot()  →  { id, path, size, cameraId, takenAt }. Photos stay on the board.
// Rejects (throws) when no camera is on — catch it and log the reason.
snapshot(opts?: { cameraId?: string }): Promise<{ id: string; path: string; size: number; cameraId: string; takenAt: number }>
```

What it gives back:

```ts
interface CameraPhoto {
  /** The photo's id on the board (`snap_…`): pass it to `p.camera.ask`. */
  id: string;
  /** Where the JPEG is on the board. */
  path: string;
  /** Bytes. */
  size: number;
  cameraId: string;
  /** Milliseconds since the epoch, board clock. */
  takenAt: number;
}
```

### p.camera.ask [#pcameraask]

```ts
// Sends the photo to the AI and resolves its answer as text. ONLY when the person set this project to
// "PAL looks at photos: Always" — otherwise it rejects, saying how to allow it. Catch it.
ask(photo: { id: string } | string, question: string): Promise<string>
```

### p.camera.record [#pcamerarecord]

```ts
// const clip = await p.camera.record({ seconds: 10 })  →  { id, path, size, cameraId, takenAt, durationMs }.
// A short video, 1–30 s (default 5); it stays on the board. Other scripts keep running while it records.
// Rejects when no camera is on or the board cannot encode video — catch it. p.camera.ask(clip, …) sends PAL a few frames.
record(opts?: { seconds?: number; cameraId?: string }): Promise<{ id: string; path: string; size: number; cameraId: string; takenAt: number; durationMs: number }>
```

What it gives back:

```ts
interface CameraClip {
  /** The clip's id on the board (`clip_…`): pass it to `p.camera.ask`. */
  id: string;
  /** Where the MP4 is on the board. */
  path: string;
  /** Bytes. */
  size: number;
  cameraId: string;
  /** Milliseconds since the epoch, board clock: when recording started. */
  takenAt: number;
  /** How long the clip is, in milliseconds. */
  durationMs: number;
}
```