﻿<head><script async src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js?client=ca-pub-4357510538660394"
     crossorigin="anonymous"></script></head># Build an app that belongs on a screen

> Canonical HTML: https://screenrig.ai/docs/sdk

Use the injected browser SDK for playlist control, application events, diagnostics, and persistent key/value state.

## Watch it built

Claude Code writes a lobby check-in kiosk against `window.screenrig`: `waitUntilActive()`, `ready()`, `kv.get()` and `emitConfirmed()`. A visitor's tap reaches the agent, and it answers on the welcome wall.

- [Build a kiosk app with the SDK, 2:17](https://screenrig.ai/videos/sdk-kiosk-app) — chapters and transcript
- [The film (MP4, 720p)](https://screenrig.ai/static-resources/videos/films/sdk-kiosk-app-720-e85f081b.mp4)

## The runtime is already in the app

`app pack` and `app upload` accept any prebuilt static directory with a root `index.html`. The packer automatically injects `_screenrig/runtime.js` and adds its script tag to `index.html`. Your running app receives `window.screenrig` with no build step, no npm dependency, no imports, and no configuration.

- **Content security policy:** Apps run under a strict CSP that blocks inline code. Packing automatically extracts inline style and script blocks into external files and links them, while rejecting inline event handlers (such as `onclick=`) and `javascript:` URLs with the offending file and line number.
- **Health checks:** The web Player pings running applications every 10 seconds and reloads any app that misses three checks in a row, backing off from 30 seconds up to 10 minutes on repeated failures.
- **Origin isolation and persistence:** Every immutable release runs on its own isolated origin under `apps.screenrig.ai`. Because the application ID outlives individual releases, key/value data persists across upgrades, and `app use-release` moves every playlist back to an earlier release or forward to the latest at once.

## Develop locally

Test your application before uploading it. `screenrig app dev` serves your built directory with the runtime injected inside a local Player harness at `http://play.screenrig.localhost:18890`. Your app gets the same `window.screenrig` surface it sees on a real screen—context, capabilities, key/value store, and every device API—simulated by the harness:

```console
screenrig app dev ./lobby-board --open
```

The harness displays your app in a frame next to a control panel:

- **Capabilities:** Toggle individual capability flags to test how your app handles missing permissions.
- **Screen:** Switch viewport presets and edit the screen name, timezone, and launch params exposed in `context`.
- **Page:** Drive the page timer behind `pageTiming()`, pause the timer, toggle the display power, and trigger page leave events for `onVisibility()`.
- **Device:** Emit simulated hardware events (scans, people counts, sound levels, presence, volume keys, ambient light, and network state) and emulate serial ports, GPIO lines, Bluetooth LE peripherals, and printers.
- **Key/value store:** Persists data across reloads in `.screenrig-dev/kv.json` (or `--kv FILE`). Pass `--kv-from APP_ID` to read an uploaded application's store read-only.

Every `emit` and `log` call prints directly in your terminal. Saving files reloads the page automatically (disable with `--no-reload`), and pack errors like inline event handlers report the exact file and line on save. The harness binds exclusively to port `18890` (the only local parent origin the runtime trusts, so `--port PORT` rejects other ports). Pass `--open` to launch the harness in your browser. See [`app dev`](https://screenrig.ai/docs/cli/applications#cmd-app-dev) for all flags.

## TypeScript

Run `screenrig app types` to write `screenrig.d.ts` into your TypeScript source folder. Any project that includes it gets full typing for `window.screenrig`—no custom `declare global`, no package install, and no imports required:

```console
screenrig app types ./src
```

Because `screenrig.d.ts` contains type declarations only, it adds zero bytes to your compiled bundle. It matches the runtime injected by `app pack` and `app upload`; re-run it after upgrading the CLI. See [`app types`](https://screenrig.ai/docs/cli/applications#cmd-app-types) for details.

```ts
const sr = window.screenrig;
await sr.waitUntilActive();
await sr.ready();

const entry = await sr.kv.get("menu"); // KvEntry
const bytes = Uint8Array.from(atob(entry.value_base64), (c) => c.charCodeAt(0));
const menu = JSON.parse(new TextDecoder().decode(bytes));
```

Key type guarantees:

- `kv.get` and `kv.set` resolve to `KvEntry`. `kv.list` resolves to `KvList`, whose `items` are `KvSummary` objects (`KvEntry` without `value_base64`). `kv.delete` resolves to `void`.
- `kv.getText` resolves to `string`, `kv.getJSON<T>` resolves to `T` (`unknown` by default), and `kv.setJSON` resolves to `KvEntry`.
- Every thrown error and rejected promise is a `ScreenRigError` (`Error` with a string `code`). Always branch on `code`, never on the message text.
- Dotted capability keys such as `capabilities["kv.write"]` are type-checked against all twenty capability flags, so in a strict project a misspelled flag does not compile.
- `window.screenrig` is typed as defined; if your bundle also runs outside screenRIG, guard access with `if (!window.screenrig)`.

Keep `screenrig.d.ts` with your source files rather than inside the built output directory, or `app pack` will upload it with your bundle.

## The `window.screenrig` surface

`window.screenrig` exposes three read-only properties, thirteen top-level methods, a `kv` namespace (eight methods), and a `device` namespace covering display control, presence, hardware keys, ambient light, network state, haptics, scanners, camera, microphone, serial ports, GPIO, Bluetooth LE, printers, infrared, UDP, and HDMI input. Check `readyState` first and verify `capabilities` before calling gated methods.

`onVisibility()`, `pageTiming()`, `context.params`, `context.screen`, the `kv` text/JSON helpers, and all hardware APIs ship inside the injected runtime, so repack older releases to enable them.

Each method answers a different question, so start from what you want to do:

| To do this | Call |
| --- | --- |
| Wait until the Player activates this page | `screenrig.waitUntilActive()` |
| Say the application is up and on screen | `screenrig.ready()` |
| End this application's turn on an application-advance page | `screenrig.nextPage()` |
| Tell the Player this page has nothing to show right now | `screenrig.skip(reason)` |
| Tell the agent that something happened | `screenrig.emit(code)` |
| Know the backend recorded that event | `screenrig.emitConfirmed(code)` |
| Leave a diagnostic for the Player and runtime to collect | `screenrig.log(...)` |
| Find the errors the page did not catch in the Player log | Uncaught errors |
| Read live application state | `screenrig.kv.get()`, `screenrig.kv.getText()`, `screenrig.kv.getJSON()`, `screenrig.kv.list()` |
| Write live application state | `screenrig.kv.set()`, `screenrig.kv.setJSON()`, `screenrig.kv.delete()` |
| Update the moment live application state changes | `screenrig.kv.onChange()` |
| React to a size or capability change | `screenrig.onResize()`, `screenrig.onCapabilities()` |
| Hear that the page left the glass or came back | `screenrig.onVisibility()` |
| Know how long the page has been up and how long it has left | `screenrig.pageTiming()` |
| Check whether the Player offers a feature | `screenrig.supports()` |
| Read the launch params, the screen's name and its time zone | `screenrig.context.params`, `screenrig.context.screen` |
| Dim, darken or wake the display | `screenrig.device.display.set()` |
| Hear that somebody walked up to the screen | `screenrig.device.onPresence()` |
| Take the hardware volume keys | `screenrig.device.onKey()` |
| Hear the ambient light level | `screenrig.device.onLight()` |
| Hear that the device went online or offline | `screenrig.device.onNetwork()` |
| Play a haptic tick | `screenrig.device.vibrate()` |
| Hear a barcode, badge or NFC tag read | `screenrig.device.onScan()` |
| Read QR codes and barcodes with the camera | `screenrig.device.scanner.start()`, `screenrig.device.scanner.stop()` |
| Count the people in front of the screen | `screenrig.device.onPeople()` |
| Hear the sound level in the room | `screenrig.device.onSoundLevel()` |
| Talk to a serial device | `screenrig.device.serial.list()`, `screenrig.device.serial.open()` |
| Drive or hear a GPIO line | `screenrig.device.gpio.write()`, `screenrig.device.gpio.onChange()` |
| Read or follow a Bluetooth LE characteristic | `screenrig.device.ble.read()`, `screenrig.device.ble.watch()` |
| Print a receipt or a document | `screenrig.device.print()`, `screenrig.device.printers()` |
| Send or hear an infrared remote code | `screenrig.device.ir.send()`, `screenrig.device.onIr()` |
| Send and receive UDP datagrams on the screen's network | `screenrig.device.udp.open()` |
| Show the player's HDMI input | `screenrig.device.hdmiInput.open()` |
| Tear down listeners when the application is done with the runtime | `screenrig.destroy()` |

### `screenrig.readyState`

Whether the injected runtime is attached. Every document starts `inert` and
turns `active` when the Player's handshake and context arrive; a page that is
not on screen yet stays `inert`. Wait for `active` with
`screenrig.waitUntilActive()`; do not treat `inert` at load as "outside
screenRIG". On `failed`, or when `window.screenrig` is absent, render your own
content and skip the surface below, so the same build also runs outside
screenRIG. While `inert`, `ready()`, `log()`, `emit()`, `emitConfirmed()`, `nextPage()`, `skip()`, `pageTiming()`, the `kv` reads and writes and the `device` display, haptics and hardware calls throw or reject with code `inert`;
`kv.onChange` can be registered at any time.

- Type: `"inert" | "active" | "failed"`

### `screenrig.context`

Where this document is running.

| Field | Type | Notes |
| --- | --- | --- |
| `application_id` | string | The `app_` id from `app upload`. The key/value store belongs to it. |
| `release_id` | string | The immutable release serving this origin. |
| `primitive_id` | string | The primitive this document fills on the current page. |
| `viewport` | `{ width, height }` | The surface the Player is rendering into. |
| `primitive` | `{ width, height }` | The rect this document occupies inside that viewport. |
| `capabilities` | object | The same booleans as `screenrig.capabilities`. |
| `screen_id` | string, optional | Present when the runtime knows which screen is playing. |
| `params` | object | The launch params of this application on this screen, strings by name. Always present, and `{}` when the page sets none. See `context.params`. |
| `screen` | `{ name, timezone }`, optional | The screen's name and IANA time zone. See `context.screen`. |

`context` is description, not request material. Nothing in it is meant to be
signed, forwarded, or sent back to screenRIG; the methods below carry whatever
the runtime needs.

Launch parameters arrive in `context.params`: a playlist can give an application `params` (see [Screen tokens in iframe addresses and application params](https://screenrig.ai/docs/compose.md#screen-tokens-in-iframe-addresses-and-application-params)), and every Player passes them in the context, whether it opens the application from a launch address or loads it from its local package. On the web Player `location.search` still carries each one too, appended to the page's address after `ticket`, for example `new URLSearchParams(location.search).get("kiosk")`. They are hints, not credentials, and anyone who can open the page can send any value on that address, so treat them as untrusted input; `context.screen_id` stays the way to learn which screen is playing.

### `screenrig.context.params`

**Read the launch params the playlist gives this application.** A playlist can give an `application` `params`, which may read screen tokens such as `{screen.field.kiosk_id}`. `context.params` is the result for this screen: an object of strings that is read-only and always present, `{}` when the page sets none. It arrives with the context on every Player, whether the Player opens the application from a launch address or loads it from its local package.

```javascript
await window.screenrig.waitUntilActive();
const kiosk = window.screenrig.context.params.kiosk ?? "lobby";
```

A screen passes at most 16 params. A name is 1 to 32 lower case letters, digits or underscores and is never `ticket` or `policy`; a value is a string of at most 512 characters, and an empty string is a valid value.

- Type: `Readonly<Record<string, string>>`
- Requires: no capability; `context` is `null` until the page is active

### `screenrig.context.screen`

**Read the screen's name and time zone.** `context.screen` is `{ name, timezone }`. `name` is the screen's name, at most 200 characters, and `timezone` is its IANA time zone, such as `America/Vancouver`. A member the screen does not have is absent, and `context.screen` is `undefined` when both are.

```javascript
const zone = window.screenrig.context.screen?.timezone ?? "UTC";
const time = new Intl.DateTimeFormat("en", { timeZone: zone, timeStyle: "short" })
  .format(new Date());
```

- Type: `{ name?: string, timezone?: string }`, optional
- Requires: no capability

### `screenrig.capabilities`

Twenty booleans that say which gated methods will do anything for this activation. The keys are dotted, so read them with bracket notation.

| Flag | Gates |
| --- | --- |
| `page.advance` | `screenrig.nextPage()` |
| `page.skip` | `screenrig.skip()` |
| `kv.read` | `screenrig.kv.get()`, `.getText()`, `.getJSON()`, `screenrig.kv.list()` and `screenrig.kv.onChange()` |
| `kv.write` | `screenrig.kv.set()`, `.setJSON()` and `screenrig.kv.delete()` |
| `device.display` | `screenrig.device.display.get()`, `.set()` and `screenrig.device.onDisplay()` |
| `device.presence` | `screenrig.device.onPresence()` |
| `device.keys` | `screenrig.device.onKey()` |
| `device.light` | `screenrig.device.onLight()` |
| `device.network` | `screenrig.device.onNetwork()` |
| `device.haptics` | `screenrig.device.vibrate()` |
| `device.scan` | `screenrig.device.onScan()` |
| `device.camera` | `screenrig.device.scanner.start()`, `.stop()` and `screenrig.device.onPeople()` |
| `device.sound` | `screenrig.device.onSoundLevel()` |
| `device.serial` | `screenrig.device.serial.list()` and `.open()` |
| `device.gpio` | `screenrig.device.gpio.write()` and `.onChange()` |
| `device.ble` | `screenrig.device.ble.read()` and `.watch()` |
| `device.print` | `screenrig.device.print()` and `screenrig.device.printers()` |
| `device.ir` | `screenrig.device.ir.send()` and `screenrig.device.onIr()` |
| `device.udp` | `screenrig.device.udp.open()` and the sockets it returns |
| `device.hdmi_input` | `screenrig.device.hdmiInput.open()` |

```javascript
if (window.screenrig.capabilities["kv.write"]) {
  saveButton.hidden = false;
}
```

Subscribe with `screenrig.onCapabilities` instead of reading the flags once at
startup.

- Type: object of booleans

### `screenrig.waitUntilActive(timeoutMs)`

**Call it first, before any other method**, and render your UI while it waits.
It resolves when the Player has activated this page, or at once when the
runtime is already `active`, and it does not declare the application rendered.
It rejects with `activation_timeout` after `timeoutMs` (default 10000, at most
300000); a page that is waiting its turn can simply wait again. Start sound after it resolves, because the Player loads an
application before its page shows: a screen whose browser allows autoplay starts it at once, and one that refuses
rejects `play()` with `NotAllowedError`, so catch it and play muted.

```javascript
const sr = window.screenrig;
async function start() {
  render(); // the UI works with or without screenRIG
  if (!sr) return;
  for (;;) {
    try { await sr.waitUntilActive(60000); break; }
    catch (err) { if (err.code !== "activation_timeout") return; }
  }
  await sr.ready();
  // From here: emit, emitConfirmed, log, kv, nextPage.
}
start();
```

Check `readyState === "active"` before an SDK call from an event handler, timer
or `catch`, and queue input that arrives earlier. A `log()` from a handler that
runs while `inert` throws too, which can end startup before any event is sent.

- Returns: `Promise<void>`

### `screenrig.ready()`

**Call it after `waitUntilActive()` resolves and before you depend on `context`,
`kv`, or `nextPage`**, once the application has what it needs to be on
screen. Called while `inert`, it throws.

```javascript
await window.screenrig.waitUntilActive();
await window.screenrig.ready();
```

- Returns: `Promise<void>`

### `screenrig.nextPage()`

**Call it only on an application-advance page where this primitive is the
controller**, when the application has finished its turn. It is one-shot: an
activation gets one advance.

```javascript
window.screenrig.nextPage();
```

The method is for a page whose `advance.mode` is `application`, where this
primitive is the controller:

```json
{
  "advance": { "mode": "application", "max_ms": 60000 },
  "primitives": [
    {
      "id": "app",
      "primitive": "application",
      "release_id": "rel_01EXAMPLERELEASE000000000",
      "rect": { "x": 0, "y": 0, "width": 1920, "height": 1080 },
      "layer": 0,
      "content_fit": "fill",
      "controller": true
    }
  ]
}
```

Exactly one primitive on that page carries `controller: true`, and it must be an
application primitive. `max_ms` on the page advance object bounds the turn.

- Requires: `capabilities["page.advance"]`
- Returns: `Promise<void>`

### `screenrig.skip(reason)`

**Call it instead of `ready()` when the application has nothing to show right
now.** The screen moves on at once with the page's normal transition, and this
appearance counts no play. It is a start-time decision: call it within ten
seconds of activation and before `ready()`.

```javascript
await window.screenrig.waitUntilActive();
const events = await loadToday();
if (events.length === 0) {
  await window.screenrig.skip("no events today");
} else {
  render(events);
  await window.screenrig.ready();
}
```

The page's controller, or the application that is alone on its page, holds the
capability, on a page with no image or video. The method rejects with
`capability_denied` without it, `skip_after_ready` once `ready()` ran, and
`not_supported` on a Player that lacks it. It rejects with `forbidden` when the
Player keeps the page: the operator holds it, the display is dark, no other
page can play, or every other page has skipped too. Render your fallback and
call `ready()` then. A playlist of tiles that all skip shows the last one for
its full time instead of cycling. The optional `reason` (at most 64
characters) appears in the project's Player log as
`player.application_skipped`. `skip()` ships in the runtime that `app pack` and
`app upload` inject, so repack a release to give it the method.

- Requires: `capabilities["page.skip"]`
- Returns: `Promise<void>`

### `screenrig.emit(code)`

**Use it when the agent should see that something happened**: a page finished a
step, a kiosk form was submitted, the application proved it ran. This is a named
application event, and it lands in the project event log where the agent watches
it with the bundled CLI's
[`events list`](https://screenrig.ai/docs/cli/notifications#cmd-events-list) or
[`events follow`](https://screenrig.ai/docs/cli/notifications#cmd-events-follow). One code,
no message body.

`log` is not a substitute. A diagnostic is not an application event, and an
agent reading the event log will not see it.

```javascript
window.screenrig.emit("menu.rendered");
```

SDK `emit()` and `emitConfirmed()` append `application.event` records whose
resource is the screen. Read them with `--type application.event`, optionally
adding `--screen-id`. The returned `details.primitive_id` and `details.code`
identify the emitting primitive and named action. `--app-id` selects application
resource, release and K/V events, so it excludes these screen events.

```console
screenrig events list --type application.event --screen-id scr_SCREEN
```

| Parameter | Type | Notes |
| --- | --- | --- |
| `code` | string | Sanitized to `[A-Za-z0-9._-]`, at most 64 characters. |

- Returns: `void`

### `screenrig.emitConfirmed(code)`

**Use it when the application must know the event landed**: a kiosk order was placed, a form was sent, a visit finished. It sends the same named application event as `emit`, and its promise resolves only once the Player confirms that the backend accepted the event.

It rejects with the backend's problem when the event is refused, and with `ack_timeout` after 10 seconds without a reply. Do not retry automatically after a timeout: the backend may already have accepted the event. A receipt proves the event is in the project event log, not that anything has acted on it yet.

Receipts work on every Player that runs applications.

```javascript
await window.screenrig.emitConfirmed("order.placed");
```

| Parameter | Type | Notes |
| --- | --- | --- |
| `code` | string | Sanitized to `[A-Za-z0-9._-]`, at most 64 characters. |

- Returns: `Promise<void>`

### `screenrig.log({ level, code, message })`

**Use it for diagnostics**: the `debug`, `info`, `warn`, and `error` text the
Player and runtime collect while the application is on screen. The injected
runtime logs through this method itself. Logging is capped:
32 lines per client, and at most 2048 bytes of message each. Log what you would
want while debugging, not one line per frame.

Do not reach for `log` when you mean `emit`. Agents do not treat log lines as
application events, so anything the agent needs to act on belongs in an `emit`
code.

```javascript
window.screenrig.log({
  level: "warn",
  code: "menu.stale",
  message: "Falling back to the cached menu."
});
```

| Field | Type | Notes |
| --- | --- | --- |
| `level` | string | `debug`, `info`, `warn`, or `error`. |
| `code` | string | Sanitized to `[A-Za-z0-9._-]`, at most 64 characters. |
| `message` | string | At most 2048 bytes. |

- Returns: `void`

### Uncaught errors

**Uncaught errors reach the Player log without any code from you.** While the runtime is active it forwards the page's `error` events and unhandled promise rejections as `log` entries at level `error`, with the code `uncaught_error` or `unhandled_rejection`. The message is the error's message followed by `(file:line:col)`, and at most 2048 characters. The runtime never calls `preventDefault`, so the browser console reports the error as usual.

At most 10 are forwarded per activation, and they count toward the 32 lines per client that `log` allows. Catch and `emit` an error the agent should act on.

### `screenrig.onResize(handler)`

**Subscribe when the layout can change under you** instead of reading `context`
once. The handler receives `{ viewport, primitive }`, the same two objects
`context` carries, and the call returns the function that ends the
subscription.

```javascript
const stopResize = window.screenrig.onResize(function (size) {
  render(size.viewport, size.primitive);
});

stopResize();
```

- Returns: unsubscribe function

### `screenrig.onCapabilities(handler)`

**Subscribe when the granted capabilities can change** instead of deciding once
at startup. Read `screenrig.capabilities` inside the handler for the current
booleans and enable or hide the affected controls; the call returns the function
that ends the subscription.

```javascript
const stopCapabilities = window.screenrig.onCapabilities(function () {
  saveButton.hidden = !window.screenrig.capabilities["kv.write"];
});
```

- Returns: unsubscribe function

### `screenrig.onVisibility(handler)`

**Pause what the page does while nobody can see it.** The handler receives `{ visible, reason }` when the page leaves the glass and when it returns. `reason` is `display` when the display went dark (its schedule, idle time or an operator), `paused` when an operator paused playback, and `leaving` when the page is about to be torn down or hidden. Playback resumes with `visible: true` and the `reason` that ended last, never `leaving`.

```javascript
const stopVisibility = window.screenrig.onVisibility(function (state) {
  if (state.visible) startTicker();
  else stopTicker();
  if (state.reason === "leaving") flushPendingWrites();
});
```

While two causes hold the page, such as a dark display during a pause, the handler hears one `visible: false` and one `visible: true`, when the last cause ends. `leaving` is sent once, best effort, just before the page goes, whether or not it was visible. The handler is not called when you register it. The call returns the function that ends the subscription and throws `invalid_handler` for a value that is not a function.

- Requires: no capability; without a Player that supports `visibility.watch` the handler never runs
- Returns: unsubscribe function

### `screenrig.pageTiming()`

**Ask how long the page has been on the glass and how long it has left.** The promise resolves with `{ elapsedMs, remainingMs, paused }`.

```javascript
const timing = await window.screenrig.pageTiming();
if (timing.remainingMs !== null && timing.remainingMs < 5000) showLastCall();
```

| Field | Type | Notes |
| --- | --- | --- |
| `elapsedMs` | integer | Milliseconds on the glass this activation, paused time excluded. |
| `remainingMs` | integer or `null` | Milliseconds until the Player moves on; `null` when the page has no scheduled end, such as the only page of a playlist. |
| `paused` | boolean | Whether playback is held: the display is dark or an operator paused it. |

- Requires: no capability
- Rejects: `inert`, `not_supported` on a Player that lacks `page.timing`, `invalid_response` for an answer it cannot read
- Returns: promise

### `screenrig.supports(kind)`

**Check what the Player offers before you depend on a feature it may lack.** It
returns `true` when the Player that hosts the page implements the message kind
or feature `kind`, such as `"page.skip"`, `"kv.watch"`, `"visibility.watch"`, `"page.timing"`, `"device.display"`, `"device.watch"`, `"device.vibrate"`, `"device.scan"`, `"device.camera"`, `"device.sound"`, `"device.serial"`, `"device.gpio"`, `"device.ble"`, `"device.print"`, `"device.ir"`, `"device.ir.send"`, `"device.udp"` or `"device.hdmi_input"`. A Player that lists `"device.ir"` supports `"device.ir.send"` too. `skip()`, `pageTiming()` and the `device` calls reject with `not_supported` when the Player lacks their feature, and `kv.onChange`, `onVisibility` and the `device` event handlers never run. `supports` says what
the Player can do; `capabilities` says what this page may do.

```javascript
const sr = window.screenrig;
if (sr.supports("device.display") && sr.capabilities["device.display"]) {
  await sr.device.display.set({ brightness: 0.3 });
}
```

- Returns: `boolean`

### `screenrig.destroy()`

**Tear down listeners when the application is done with the runtime.** An
application that runs for its whole turn and lets the Player replace the
document does not need to call it.

- Returns: `void`

### `screenrig.kv`

The application key/value store, for live application state that outlives one
activation. Eight methods of its own: `get`, `getText`, `getJSON`, `list`, `set`, `setJSON`, `delete`, and `onChange`. The key/value store section below documents all eight.

- Type: namespace

## The key/value store

Use the store for live application state: the menu the application renders, the
copy an operator changed this morning, a counter the last activation left
behind. Read it with `kv.get` and `kv.list`, or as text and JSON with `kv.getText` and `kv.getJSON`; write it with `kv.set` and `kv.delete`, or JSON with `kv.setJSON`; and hear about every change with `kv.onChange`.

The store belongs to the application id in `context.application_id`, not to a
release, so an entry survives the next `app upload`. Values are bytes, so text,
JSON, and small binaries all round-trip. Reads need `kv.read` and writes need
`kv.write`; check the flag before you call.

The store and its change push run on every Player that runs applications: the
Player web app (PWA), Android, Amazon Signage Stick, macOS, Windows, Linux and
Raspberry Pi, LG webOS Signage, BrightSign and Samsung Smart Signage (Tizen).
Apple TV, iPhone and iPad do not run applications; see
[primitive support by platform](https://screenrig.ai/docs/players#primitive-support).

### `screenrig.kv.get(key)`

**Read live application state.** Await the promise.

```javascript
const entry = await window.screenrig.kv.get("menu");
```

- Requires: `capabilities["kv.read"]`
- Returns: promise

### `screenrig.kv.getText(key)`

**Read live application state as text.** The promise resolves with the value decoded as UTF-8.

```javascript
const banner = await window.screenrig.kv.getText("banner");
```

- Requires: `capabilities["kv.read"]`
- Rejects: `not_found` as `kv.get` does, and `invalid_response` for a value that is not UTF-8 text
- Returns: promise of a string

### `screenrig.kv.getJSON(key)`

**Read live application state as JSON.** The promise resolves with the value parsed as JSON, typed `unknown` unless you name a type.

```javascript
const menu = await window.screenrig.kv.getJSON("menu");
```

```ts
const menu = await window.screenrig.kv.getJSON<Menu>("menu");
```

- Requires: `capabilities["kv.read"]`
- Rejects: `not_found` as `kv.get` does, and `invalid_value` when the value is not JSON
- Returns: promise of the parsed value

### `screenrig.kv.list()`

**Read live application state** when you do not know the keys yet: this lists
the keys the application has stored. Await the promise.

```javascript
const keys = await window.screenrig.kv.list();
```

- Requires: `capabilities["kv.read"]`
- Returns: promise

### `screenrig.kv.set(key, value, options)`

**Write live application state.** `value` is a string or a `Uint8Array`;
`options` is optional.

```javascript
await window.screenrig.kv.set("menu", JSON.stringify(menu), {
  contentType: "application/json"
});

await window.screenrig.kv.set("badge.png", pngBytes, {
  contentType: "image/png"
});
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `key` | string | yes | See the key rules below. |
| `value` | string or `Uint8Array` | yes | The bytes to store. |
| `options.contentType` | string | no | Defaults to `text/plain` for a string and `application/octet-stream` for a `Uint8Array`. |
| `options.expectedRevision` | non-negative integer | no | Write only if the entry is still at this revision. |
| `options.idempotencyKey` | string | no | Retry the same write without applying it twice. |

- Requires: `capabilities["kv.write"]`
- Returns: promise

### `screenrig.kv.setJSON(key, value, options)`

**Write live application state as JSON.** It stores `JSON.stringify(value)` with the content type `application/json`, or `options.contentType` when you give one, and takes the other `options` of `kv.set`. It resolves with the stored entry.

```javascript
await window.screenrig.kv.setJSON("visits", { count: 41, day: "2026-11-11" });
```

- Requires: `capabilities["kv.write"]`
- Rejects: `invalid_value` for a value JSON cannot represent, such as `undefined`, a function or a symbol; otherwise as `kv.set`
- Returns: promise

### `screenrig.kv.delete(key, expectedRevision, options)`

**Write live application state** by removing an entry. `expectedRevision` is optional: omit it to delete the current entry, or supply it to reject concurrent changes.

```javascript
await window.screenrig.kv.delete("menu");
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `key` | string | yes | See the key rules below. |
| `expectedRevision` | non-negative integer | no | The revision the entry was at when you read it. |
| `options.idempotencyKey` | string | no | Retry the same delete without applying it twice. |

- Requires: `capabilities["kv.write"]`
- Returns: promise

### `screenrig.kv.onChange(handler)`

**Update the moment live application state changes** instead of polling for it.
The handler runs whenever any key of this application changes, whoever wrote
it: the agent with `kv set`, an outside system through a key/value webhook (see
Push data from another system below), or this application on any screen. It
receives which key changed, not the value, so read the new value with `kv.get`.
The call returns the function that ends the subscription.

```javascript
const sr = window.screenrig;

async function showMenu() {
  render(await sr.kv.get("menu"));
}

const stopChanges = sr.kv.onChange(function (change) {
  if (change.key === "menu" && !change.deleted) showMenu();
});

await sr.waitUntilActive();
await sr.ready();
await showMenu();
```

Subscribe before the first read, so a change that lands while you read is not
missed; a handler registered before activation starts once the page is active.
Call `stopChanges()` to end the subscription.

A change reaches every screen whose playlist places this application within
seconds. Several quick writes to one key can arrive as one change carrying the
newest revision, so treat a change as "read this key again", not as a count of
writes. A change is a signal, not a history: read what you need when the
application starts, then follow changes.

| Field | Type | Notes |
| --- | --- | --- |
| `key` | string | The key that changed. |
| `revision` | integer, optional | The entry's new revision. Absent when `deleted` is `true`. |
| `deleted` | boolean | `true` when the key was deleted. |

- Requires: `capabilities["kv.read"]`; without it the handler never runs
- Returns: unsubscribe function

### Keys

A key is 1 to 256 UTF-8 bytes. The limit is bytes, not characters, so a key with
multi-byte characters reaches it sooner than its length suggests. A key must not
begin with `_screenrig/`; that prefix belongs to the injected runtime. The keys
`.` and `..` are refused too.

### Revisions and idempotency

Every entry carries a revision. Optionally pass `expectedRevision` to `screenrig.kv.set` or `screenrig.kv.delete` to write only if the entry is still at the revision you read. A stale revision means someone else wrote first:
read the entry again, reapply your change, and retry.

`idempotencyKey` covers the other half. A write that may be retried after a lost
response can carry the same key on every attempt, and the store applies it once.

### Results and limits

`kv.get`, `kv.set` and `kv.setJSON` resolve with the entry: `application_id`, `key`,
`value_base64` (the value's bytes, base64 encoded), `content_type`, `bytes`,
`sha256` and `revision`. `kv.list` resolves with `{ items }`, the same entries
without `value_base64`, for up to 200 keys. `kv.delete` resolves with no value,
and `kv.get` of a key that is not stored rejects with `not_found`.

```javascript
const entry = await window.screenrig.kv.get("menu");
const bytes = Uint8Array.from(atob(entry.value_base64), (c) => c.charCodeAt(0));
const menu = JSON.parse(new TextDecoder().decode(bytes));
```

An application holds at most 10,000 keys; a write past that limit rejects with
`quota_exceeded`. A screen writes to one application at most 120 times a minute,
and past that a write rejects with `rate_limited`. A value is at most 1 MiB with
`kv set` and webhooks; a value read or written through `screenrig.kv` travels in
one message of at most 64 KiB, base64 included, so keep it under about 48 KB.

### The same store from the CLI

The agent can reach these entries from outside the browser with the bundled
CLI's [`kv` commands](https://screenrig.ai/docs/cli/applications#kv) against the `app_` id
from `app upload`. That is the operator's view of the store. It is not a substitute for the methods above: an application changes its own data
through `screenrig.kv`, in the browser, while it is on screen. A change the
agent writes reaches the running application through `kv.onChange`.

<a id="kv-webhooks"></a>

### Push data from another system

A key/value webhook is a URL that writes one key of this application. Hand it
to anything that can send an HTTP POST, such as a point of sale,
a spreadsheet script, a cron job or `curl`, and each post replaces that key's
value. Every screen running the application hears about it through
`kv.onChange` within seconds, with no new release and no agent in the loop.

The agent creates one for a key with the bundled CLI and hands you its URL and
secret:

```console
screenrig kv webhook create menu --app-id app_01EXAMPLEAPP00000000000 --description "Point of sale menu feed"
```

The answer carries the webhook's `url` and its `secret` (`srkw_…`). The secret
is shown only when the webhook is created and when its secret is rotated, so
enter it in the sending system right away. The URL is not secret; the secret
is.

The sender posts the new value as the raw request body, with the secret in the
`Authorization` header:

```console
curl https://api.screenrig.ai/api/applications/app_01EXAMPLEAPP00000000000/kv-webhooks/kvw_01EXAMPLEWEBHOOK00000/write \
  -H "Authorization: Bearer $KV_WEBHOOK_SECRET" \
  -H "Content-Type: application/json" \
  --data '{"soup":"lentil","price":"6.50"}'
```

A sender that only speaks HTTP Basic authentication uses the webhook id as the
username and the secret as the password:

```console
curl https://api.screenrig.ai/api/applications/app_01EXAMPLEAPP00000000000/kv-webhooks/kvw_01EXAMPLEWEBHOOK00000/write \
  --user "kvw_01EXAMPLEWEBHOOK00000:$KV_WEBHOOK_SECRET" \
  -H "Content-Type: application/json" \
  --data '{"soup":"lentil","price":"6.50"}'
```

- The body, at most 1 MiB, becomes the value, and `Content-Type` its content
  type (`application/octet-stream` when the header is absent). The value
  reaches the browser application, so never post a credential as one.
- Each post is a key/value write like `kv set`: it replaces the value, raises
  the revision, and is counted toward storage like any other write.
- The answer is the key's new metadata (`key`, `revision`, `bytes`, `sha256`,
  `content_type` and `updated_at`), never its value.
- Add an `Idempotency-Key` header (8 to 200 characters) to retry a post
  safely: within 24 hours the same key applies once, and the same key with
  another body or content type is refused with `idempotency_mismatch`. Without
  one, every post is a new write.
- One webhook takes up to 120 posts a minute; past that the answer is `429`
  with `Retry-After`.
- A missing or wrong secret, or an unknown webhook, answers `401`. A secret in
  the URL or query string is never accepted.
- An application has up to 20 webhooks. `kv webhook rotate-secret` issues a
  new secret and the old one stops at once; `kv webhook delete` stops the URL
  at once and leaves the key's value in place.

A card takes webhooks too: a post builds its data document, as it is or through a mapping ([Card webhooks](https://screenrig.ai/docs/cli/cards#card-webhooks)).

[Key/value webhook commands](https://screenrig.ai/docs/cli/applications#kv-webhooks)

## The device

Kiosk and wall-panel apps can read sensors and control the display they run on. The `device.display`, `device.presence`, `device.keys`, `device.light`, `device.network`, and `device.haptics` capability flags are granted only to the page-controlling frame (the page's controller, or its sole application) on hardware and Players that support each feature:

- **Android** grants `device.display`, `device.keys`, and `device.network`; grants `device.presence` when the device has a camera with Camera permission enabled (**Android settings → Apps → screenRIG Player → Permissions → Camera**); grants `device.light` when an ambient light sensor is present; and grants `device.haptics` when a vibration motor is present.
- **Other Players** leave those flags `false`. Calling `display.get()`, `display.set()`, or `vibrate()` rejects with `not_supported` when the Player lacks the feature, or `capability_denied` when the flag is `false`. Event subscriptions (`onDisplay`, `onPresence`, `onKey`, `onLight`, and `onNetwork`) can be registered at any time and simply never fire when the flag is `false`.

### `screenrig.device.display.set(state)`

**Dim, darken or wake the display.** `brightness` is 0 to 1 (0 is the lowest the
backlight goes, not off); `on: false` darkens the glass and `on: true` lights it
again. Omit a member to leave it as it is. Taps still reach the application while
the glass is dark, so a tap can wake it. A display schedule that holds the screen
dark wins over the application, and the Player restores the display when the
page leaves the screen. A non-boolean `on`, a `brightness` outside 0 to 1 or any
other member rejects with `invalid_request` and sends nothing.

```javascript
await window.screenrig.device.display.set({ brightness: 0.3 });
await window.screenrig.device.display.set({ on: false });
```

- Resolves: `{ on, brightness }`, the display afterwards (`brightness` is `null`
  when the Player cannot read it); `set({})` only reads, and `brightness` keeps
  its value while the glass is dark
- Requires: `capabilities["device.display"]`

### `screenrig.device.display.get()`

The display now, as `{ on, brightness }`.

- Requires: `capabilities["device.display"]`

### `screenrig.device.onDisplay(handler)`

Called with `{ on, brightness }` whenever the display changes, whether this
application, a display schedule or an operator changed it.

- Returns: unsubscribe function
- Requires: `capabilities["device.display"]`

### `screenrig.device.onPresence(handler)`

Called when the device sees somebody move in front of the screen, at most once a
second. The Player reads the camera on the device and keeps no picture: no image
is stored, logged or sent. The camera runs only while a handler is registered.

```javascript
window.screenrig.device.onPresence(function () {
  window.screenrig.device.display.set({ on: true, brightness: 1 });
});
```

- Returns: unsubscribe function
- Requires: `capabilities["device.presence"]`

### `screenrig.device.onKey(handler)`

Called with `"volume_up"` or `"volume_down"` for every press of a hardware volume
key, repeats included. While a handler is registered the keys belong to the
application and the device volume stays where it is.

- Returns: unsubscribe function
- Requires: `capabilities["device.keys"]`

### `screenrig.device.onLight(handler)`

Called with the ambient light in lux: the first reading after the handler is
registered, then whenever the light changes by at least 10% or across 1 lux, at
most once a second. The device needs a light sensor.

```javascript
window.screenrig.device.onLight(function (lux) {
  document.body.classList.toggle("dim-room", lux < 10);
});
```

- Returns: unsubscribe function
- Requires: `capabilities["device.light"]`

### `screenrig.device.onNetwork(handler)`

Called with `true` or `false` whenever the device gains or loses internet
connectivity that the system has validated, and at once with the current state
when the first handler is registered.

```javascript
window.screenrig.device.onNetwork(function (online) {
  offlineBadge.hidden = online;
});
```

- Returns: unsubscribe function
- Requires: `capabilities["device.network"]`

### `screenrig.device.vibrate(ms)`

**Play one haptic tick.** `ms` is a whole number of milliseconds from 1 to 200
and defaults to 12. The promise resolves with no value once the Player has
started the vibration, and rejects `invalid_request`, sending nothing, for any
other `ms`.

```javascript
await window.screenrig.device.vibrate();
await window.screenrig.device.vibrate(40);
```

- Resolves: no value
- Requires: `capabilities["device.haptics"]`

## Hardware

Kiosk applications can communicate with barcode/badge scanners, cameras, microphones, serial ports, GPIO lines, Bluetooth LE peripherals, printers, and, on some Players, an infrared remote, UDP sockets, and HDMI input. Each peripheral family has its own capability flag: `device.scan`, `device.camera`, `device.sound`, `device.serial`, `device.gpio`, `device.ble`, `device.print`, `device.ir`, `device.udp`, and `device.hdmi_input`.

Capability flags are granted only to the page-controlling frame (the controller or sole application on the page) when both the device hardware and Player support the feature; everywhere else, the flag is `false`, method calls reject, and listeners never fire. Use `screenrig.supports("device.serial")` to check Player support and `capabilities["device.serial"]` to check page permission. All camera and audio analysis runs locally on the device—no images or audio ever leave it.

See [Hardware an application can use](https://screenrig.ai/docs/hardware.md) for the full Player support matrix and required permissions. Page visibility, page timing, launch params, and screen metadata in `context` need no special hardware and work on every Player that runs applications (Apple TV, iPhone, and iPad do not run applications).

Check `supports("device.scanner")` for camera barcode scanning and `supports("device.people")` for people counting; Players advertising the legacy `device.camera` host feature support both.

### How hardware calls behave

Every hardware call validates four conditions in order before messaging the Player: runtime active (`inert`), Player support (`not_supported`), page permission (`capability_denied`), and argument validity (`invalid_request`). Player-side failures reject with the method-specific error codes documented below.

Listeners can be registered at any time and start firing once the Player supports the feature and the page holds the flag. Hardware leases are automatically cleaned up when the page leaves the screen: the camera scanner stops, serial ports and UDP sockets close, GPIO and Bluetooth LE subscriptions end, and in-flight print jobs cancel. The SDK automatically chunks large writes and print jobs across bridge messages.

### `screenrig.device.onScan(handler)`

**Hear what the device reads.** The handler receives `{ source, format, data }` for a barcode scanner or badge reader, an NFC tag and the camera scanner.

```javascript
window.screenrig.device.onScan(function (scan) {
  if (scan.source === "scanner") lookUpBadge(scan.data);
});
```

| Source | Format | Notes |
| --- | --- | --- |
| `scanner` | `text` | A keyboard-wedge scanner or badge reader. A burst of at least 4 keystrokes, each at most 50 ms after the one before, that ends in Enter while no editable field of the page has focus. The Player takes the burst instead of typing it into the page, and types any other keys as usual. |
| `nfc` | `uid`, `ndef_text` or `ndef_uri` | A tag's identifier in upper case hexadecimal without separators, or the first text or URI record, decoded. |
| `camera` | A symbology name | A code the camera scanner read. It arrives only while `scanner.start()` runs. |

`data` is 1 to 2048 characters. At most one scan per 100 ms reaches the handler, and the camera reports a code it just reported again only after 2 seconds.

- Requires: `capabilities["device.scan"]`
- Returns: unsubscribe function

### `screenrig.device.scanner.start(options)`

**Start reading QR codes and barcodes with the camera.** Each code arrives at the `onScan` handlers with source `camera`. The camera is analyzed on the device, and the Player stops the scanner when the page leaves the screen.

```javascript
const { formats } = await window.screenrig.device.scanner.start({ formats: ["qr", "code128"] });
window.screenrig.device.onScan(function (scan) {
  if (scan.source === "camera") checkIn(scan.data);
});
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `options.formats` | array of strings | no | 1 to 13 distinct symbologies: `qr`, `ean13`, `ean8`, `upca`, `upce`, `code128`, `code39`, `code93`, `itf`, `codabar`, `datamatrix`, `pdf417` and `aztec`. Every symbology the device decodes by default. |

The promise resolves with `{ formats }`, the requested symbologies this device decodes, in the order you asked. When it decodes none of them the list is empty and nothing starts.

- Host feature: `device.scanner`
- Requires: `capabilities["device.camera"]` and `capabilities["device.scan"]`
- Rejects: `invalid_request` for an unknown or repeated name or an empty list, `camera_unavailable` when there is no camera, no permission to use it or it is in use
- Resolves: `{ formats }`

### `screenrig.device.scanner.stop()`

**Stop the camera scanner.** The promise resolves when the scanner is stopped, and also when it was not running.

- Host feature: `device.scanner`
- Requires: `capabilities["device.camera"]`
- Returns: promise

### `screenrig.device.onPeople(handler)`

**Hear how many people the camera sees.** The handler receives the count, an integer from 0 to 1000: first the count when the watch starts, then whenever it changes, at most once a second. The camera is analyzed on the device and runs only while a handler or the scanner needs it.

```javascript
window.screenrig.device.onPeople(function (count) {
  welcome.hidden = count === 0;
});
```

- Host feature: `device.people`
- Requires: `capabilities["device.camera"]`
- Returns: unsubscribe function

### `screenrig.device.onSoundLevel(handler)`

**Hear how loud the room is.** The handler receives the level of the last second of microphone audio in dBFS, a number from -120 to 0, at most once a second. No audio leaves the device.

```javascript
window.screenrig.device.onSoundLevel(function (dbfs) {
  meter.value = dbfs + 120;
});
```

- Requires: `capabilities["device.sound"]`
- Returns: unsubscribe function

### `screenrig.device.serial.list()`

**List the serial ports.** The promise resolves with up to 16 ports as `{ id, name, vendorId, productId }`; the vendor and product ids are present for a USB device. A port another process holds is listed too.

- Requires: `capabilities["device.serial"]`
- Returns: promise of an array of ports

### `screenrig.device.serial.open(port, options)`

**Open a serial port.** At most 4 ports are open at once, and the Player closes them when the page leaves the screen.

```javascript
const sr = window.screenrig;
const ports = await sr.device.serial.list();
const port = await sr.device.serial.open(ports[0].id, { baudRate: 9600 });
port.onData(function (bytes) {
  showWeight(new TextDecoder().decode(bytes));
});
await port.write("P\r\n");
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `port` | string | yes | An `id` from `serial.list()`. |
| `options.baudRate` | integer | yes | Bits per second, 50 to 4000000. |
| `options.dataBits` | 5, 6, 7 or 8 | no | 8 by default. |
| `options.stopBits` | 1 or 2 | no | 1 by default. |
| `options.parity` | `none`, `even` or `odd` | no | `none` by default. |
| `options.flowControl` | `none` or `hardware` | no | `none` by default. |

The promise resolves with the open port:

| Member | Notes |
| --- | --- |
| `port.id` | The id the port was opened with. |
| `port.write(data)` | Writes a `Uint8Array`, or a string sent as UTF-8, and resolves when the Player has handed the bytes to the port. Writes run in order, and one call writes at most 1,048,576 bytes. It rejects `invalid_handle` once the port is closed and `io_failed` when the write fails. |
| `port.onData(handler)` | Calls the handler with each chunk the port reads, in order. Bytes that arrived before the first handler, up to 65,536, are delivered to it first. It returns a function that removes the handler. |
| `port.onClose(handler)` | Calls the handler once with `unplugged`, `error` or `context` when the port closes by itself. It returns a function that removes the handler. |
| `port.close()` | Closes the port. Closing a closed port resolves. |

- Requires: `capabilities["device.serial"]`
- Rejects: `invalid_request` for bad options, `port_not_found`, `port_busy`, `port_limit` past 4 open ports, `io_failed`
- Resolves: the open port

### `screenrig.device.gpio.write(pin, value, options)`

**Drive a GPIO line as an output.** `pin` is an integer from 0 to 255, the line number of the device's GPIO chip (on a Raspberry Pi, the BCM number), and `value` is `true` for high. A relay needs a relay board, never a direct connection to the pin; [Buttons and relays on GPIO](https://screenrig.ai/docs/gpio.md) covers wiring, pin numbers and examples.

```javascript
await window.screenrig.device.gpio.write(17, true);
await window.screenrig.device.gpio.write(23, false, { idle: true });
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `options.idle` | boolean | no | The level the Player drives the line to when the page releases it: when it leaves the screen, when its context ends or on `destroy()`. Low by default. The latest write's `idle` for a pin applies, and the Player releases the line after driving it. Pass `true` for an active-low relay board. Linux, Raspberry Pi, Android and BrightSign. |

- Requires: `capabilities["device.gpio"]`
- Rejects: `invalid_request` for a bad `pin`, `value` or `idle`, `not_supported` when `options.idle` is given and the Player cannot set it, `pin_not_found`, `pin_busy`, `gpio_unavailable` when the Player can open no GPIO chip
- Resolves: no value

### `screenrig.device.gpio.onChange(pin, handler, options)`

**Hear a GPIO line change.** The handler receives the line's level as a boolean: first the level it has when the Player starts watching, then every change. The Player filters contact bounce. At most 16 lines are watched at once, and a 17th line throws `invalid_request`.

```javascript
window.screenrig.device.gpio.onChange(27, function (high) {
  doorOpen = high;
}, { pull: "up" });
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `options.pull` | `"up"`, `"down"` or `"none"` | no | The bias the Player sets on the line: `"up"` for a button wired to ground, which then reads low when pressed, `"down"` for a button wired to 3.3 V. `"none"` by default, which sets no bias. Linux and Raspberry Pi. Two live handlers on one pin must agree: a different `pull` throws `invalid_request`. On a Player that cannot set a pull, the SDK watches the line without one and logs one `warn` entry with the code `gpio_pull_unsupported`. |

- Requires: `capabilities["device.gpio"]`; without it, or on a Player without `device.gpio`, the handler never runs
- Returns: unsubscribe function

### `screenrig.device.ble.read(target)`

**Read a Bluetooth LE characteristic.** The promise resolves with its value, 0 to 512 bytes. Bluetooth LE here reads and notifies; there is no pairing and no writing.

| Member | Type | Required | Notes |
| --- | --- | --- | --- |
| `service` | string | yes | The service UUID: 4 or 8 hexadecimal characters, or 36 with dashes. |
| `characteristic` | string | yes | The characteristic UUID, in the same forms. |
| `device` | string | no | An advertised name or an address such as `aa:bb:cc:dd:ee:ff`, at most 64 characters. Without it the first peripheral that advertises the service is used, and none within 10 seconds rejects `device_not_found`. |

```javascript
const bytes = await window.screenrig.device.ble.read({ service: "180f", characteristic: "2a19" });
batteryLevel.textContent = bytes[0] + "%";
```

- Requires: `capabilities["device.ble"]`
- Rejects: `invalid_request` for a malformed target, `ble_unavailable` when there is no adapter, it is off or it has no permission, `device_not_found`, `characteristic_not_found`, `io_failed`
- Resolves: a `Uint8Array`

### `screenrig.device.ble.watch(target, handler)`

**Follow a Bluetooth LE characteristic.** The handler receives each notification's bytes. The promise resolves with a function that stops following once the Player has subscribed. At most 8 subscriptions are held at once, and they end when the page leaves the screen.

```javascript
const stop = await window.screenrig.device.ble.watch(
  { service: "180d", characteristic: "2a37" },
  function (bytes) {
    showHeartRate(bytes[1]);
  }
);
```

- Requires: `capabilities["device.ble"]`
- Rejects: as `ble.read` does, and `subscription_limit` past 8
- Resolves: a function that stops following

### `screenrig.device.printers()`

**List the printers.** The promise resolves with up to 16 printers as `{ id, name, formats, default }`. `formats` holds `escpos`, `pdf` or both, and `default` is `true` on the device's default printer.

- Requires: `capabilities["device.print"]`
- Returns: promise of an array of printers

### `screenrig.device.print(job)`

**Print a receipt or a document.** The promise resolves when the printer or its spooler has the job. Jobs from one page run one after another.

```javascript
const printers = await window.screenrig.device.printers();
await window.screenrig.device.print({ escpos: receiptBytes, printer: printers[0].id });
```

| Member | Type | Required | Notes |
| --- | --- | --- | --- |
| `escpos` | `Uint8Array` | one of the two | Raw ESC/POS commands for a receipt printer on USB or the network. |
| `pdf` | `Uint8Array` | one of the two | A PDF document, printed through CUPS on Linux and Raspberry Pi only. On Android and Windows `printers()` lists `escpos` alone, and a PDF job rejects `printer_not_found`, or `invalid_request` when it names a printer. |
| `printer` | string | no | A printer `id` from `printers()`. The default printer when absent. |

A job is 1 to 4,194,304 bytes. The printer must print the format you send.

- Requires: `capabilities["device.print"]`
- Rejects: `invalid_request` for a bad job or a printer that does not print the format, `printer_not_found`, `print_failed` when the printer accepted the job and failed it, `payload_too_large`
- Resolves: no value

### `screenrig.device.ir.send(code, options)`

**Send an infrared remote code**, to switch a TV's input or change its volume from the application. `code` is an NEC code, an integer from 0 to 16777215 (`0xFFFFFF`): bits 0 to 7 are the command (the button) and bits 8 to 23 the 16-bit address (the manufacturer code). A remote whose address is `0x00FF` and whose button is `0x20` is `0x00FF20`. On the wire an NEC frame carries the address low byte (bits 8 to 15), the address high byte (bits 16 to 23), the command and the command's bitwise complement, each byte least significant bit first, so `0x00FF20` goes out as the bytes `0xFF 0x00 0x20 0xDF`.

```javascript
await window.screenrig.device.ir.send(0x00ff20);
await window.screenrig.device.ir.send(0x00ff20, { repeat: 2 });
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `code` | integer | yes | 0 to 16777215, laid out as above. |
| `options.encoding` | `"NEC"` | no | `"NEC"` is the only encoding and the default. |
| `options.repeat` | integer | no | How many more times to send the whole code, about 110 ms apart: 0 to 10, and 0 by default, one send. It resends the whole code and is not an NEC repeat frame. |

The promise resolves once the Player's emitter has the last send, up to about 1.1 seconds after the call for a `repeat` of 10.

- Requires: `capabilities["device.ir"]`, on a Player that transmits: `screenrig.supports("device.ir.send")` is true on a BrightSign player and on an Android device with an infrared emitter
- Rejects: `not_supported` on a Player that cannot transmit, `capability_denied` without the capability, `invalid_request` for a `code`, `repeat` or `encoding` out of range, `ir_unavailable` when the device has no usable emitter
- Resolves: no value

### `screenrig.device.onIr(handler)`

**Hear the infrared codes the device receives.** The handler receives `{ encoding, code, repeat }` for each code, with `code` laid out as `ir.send` describes: a frame whose bytes are `0xFF 0x00 0x20 0xDF` arrives as `0x00FF20`. `repeat` is `true` for the auto-repeat of a held key, as the receiver reports it, and `false` for the first code of a press. Every code reaches the handler, with no debounce.

```javascript
window.screenrig.device.onIr(function (ir) {
  if (ir.code === 0x00ff20 && !ir.repeat) nextSlide();
});
```

A BrightSign player receives through its infrared input, and through its GPIO line 1 when you wire an infrared receiver there. An Android device transmits only.

- Requires: `capabilities["device.ir"]`; without it, or on a Player that cannot receive (`screenrig.supports("device.ir")` is false), the handler never runs
- Returns: unsubscribe function

### `screenrig.device.udp.open(port, options)`

**Open a UDP socket on the screen's network**, to follow or drive a show controller, a Crestron, AMX or Q-SYS system or any other device that speaks UDP. The promise resolves with a socket.

```javascript
const socket = await window.screenrig.device.udp.open(9000);
socket.onMessage(function (message) {
  show(new TextDecoder().decode(message.data), message.fromHost);
});
await socket.send("192.168.1.40", 7000, "scene 3\r\n");
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `port` | integer | no | 1024 to 65535 binds that port for receiving and sending. 0, the default, opens a send-only socket on a port the Player picks, which receives nothing. |
| `options.broadcast` | boolean | no | Lets the socket send to a broadcast address such as `255.255.255.255`. `false` by default. |
| `options.multicast` | string | no | An IPv4 group address from `239.0.0.0` to `239.255.255.255` that the socket joins on its port, so datagrams sent to the group and port arrive. It needs a `port`. |

At most 4 sockets are open at once, and a fifth rejects `socket_limit`. Ports 49817 and 49818 are the Player's own, for eventual sync, and reject `port_busy` on every Player, as does a port another program holds. The sockets close when the page leaves the screen.

The socket has these members:

| Member | Notes |
| --- | --- |
| `socket.port` | The port the socket was asked to bind: 0 for a send-only socket. |
| `socket.send(host, port, data)` | Sends one datagram of 1 to 8192 bytes: a `Uint8Array`, or a string sent as UTF-8. `host` is an IPv4 address, a name that ends in `.local` or a single-word name on the screen's network; a public domain name, an IPv6 address and a name with a port are refused. `port` is 1 to 65535. It rejects `invalid_request` for a bad argument, `payload_too_large` for more than 8192 bytes, `invalid_handle` once the socket is closed and `io_failed` when the network refuses the datagram. |
| `socket.onMessage(handler)` | Calls the handler with `{ fromHost, fromPort, data }` for each datagram, in order, `data` being 1 to 8192 bytes. The newest 32 datagrams that arrived before the first handler are delivered to it first. A longer datagram is dropped, and the Player logs one warning for the socket. It returns a function that removes the handler. |
| `socket.onClose(handler)` | Calls the handler once with `error` when the Player's network socket fails, such as when the interface goes away, or `context` when the page's context ends. A send on a closed socket rejects `invalid_handle`. It returns a function that removes the handler. |
| `socket.close()` | Closes the socket. Closing a closed socket does nothing. |

- Requires: `capabilities["device.udp"]`
- Rejects: `not_supported` on a Player without UDP, `capability_denied` without the capability, `invalid_request` for a bad port or option, `socket_limit`, `port_busy`, `io_failed` for any other bind failure
- Resolves: the open socket

### `screenrig.device.hdmiInput.open(options)`

**Show the player's HDMI input.** The promise resolves with a `MediaStream` of the live picture to attach to a `video` element, for a camera, a laptop or a set-top box plugged into the player. The input exists on the BrightSign XT1143, XT1144, XT1145, XT2144 and XT2145.

```javascript
const stream = await window.screenrig.device.hdmiInput.open({ audio: true });
const video = document.getElementById("input");
video.srcObject = stream;
await video.play();
```

| Parameter | Type | Required | Notes |
| --- | --- | --- | --- |
| `options.audio` | boolean | no | Also capture the input's sound. `false` by default. |

The Player lets the frame that holds the capability use the browser's capture devices, and the runtime picks the video input whose label says HDMI, or the only video input listed. The page owns the stream: stop its tracks to release the input.

- Requires: `capabilities["device.hdmi_input"]`
- Rejects: `not_supported` on a Player without an HDMI input, `capability_denied` without the capability, `invalid_request` for a bad option, `hdmi_input_unavailable` when no HDMI input is listed (or, with `audio`, no sound of it), the stream cannot open (no signal, or the input is in use) or the browser has no capture devices
- Resolves: a `MediaStream`

## Reach devices on the screen's network

Applications can connect to local `http://` and `ws://` endpoints as well as `https://` and `wss://`—for example, a local controller at `http://192.168.1.20`. See [Pages on the screen's network](https://screenrig.ai/docs/players.md#local-network) for per-platform protocol rules and Chrome/Edge enterprise policies for kiosk browsers. Your local server must return CORS headers allowing the application's origin (on macOS, requests send `Origin: null`, so allow that origin as well).

Because browsers block mixed-content `<img src="http://…">` tags on HTTPS pages, load local HTTP images via `fetch()` and `URL.createObjectURL()`:

```javascript
const response = await fetch("http://192.168.1.20/snapshot.jpg");
image.src = URL.createObjectURL(await response.blob());
```

## Subscribe to MQTT

An application can subscribe directly to an MQTT broker by bundling [mqtt.js](https://www.npmjs.com/package/mqtt) and connecting over WebSockets (`ws://` for a local-network broker or `wss://` for a cloud broker—browsers speak MQTT over WebSockets only). Because the SDK has no built-in MQTT API, your app connects directly and handles incoming messages by updating the UI, writing to `kv`, or calling `emit()`.

Bundle `mqtt` with your build tool before uploading; `app pack` excludes `node_modules/` and `vendor/`.

```javascript
import mqtt from "mqtt";

const sr = window.screenrig;
await sr.waitUntilActive();
await sr.ready();

// {"url": "ws://192.168.1.30:9001", "username": "screen", "password": "...", "topic": "lobby/occupancy"}
const config = await sr.kv.getJSON("mqtt");
const client = mqtt.connect(config.url, {
  username: config.username,
  password: config.password,
});

client.on("connect", function () {
  client.subscribe(config.topic);
});

client.on("message", function (topic, payload) {
  render(JSON.parse(payload.toString()));
});
```

`mqtt.js` automatically reconnects and resubscribes after broker restarts. In Mosquitto, expose a dedicated WebSockets listener:

```text
listener 9001
protocol websockets
```

Require authentication on that listener and restrict the account to read-only subscriptions on the topics the screen displays.

Store broker URLs and credentials in `kv` rather than hard-coding them in the bundle or passing them via `params`. Your agent can update them with [`kv set`](https://screenrig.ai/docs/cli/applications#cmd-kv-set) without uploading a new release, and the application reads them with [`kv.getJSON`](https://screenrig.ai/docs/sdk.md#kv-getjson), while `params` are untrusted hints anyone opening the URL can override. Because `kv` values are read in the browser, keep the broker account limited to subscribe-only permissions.

```console
screenrig kv set --app-id app_01EXAMPLEAPP00000000000 mqtt --json-value '{"url":"ws://192.168.1.30:9001","username":"screen","password":"...","topic":"lobby/occupancy"}'
```

Plain `ws://` connections work on Players that permit local unencrypted WebSockets (see [Pages on the screen's network](https://screenrig.ai/docs/players.md#local-network)); Samsung Smart Signage (Tizen), LG webOS Signage, and BrightSign require `wss://`.

If you use a cloud MQTT broker with an HTTP rule engine, you can forward messages directly to a [key/value webhook](https://screenrig.ai/docs/sdk.md#kv-webhooks) instead. Screens then need neither a broker connection nor credentials, and `kv.onChange` updates the display within seconds. Because each webhook accepts up to 120 posts per minute, have your rule forward summaries rather than raw high-frequency telemetry.

## Build and place the app

- [Run an application locally](https://screenrig.ai/docs/cli/applications#cmd-app-dev)
- [Pack and upload applications](https://screenrig.ai/docs/cli/applications#applications)
- [Create the playlist page](https://screenrig.ai/docs/cli/playlists#playlists)
- [Key/value commands](https://screenrig.ai/docs/cli/applications#kv)
- [Key/value webhooks](https://screenrig.ai/docs/cli/applications#kv-webhooks)
- [Read application events](https://screenrig.ai/docs/cli/notifications#events)
