# Device screens: your device's own page in the Connectivitizer app

Your device can bring its own screen: one HTML page that it serves itself. The Connectivitizer app shows that page when someone taps the device, and `cz ui` shows it in a browser on a computer.

You don't build or publish an app, and nothing is uploaded anywhere. The page reaches the screen over the same end-to-end encrypted session as everything else, and when you change it on the device, the next open shows the new version.

<!-- cz:phones starter greenhouse -->

This guide takes a device that already connects (the quickstart at https://connectivitizer.com gets you there) and gives it the page on the left in a few minutes: a switch, a slider and a value the device reports. Then it shows how to try changes on your computer, how to add your own controls, colours, the camera and the other things a page can do, and finished examples to start from. You have never written a web page? Section 1 explains the little you need.

## How it works

<!-- cz:diagram screen -->

When the app opens the device, it connects to the service named `ui`, else `api`, else the device's only service. Then it asks for two files with `GET`:

| The app asks for | The device answers |
|---|---|
| `/.cz/ui.json` | the manifest, `application/json`: `{"name": "Desk lamp", "entry": "/.cz/ui.html", "version": "1"}` |
| `/.cz/ui.html` | the page, `text/html`: one file with its scripts and styles inline, at most 2 MB, served uncompressed |

A device without a screen answers `/.cz/ui.json` with `404`. Everything else the page asks for (`fetch("/state")`) goes to the same service, so your device's web server is all there is to it.

## 1. The page

Save this as `ui.html`. It shows whether the lamp is on, a button switches it, a slider sets its brightness, and it shows how long the device has been running, refreshed every two seconds:

```html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- CSS: how the page looks -->
<style>
  body { margin: 0; padding: 24px; font: 16px system-ui, sans-serif; background: #fdf6e3; color: #3b3526; }
  h1 { font-size: 44px; margin: 4px 0 24px; }
  label { display: block; margin: 28px 0 8px; }
  button { font: inherit; padding: 12px 24px; border-radius: 12px; border: 0; background: #b58900; color: #fff; }
  input, select { font: inherit; padding: 10px; border-radius: 10px; border: 1px solid #c8b98a; background: #fff; color: inherit; }
  input[type=range] { width: 100%; padding: 0; border: 0; background: none; accent-color: #b58900; }
</style>

<!-- HTML: what is on the page. Each id connects an element to the script below. -->
<p>Desk lamp</p>
<h1 id="state">…</h1>
<button id="toggle">Switch</button>

<label for="level">Brightness: <b id="level-value">…</b> %</label>
<input id="level" type="range" min="0" max="100" step="5">

<p>Running for <b id="uptime">…</b> s</p>

<!-- JavaScript: what happens. fetch('/…') goes to the device, through the app. -->
<script>
  const $ = (id) => document.getElementById(id);

  // The device answers every request with its state, e.g. {"on":true,"level":40,"uptime":120}.
  // show() puts it on the page: one line per value.
  const show = async (response) => {
    const s = await response.json();
    $('state').textContent = s.on ? 'On' : 'Off';
    $('level-value').textContent = s.level;
    if (document.activeElement !== $('level')) $('level').value = s.level;
    $('uptime').textContent = s.uptime;
  };
  const refresh = () => fetch('/state').then(show).catch(() => { $('state').textContent = 'No /state yet'; });

  // A tap or a change sends a request; the answer is shown right away.
  $('toggle').onclick = () => fetch('/toggle', { method: 'POST' }).then(show);
  $('level').oninput = () => { $('level-value').textContent = $('level').value; };
  $('level').onchange = () => fetch('/level?value=' + $('level').value, { method: 'POST' }).then(show);

  refresh();
  setInterval(refresh, 2000);   // new values every 2 seconds
</script>
</html>
```

`fetch('/state')` goes to the device, through the app. The same page also works when you open it in a browser straight from the device on your own network.

### New to HTML, CSS and JavaScript?

You don't need to learn much of them for a page like this. The page has three parts, each marked in the code above:

- **HTML** is what is on the page: a heading, a button, a slider. Each element that the script changes or listens to has an `id`, such as `id="toggle"`.
- **CSS** (in `<style>`) is how it looks: sizes, colours, spacing. Change a colour code like `#b58900` and the button changes.
- **JavaScript** (in `<script>`) is what happens. `$('toggle')` finds the element with `id="toggle"`; `.onclick = …` says what a tap does.

A tap travels like this: the button's `onclick` calls `fetch('/toggle', { method: 'POST' })`, the request goes through the app to your device, the device runs its `/toggle` route and answers with its state as JSON (`{"on":true,"level":40,"uptime":120}`), and `show()` writes each value into the page. Every control in this guide works the same way, so adding one means three small steps: an element in the HTML, a line in the script that sends its request, and a route on the device that answers it.

To see errors, open the page in the preview (section 4) and press F12 (on a Mac, Cmd+Option+I): the *Console* shows every error with its line. Section 5 has ready-made controls to copy.

**Let an AI assistant write it.** Assistants are good at exactly this. Give yours the page and your device's code, and a request like:

> Add a control to my Connectivitizer device screen (ui.html) and the matching route to my device's web server. The control: a number field "Target temperature", 5 to 35 in steps of 0.5, sent as `POST /target?value=<number>`; the device keeps it and adds `"target"` to the JSON it answers `/state` with. Keep the page one file with inline CSS and JavaScript, no external files, no localStorage or cookies, and use `fetch` with paths like `/target`, never the device's address. The rules are in https://connectivitizer.com/guides/device-screen.md.

## 2. Serve it

Pick the language of your device. Each snippet is a complete web server on `127.0.0.1:8080`, the address the device guides expose as the service `api`, and it answers the two files plus the page's own requests: `GET /state`, `POST /toggle` and `POST /level?value=40`, each answered with the state. On an ESP32 the routes go on the sketch's own web server instead.

```cpp tab="ESP32 (Arduino)"
// In the sketch: the routes go on the WebServer that is exposed as "api" (port 80).
static const char UI_JSON[] PROGMEM = R"({"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"})";
static const char UI_HTML[] PROGMEM = R"html(<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">

<!-- CSS: how the page looks -->
<style>
  body { margin: 0; padding: 24px; font: 16px system-ui, sans-serif; background: #fdf6e3; color: #3b3526; }
  h1 { font-size: 44px; margin: 4px 0 24px; }
  label { display: block; margin: 28px 0 8px; }
  button { font: inherit; padding: 12px 24px; border-radius: 12px; border: 0; background: #b58900; color: #fff; }
  input, select { font: inherit; padding: 10px; border-radius: 10px; border: 1px solid #c8b98a; background: #fff; color: inherit; }
  input[type=range] { width: 100%; padding: 0; border: 0; background: none; accent-color: #b58900; }
</style>

<!-- HTML: what is on the page. Each id connects an element to the script below. -->
<p>Desk lamp</p>
<h1 id="state">…</h1>
<button id="toggle">Switch</button>

<label for="level">Brightness: <b id="level-value">…</b> %</label>
<input id="level" type="range" min="0" max="100" step="5">

<p>Running for <b id="uptime">…</b> s</p>

<!-- JavaScript: what happens. fetch('/…') goes to the device, through the app. -->
<script>
  const $ = (id) => document.getElementById(id);

  // The device answers every request with its state, e.g. {"on":true,"level":40,"uptime":120}.
  // show() puts it on the page: one line per value.
  const show = async (response) => {
    const s = await response.json();
    $('state').textContent = s.on ? 'On' : 'Off';
    $('level-value').textContent = s.level;
    if (document.activeElement !== $('level')) $('level').value = s.level;
    $('uptime').textContent = s.uptime;
  };
  const refresh = () => fetch('/state').then(show).catch(() => { $('state').textContent = 'No /state yet'; });

  // A tap or a change sends a request; the answer is shown right away.
  $('toggle').onclick = () => fetch('/toggle', { method: 'POST' }).then(show);
  $('level').oninput = () => { $('level-value').textContent = $('level').value; };
  $('level').onchange = () => fetch('/level?value=' + $('level').value, { method: 'POST' }).then(show);

  refresh();
  setInterval(refresh, 2000);   // new values every 2 seconds
</script>
</html>)html";
static bool on = false;
static int level = 50;

static void sendState() {
  String json = String("{\"on\":") + (on ? "true" : "false") + ",\"level\":" + level +
                ",\"uptime\":" + (millis() / 1000) + "}";
  server.send(200, "application/json", json);
}

// in setup(), before server.begin():
server.on("/.cz/ui.json", HTTP_GET, [] { server.send_P(200, "application/json", UI_JSON); });
server.on("/.cz/ui.html", HTTP_GET, [] { server.send_P(200, "text/html; charset=utf-8", UI_HTML); });
server.on("/state", HTTP_GET, sendState);
server.on("/toggle", HTTP_POST, [] {
  on = !on;   // switch your pin here: digitalWrite(LED_PIN, on);
  sendState();
});
server.on("/level", HTTP_POST, [] {
  level = constrain(server.arg("value").toInt(), 0, 100);   // e.g. analogWrite(LED_PIN, level * 255 / 100);
  sendState();
});
```

```js tab="Node.js"
// server.mjs, with ui.html next to it. Start it in the same program as the agent, or on its own.
import { createServer } from 'node:http';
import { readFileSync } from 'node:fs';

const manifest = '{"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"}';
const page = readFileSync(new URL('./ui.html', import.meta.url));
const started = Date.now();
let on = false;
let level = 50;
const state = () => JSON.stringify({ on, level, uptime: Math.round((Date.now() - started) / 1000) });

createServer((request, response) => {
  const send = (type, body) => response.writeHead(200, { 'Content-Type': type }).end(body);
  const url = new URL(request.url, 'http://device');
  const route = `${request.method} ${url.pathname}`;
  if (route === 'GET /.cz/ui.json') return send('application/json', manifest);
  if (route === 'GET /.cz/ui.html') return send('text/html; charset=utf-8', page);
  if (route === 'GET /state') return send('application/json', state());
  if (route === 'POST /toggle') { on = !on; return send('application/json', state()); }
  if (route === 'POST /level') {
    level = Math.min(100, Math.max(0, Number(url.searchParams.get('value')) || 0));
    return send('application/json', state());
  }
  response.writeHead(404).end();
}).listen(8080, '127.0.0.1');
```

```python tab="Python"
# screen.py, with ui.html next to it. start_screen() before asyncio.run(agent.run()).
import json
import threading
import time
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
from urllib.parse import parse_qs, urlsplit

MANIFEST = b'{"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"}'
PAGE = (Path(__file__).parent / "ui.html").read_bytes()
STARTED = time.monotonic()
state = {"on": False, "level": 50}


def state_json():
    return json.dumps({**state, "uptime": int(time.monotonic() - STARTED)}).encode()


class Screen(BaseHTTPRequestHandler):
    def send(self, kind, body):
        self.send_response(200)
        self.send_header("Content-Type", kind)
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_GET(self):
        path = urlsplit(self.path).path
        if path == "/.cz/ui.json":
            return self.send("application/json", MANIFEST)
        if path == "/.cz/ui.html":
            return self.send("text/html; charset=utf-8", PAGE)
        if path == "/state":
            return self.send("application/json", state_json())
        self.send_error(404)

    def do_POST(self):
        url = urlsplit(self.path)
        if url.path == "/toggle":
            state["on"] = not state["on"]
            return self.send("application/json", state_json())
        if url.path == "/level":
            value = parse_qs(url.query).get("value", ["0"])[0]
            state["level"] = max(0, min(100, int(value) if value.isdigit() else 0))
            return self.send("application/json", state_json())
        self.send_error(404)


def start_screen():
    server = ThreadingHTTPServer(("127.0.0.1", 8080), Screen)
    threading.Thread(target=server.serve_forever, daemon=True).start()
```

```csharp tab="C# / .NET"
// Program.cs of an ASP.NET project (dotnet new web), with ui.html next to it and in the .csproj:
// <None Update="ui.html" CopyToOutputDirectory="PreserveNewest" />
var builder = WebApplication.CreateBuilder(args);
builder.WebHost.UseUrls("http://127.0.0.1:8080");
var web = builder.Build();

var page = File.ReadAllText(Path.Combine(AppContext.BaseDirectory, "ui.html"));
var started = DateTime.UtcNow;
var on = false;
var level = 50;
object State() => new { on, level, uptime = (int)(DateTime.UtcNow - started).TotalSeconds };

web.MapGet("/.cz/ui.json", () => Results.Text("""{"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"}""", "application/json"));
web.MapGet("/.cz/ui.html", () => Results.Text(page, "text/html; charset=utf-8"));
web.MapGet("/state", () => Results.Json(State()));
web.MapPost("/toggle", () => { on = !on; return Results.Json(State()); });
web.MapPost("/level", (int value) => { level = Math.Clamp(value, 0, 100); return Results.Json(State()); });

await web.StartAsync();   // then start the agent, which exposes 127.0.0.1:8080 as "api"
```

```java tab="Java"
// Screen.java, with ui.html in the working directory. Screen.start() before agent.run().
// The JDK's own web server: no dependency. (On Android, use an embedded server such as NanoHTTPD.)
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;

public final class Screen {
    private static final byte[] MANIFEST = "{\"name\":\"Desk lamp\",\"entry\":\"/.cz/ui.html\",\"version\":\"1\"}".getBytes(StandardCharsets.UTF_8);
    private static final long STARTED = System.currentTimeMillis();
    private static volatile boolean on = false;
    private static volatile int level = 50;

    private static void send(HttpExchange exchange, String type, byte[] body) throws IOException {
        exchange.getResponseHeaders().set("Content-Type", type);
        exchange.sendResponseHeaders(200, body.length);
        try (var out = exchange.getResponseBody()) {
            out.write(body);
        }
    }

    private static byte[] state() {
        long uptime = (System.currentTimeMillis() - STARTED) / 1000;
        return ("{\"on\":" + on + ",\"level\":" + level + ",\"uptime\":" + uptime + "}").getBytes(StandardCharsets.UTF_8);
    }

    public static void start() throws IOException {
        byte[] page = Files.readAllBytes(Path.of("ui.html"));
        HttpServer server = HttpServer.create(new InetSocketAddress("127.0.0.1", 8080), 0);
        server.createContext("/.cz/ui.json", exchange -> send(exchange, "application/json", MANIFEST));
        server.createContext("/.cz/ui.html", exchange -> send(exchange, "text/html; charset=utf-8", page));
        server.createContext("/state", exchange -> send(exchange, "application/json", state()));
        server.createContext("/toggle", exchange -> {
            if ("POST".equals(exchange.getRequestMethod())) on = !on;
            send(exchange, "application/json", state());
        });
        server.createContext("/level", exchange -> {
            String query = exchange.getRequestURI().getQuery();   // "value=40"
            if ("POST".equals(exchange.getRequestMethod()) && query != null && query.matches("value=\\d{1,3}")) {
                level = Math.min(100, Integer.parseInt(query.substring("value=".length())));
            }
            send(exchange, "application/json", state());
        });
        server.start();
    }
}
```

```kotlin tab="Kotlin"
// Screen.kt, with ui.html in the working directory. startScreen() before agent.run().
// The JDK's own web server: no dependency. (On Android, use an embedded server such as NanoHTTPD.)
import com.sun.net.httpserver.HttpExchange
import com.sun.net.httpserver.HttpServer
import java.io.File
import java.net.InetSocketAddress

private val started = System.currentTimeMillis()
@Volatile private var on = false
@Volatile private var level = 50

private fun HttpExchange.send(type: String, body: ByteArray) {
    responseHeaders.set("Content-Type", type)
    sendResponseHeaders(200, body.size.toLong())
    responseBody.use { it.write(body) }
}

private fun state(): ByteArray {
    val uptime = (System.currentTimeMillis() - started) / 1000
    return """{"on":$on,"level":$level,"uptime":$uptime}""".toByteArray()
}

fun startScreen() {
    val manifest = """{"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"}""".toByteArray()
    val page = File("ui.html").readBytes()
    HttpServer.create(InetSocketAddress("127.0.0.1", 8080), 0).apply {
        createContext("/.cz/ui.json") { it.send("application/json", manifest) }
        createContext("/.cz/ui.html") { it.send("text/html; charset=utf-8", page) }
        createContext("/state") { it.send("application/json", state()) }
        createContext("/toggle") {
            if (it.requestMethod == "POST") on = !on
            it.send("application/json", state())
        }
        createContext("/level") {
            val value = it.requestURI.query?.removePrefix("value=")?.toIntOrNull()
            if (it.requestMethod == "POST" && value != null) level = value.coerceIn(0, 100)
            it.send("application/json", state())
        }
        start()
    }
}
```

```bash tab="cz (any language)"
# Your program's web server answers GET /.cz/ui.json and GET /.cz/ui.html, and the page's own
# requests: GET /state, POST /toggle and POST /level?value=40, each with {"on":…,"level":…,"uptime":…}.
# To see the page first, any static server will do (the switch and the slider need your program):
mkdir -p screen/.cz
cp ui.html screen/.cz/ui.html   # the page
echo '{"name":"Desk lamp","entry":"/.cz/ui.html","version":"1"}' > screen/.cz/ui.json
python3 -m http.server 8080 --bind 127.0.0.1 --directory screen

# exposed as "api" by: cz service add api 127.0.0.1:8080 --protocol http
```

## 3. Open it

![The device list in the app](/docs/screens/app-devices.webp)
![A device's screen in the app](/docs/screens/app-greenhouse.webp)

- **On the phone:** in the Connectivitizer app, tap the device. The first time, add the device's shared key under *Account › Keys › Add a key*: [The Connectivitizer app](https://connectivitizer.com/guides/mobile-app.md) explains how.
- **On the computer:** `cz ui <device>` opens the page in your browser, through Connectivitizer, with the keys staying on your machine ([cz](https://connectivitizer.com/guides/cz.md)). The web app at https://connectivitizer.com does not show device screens, because your shared key would have to be used on our website.

To change the page, edit it, then restart the device's program (or flash the ESP32 again) and open the device again. The app always loads the page the device serves now. While you are still trying things, the preview below is quicker.

If devices are limited to certain clients (*Clients allowed to connect* on the device's page in the web app), the app is the client **Connectivitizer**.

## 4. Try changes on your computer

`screen-preview.mjs` shows your `ui.html` in the browser on your computer and reloads it each time you save. It is one file for Node.js 18 or later, with nothing to install:

```bash
curl -fsSLO https://connectivitizer.com/downloads/tools/screen-preview.mjs
node screen-preview.mjs ui.html --fake fake-device.js --open
```

**Without the device:** `--fake` answers the page's requests with a pretend device, so you can work on the page before the device's code exists, or away from the hardware. This one answers the starter page; save it as `fake-device.js` and give it a route for each request your page makes:

```js
// fake-device.js: answers the page's requests the way the device will, with made-up values.
czDemo.define({
  routes: {
    'GET /state': (request, ctx) => state(ctx),
    'POST /toggle': (request, ctx) => {
      ctx.state.on = !ctx.state.on;
      return state(ctx);
    },
    'POST /level': (request, ctx) => {
      ctx.state.level = Math.min(100, Math.max(0, Number(request.query.get('value')) || 0));
      return state(ctx);
    },
  },
});

function state(ctx) {
  return { on: ctx.state.on === true, level: ctx.state.level ?? 50, uptime: Math.round(ctx.seconds()) };
}
```

`request.query.get('value')` is what the page sent after `?value=`, `ctx.state` keeps values between requests, and `ctx.seconds()` counts from the start. What a route returns is the answer, as JSON.

**With the device:** `--device` sends the page's requests to the real device, while the page comes from your file. On an ESP32 nothing has to be flashed until the page is done:

```bash
node screen-preview.mjs ui.html --device http://192.168.1.50      # the ESP32 on your network (WiFi.localIP())
node screen-preview.mjs ui.html --device http://127.0.0.1:8080    # a program on this computer
```

The preview runs the page under the same rules as the app (its Content-Security-Policy), so what works here works there. It also prints what the app would refuse, such as a picture loaded from the device by its address or the use of `localStorage`. When the page is done, put it on the device: replace `ui.html` next to the program and restart it, or on an ESP32 paste it into the `UI_HTML` string and flash.

## 5. Add controls

Each control below adds to the starter page: the HTML goes with the other elements, the script lines into `<script>`, and the `show()` line into `show()`. Every control sends its value after `?value=`, so the device reads them all the same way, and every route answers with the state, so the page shows the result at once. Add the new values to the JSON your device answers `/state` with.

**A button that does something once**, `POST /feed`:

```html
<button id="feed">Feed the fish</button>
```

```js
$('feed').onclick = () => fetch('/feed', { method: 'POST' }).then(show);
```

**An on/off switch**, `POST /pump?value=1` or `?value=0`, and `"pump": true` in the state:

```html
<label><input id="pump" type="checkbox"> Pump</label>
```

```js
$('pump').onchange = () => fetch('/pump?value=' + ($('pump').checked ? 1 : 0), { method: 'POST' }).then(show);
// in show():
$('pump').checked = s.pump;
```

**A number field with a button**, `POST /target?value=21.5`:

```html
<label for="target">Target temperature (°C)</label>
<input id="target" type="number" min="5" max="35" step="0.5"> <button id="save">Save</button>
```

```js
$('save').onclick = () => fetch('/target?value=' + $('target').value, { method: 'POST' }).then(show);
// in show(), so that typing is not overwritten:
if (document.activeElement !== $('target')) $('target').value = s.target;
```

**A slider** is in the starter page: `<input type="range">` with `oninput` for the number next to it and `onchange` to send it when the finger lifts.

**A text field**, `POST /name?value=…`:

```html
<label for="name">Name on the display</label>
<input id="name" maxlength="40"> <button id="rename">Save</button>
```

```js
$('rename').onclick = () => fetch('/name?value=' + encodeURIComponent($('name').value), { method: 'POST' }).then(show);
```

`encodeURIComponent` lets spaces and other characters through; the device's web server decodes them.

**A choice from a list**, `POST /mode?value=auto`:

```html
<label for="mode">Mode</label>
<select id="mode">
  <option value="auto">Automatic</option>
  <option value="on">Always on</option>
  <option value="off">Off</option>
</select>
```

```js
$('mode').onchange = () => fetch('/mode?value=' + $('mode').value, { method: 'POST' }).then(show);
// in show():
$('mode').value = s.mode;
```

**A value the device reports**, `"temperature": 21.4` in the state, refreshed with everything else:

```html
<p>Temperature: <b id="temperature">…</b> °C</p>
```

```js
// in show():
$('temperature').textContent = s.temperature.toFixed(1);
```

**A warning that shows only when needed**, `"tankEmpty": true` in the state:

```html
<p id="tank-warning" hidden style="color: #b00020"><b>The tank is empty.</b></p>
```

```js
// in show():
$('tank-warning').hidden = !s.tankEmpty;
```

**A small chart of the last values**, drawn as a line in SVG:

```html
<svg viewBox="0 0 290 80" width="100%" height="80"><polyline id="line" fill="none" stroke="currentColor" stroke-width="2" /></svg>
```

```js
const recent = [];
// in show():
recent.push(s.temperature);
if (recent.length > 30) recent.shift();
const low = Math.min(...recent), high = Math.max(...recent), span = high - low || 1;
$('line').setAttribute('points', recent.map((v, i) => i * 10 + ',' + (75 - ((v - low) / span) * 70)).join(' '));
```

**On the device**, each control is one more route next to `/level` in the starter server of your language, and the value is read the same way everywhere:

| Device | The value after `?value=` |
|---|---|
| ESP32 (Arduino) | `server.arg("value")`, with `.toInt()` or `.toFloat()` for a number |
| Node.js | `url.searchParams.get('value')` |
| Python | `parse_qs(url.query).get("value", [""])[0]` |
| C# / .NET | a parameter of the handler: `(int value)`, `(double value)` or `(string value)` |
| Java, Kotlin | `exchange.getRequestURI().getQuery()` is `value=…`; for text, decode it with `URLDecoder.decode(…, StandardCharsets.UTF_8)` |

On an ESP32, the switch above is:

```cpp
static bool pump = false;
// in setup():
server.on("/pump", HTTP_POST, [] {
  pump = server.arg("value") == "1";
  digitalWrite(PUMP_PIN, pump);
  sendState();   // with ",\"pump\":" + String(pump ? "true" : "false") added to its JSON
});
```

## 6. Talk to the device

- `fetch("/info")` and `fetch("/led", { method: "POST", body: "on" })` go to the device, through the app.
- `window.connectivitizer.webSocket("/events")` opens a WebSocket to the device. A browser `new WebSocket(...)` does not reach it.
- Files on the device are not loaded by URL: `<img src="/snapshot.jpg">` stays empty. Fetch them instead: `URL.createObjectURL(await (await fetch("/snapshot.jpg")).blob())` gives a `blob:` URL for an `<img>`.
- `window.connectivitizer` exists only in the app (and in `cz ui`), so check for it, and the page also works when opened straight from the device.

## 7. Give it colours

<!-- cz:phones starter starter-themed -->

The app's bar above the page (the device's name, the connection line and the phone's status bar) can take the page's colours. Add a theme to `ui.json`:

```json
{ "name": "Desk lamp", "entry": "/.cz/ui.html", "version": "2",
  "theme": { "background": "#fdf6e3", "foreground": "#3b3526" } }
```

Give the page's `<body>` the same background, so nothing flashes while it loads. A page that changes its look (day and night) calls `window.connectivitizer?.setTheme({ background, foreground })`, and `setTheme(null)` goes back to the manifest's. Colours are `#rgb` or `#rrggbb`, and the two have to be readable together (a contrast of at least 4.5 : 1); otherwise the app keeps its own. The bar's text and buttons stay the app's.

**A theme for the whole app:** `ui.json` can also offer up to three themes for the whole app, `"appThemes": [{ "id": "camera-green", "name": "Camera green", "version": "1", "palette": { … } }]`. The palette has every colour of the app's own themes as `#rgb` or `#rrggbb`: `background`, `card`, `text`, `muted`, `border`, `tint`, `onTint`, `good`, `goodBackground`, `warn`, `warnBackground`, `bad`, `badBackground`, `neutralBackground`. The app asks once whether to add a theme, and again only when its colours or version change; added themes are chosen under *Account › Appearance* and stay on the phone. A theme that makes text or warnings hard to read is refused: text needs a contrast of 4.5 : 1 on its backgrounds, as do `onTint` on `tint` and `good`, `warn` and `bad` on their own backgrounds; `muted` and `tint` need 3 : 1 on `background` and `card`, `bad` and `warn` 3 : 1 on `card`, and `border` 1.2 : 1 on `card`.

## 8. What a page can and cannot do

The app shows the page under a Content-Security-Policy that the page cannot loosen:

- **Your device, and the internet over `https:`.** Inline scripts and styles run. Scripts, styles, pictures, video, fonts and frames load from `https:` addresses (your own server, map tiles, a library from a CDN), and `fetch("https://…")`, `XMLHttpRequest` and `new WebSocket("wss://…")` reach `https:` and `wss:` servers. Plain `http:` is blocked, and so are forms and `eval`.
- **Links, camera, microphone and location only if the person allows them.** Each person who uses the app decides for themselves, under *Account › Security*: *Device pages may open links*, *… may ask for the camera*, *… may ask for the microphone*, *… may ask for your location*. All four are off at first. While one is off, your page's request is refused without a question (`getUserMedia()` rejects with `NotAllowedError`, a location request fails with `PERMISSION_DENIED`, a link does nothing), and the app tells the person, each time, that they can turn it on. While it is on, the app asks, with your device's name and what the page wants (*"Greenhouse wants to use the camera"*, or the full address of a link): *Allow once* counts for that one request, *Always allow* for every later request of your device's page for the same thing (for a link, that exact address). The person can forget such decisions under *Account › Security*. A link is asked about only right after a tap on the page, at most three times a minute; a page that navigates by itself gets nowhere. Places in the page (`#/settings`) work.
- **Photos and files when the person picks them**, whatever the switches say: `<input type="file" accept="image/*" capture="environment">` opens the phone's camera or file picker on a tap, and the page can send the picture to its device (`fetch("/upload", { method: "POST", body: file })`).
- **No stored data:** no `localStorage`, no cookies. What has to last belongs on the device.

**Asking the person to turn something on.** Expect the refusal and say what to do, next to the button that needs it:

```js
async function startScanner() {
  try {
    video.srcObject = await navigator.mediaDevices.getUserMedia({ video: { facingMode: "environment" } });
  } catch (error) {
    hint.textContent = window.connectivitizer
      ? "To scan, turn on \"Device pages may ask for the camera\" under Account › Security in the Connectivitizer app, then tap Scan again."
      : "The camera is not available.";
  }
}
scanButton.onclick = startScanner;
```

Ask from a button rather than when the page opens: the person then knows why the question comes. Each tap asks again, so ask once per action, not in a loop. Whatever the camera, microphone or location gives your page goes where your page sends it: to your device, or to a server you name. Connectivitizer does not receive it.

On an ESP32, embed the page in the firmware (ESP-IDF `EMBED_TXTFILES`, Arduino a `PROGMEM` string as above) and keep it small, tens of KB.

## 9. Examples to start from

Each archive has a finished page, the code for its device (or devices), and a README. They run on the start page of https://connectivitizer.com with simulated data; `demo-kit/` in each archive is what simulates the device, so a page can be tried and changed without the hardware. **Code** opens the same files in the browser, to read before downloading.

<!-- cz:gallery -->

| Example | Device | Look | Code | Download |
|---|---|---|---|---|
| Greenhouse: soil, climate, tank, a pump | ESP32, Arduino sketch | soft, botanical | [Code](https://connectivitizer.com/examples/greenhouse) | https://connectivitizer.com/downloads/examples/greenhouse.zip |
| LED strip: colour, brightness, effects | ESP32, Arduino sketch | neon glass | [Code](https://connectivitizer.com/examples/lights) | https://connectivitizer.com/downloads/examples/lights.zip |
| Rover: a joystick over a WebSocket, with a dead-man stop | ESP32, Arduino sketch | retro arcade | [Code](https://connectivitizer.com/examples/rover) | https://connectivitizer.com/downloads/examples/rover.zip |
| Aquarium: a lamp that follows the day, a feeder, the water's temperature | ESP32, Arduino sketch | living scene | [Code](https://connectivitizer.com/examples/aquarium) | https://connectivitizer.com/downloads/examples/aquarium.zip |
| 3D printer companion, with a simulated printer | Raspberry Pi, Python | blueprint | [Code](https://connectivitizer.com/examples/printer) | https://connectivitizer.com/downloads/examples/printer.zip |
| Observatory: a simulated telescope, and a PC at home that stacks its frames | Raspberry Pi and a PC, Python | night vision | [Code](https://connectivitizer.com/examples/observatory) | https://connectivitizer.com/downloads/examples/observatory.zip |
| Home lab: load and containers of a server | Linux PC or Raspberry Pi, Python, exposed with `cz` | clean rack | [Code](https://connectivitizer.com/examples/homelab) | https://connectivitizer.com/downloads/examples/homelab.zip |
| PC stats: CPU, memory, GPU, disks, network | Windows PC, C# | terminal green | [Code](https://connectivitizer.com/examples/pc-stats) | https://connectivitizer.com/downloads/examples/pc-stats.zip |
| Two lamps in two homes: touch one, the other glows | two Raspberry Pis, Python | warm evening | [Code](https://connectivitizer.com/examples/lamps) | https://connectivitizer.com/downloads/examples/lamps.zip |
| Two lamps, two homes, one connection | two ESP32s, Arduino sketch | rings of light | [Code](https://connectivitizer.com/examples/lamps-esp32) | https://connectivitizer.com/downloads/examples/lamps-esp32.zip |
| Arcade duel: two cabinets in two homes, one match | two Raspberry Pis, Python | glowing vectors | [Code](https://connectivitizer.com/examples/arcade) | https://connectivitizer.com/downloads/examples/arcade.zip |
| Mailbox: a sensor at the mailbox calls a light indoors | two ESP32s, Arduino sketches | paper and postmark | [Code](https://connectivitizer.com/examples/mailbox) | https://connectivitizer.com/downloads/examples/mailbox.zip |
| Sightings (field log): a journal of birds and butterflies with a photo, species, count, a voice note and the location, sent to the device | any PC or a container, Node.js | nature journal | [Code](https://connectivitizer.com/examples/field-log) | https://connectivitizer.com/downloads/examples/field-log.zip |

In the observatory and the last four, more than the phone opens sessions to the device: a program on a PC, or a second device; their READMEs show how. Each README says what of it has been run and on what. The sketches compile; unless a README says otherwise they have not been run on hardware.

## When something does not work

| The app says | |
|---|---|
| "This device brings no screen of its own" | The device answers `/.cz/ui.json` with 404 or with something that is not JSON. `curl http://<device>/.cz/ui.json` on its network shows what it answers. Check that the web server with the two routes is the one exposed as `ui` or `api`. |
| The screen stays empty | The page fails in the WebView. Open it in a browser from the device (`http://<device>/.cz/ui.html`) and check its console. A picture, script or font from a URL, also `<img src="/…">` on the device, is blocked in the app: inline it, or fetch it and show it from a `blob:` URL. |
| The page shows, but buttons do nothing | The page's own requests (`/state`, `/toggle` here) go to the same service: check that the server answers them, and that they are paths (`/state`), not addresses (`http://192.168.…/state`). |
| A control does nothing, and the console says `Cannot set properties of null` | An `id` in the script that is not in the HTML, or spelled differently: `$('toggle')` needs `id="toggle"`. |
| The console says `Unexpected token` or `is not valid JSON` | The device's answer is not JSON. Open `http://<device>/state` in a browser on its network and look at it; on an ESP32 a missing `\"` in the string that builds the JSON is the usual cause. |
| The device answers 404 or 405 to a control | The path or the method differs: `fetch('/pump', { method: 'POST' })` needs a route for `/pump` that takes POST (`HTTP_POST` on the ESP32). |
| A value arrives as 0 or empty | The name after `?` differs between the page and the device: `?value=` in the page, `server.arg("value")` (or your language's way, section 5) on the device. |
| It works in the preview, not on the device | The device still serves the old page: restart its program or flash the ESP32 again, then open the device again in the app. |
| Keys, access and connection messages | [The Connectivitizer app](https://connectivitizer.com/guides/mobile-app.md), "When something does not work". |
