# Python: calling side and device side

The package `huelake-connectivitizer` (import `connectivitizer`) connects a Python program to a service on a device (calling side), or makes a Python program a device that exposes local services (device side). It is asyncio-based and needs Python 3.10 or newer; its only dependency is `cryptography`.

## Install

```bash
pip install huelake-connectivitizer
```

From PyPI. Add `huelake-connectivitizer` to `requirements.txt` (or `pyproject.toml`) of the project.

## What you need

Decide first whether your program is the calling side (it connects to a device), the device side (it offers services), or both. The SDK is asyncio-based: a program that does not use asyncio yet runs it with `asyncio.run(...)`, or in a thread of its own. Then have these ready:

- Calling side: an **API key** (`czk_…`; web app: *Credentials → Create an API key*) for a program you run yourself. A program that other people install gets a key of its own with `link_app` instead (below).
- Device side: a **device key** (`czd_…`; web app: *Credentials → Create a device key*) and the **device name** apps will address the device by. One device key serves any number of devices, each under its own name.
- Device side: the services to expose, each with a name and its local `host:port`. Nothing else on the machine is reachable.
- A **shared key** (`czs_…`; web app: *Credentials → Generate a shared key*, or `python -m connectivitizer keygen`). The same key on both sides. It never reaches Connectivitizer.

Keep the keys in environment variables or a git-ignored `.env` file, never in committed code.

## Calling side

```python
import asyncio, os
from connectivitizer import Client

async def main():
    async with Client(
        api_key=os.environ["CZ_API_KEY"],
        shared_key=os.environ["CZ_SHARED_KEY"],       # the same key the device has
    ) as client:
        session = await client.connect("living-room-lamp", ["api"])   # device name, services
        response = await session.fetch("api", "/state")
        print(response.status, await response.json())
        print(session.info.mode)                    # 'direct' or 'e2e-relay'
        print(session.info.end_to_end_encrypted)    # established by this endpoint, not claimed by the platform

asyncio.run(main())
```

| | |
|---|---|
| `await client.list_devices()` | The devices this program may reach: name, alias, online, and the services it may use. |
| `await session.fetch(service, path, method="POST", headers={...}, body=...)` | An HTTP request: `status`, `headers`, `await text()`, `await json()`, `await bytes()`, `async for chunk in response.chunks()`. |
| `await session.websocket(service, path)` | A WebSocket: `await ws.send("...")`, `await ws.receive()` (None once closed), `async for message in ws`. |
| `await session.open_stream(service)` | The raw byte stream, for any other TCP protocol. |
| `session.info` | `mode`, `transport`, `end_to_end_encrypted`, `trust`, `peer_address`, `direct_failure_reason`. |

Errors are `ConnectivitizerError` with a stable `code`: see [Error codes](https://connectivitizer.com/guides/errors.md).

## Linking a program instead of giving it a key

A program that other people install should not ask them to type in a key. `link_app` gets it a key of its own: the person signs in on this web app and approves.

```python
from connectivitizer import link_app

linked = await link_app(
    "Report service",                     # the name it appears under in the web app
    lambda prompt: print(f"Open {prompt.url} and confirm the code {prompt.code}"),
)
# linked.api_key is returned this once: store it safely and pass it as api_key from then on
```

It raises `LINK_DENIED` when the person refused and `LINK_EXPIRED` after ten minutes. The linked program is listed, and revoked, under *Credentials*.

## Device side

```python
import asyncio, os
from connectivitizer import Agent

agent = Agent(
    device_key=os.environ["CZ_DEVICE_KEY"],   # from the workspace
    name="nas",                               # how apps address this device; it stays the same
    shared_key=os.environ["CZ_SHARED_KEY"],
    services={"api": "127.0.0.1:8080"},       # nothing else is reachable
    log=print,
)
asyncio.run(agent.run())   # reconnects by itself; stops with await agent.stop()
```

The device appears under *Devices* the first time it connects. `run()` raises when the device key was revoked.

## A device that calls another device

A running device opens sessions to other devices over its own connection to the platform. It needs no API key: the platform uses the rights of the device key the device logs in with.

- The device key has *Its devices may open sessions to other devices* switched on (web app: *Credentials*, when you create or edit the key). Without it, or for a device or service outside the access rules of the key, the platform refuses with `FORBIDDEN`.
- The device holds the other device's shared key. With several keys, the one named like the other device is used, else the only one, else the one named `default`.

```python
import asyncio, os
from connectivitizer import Agent

async def main():
    agent = Agent(
        device_key=os.environ["CZ_DEVICE_KEY"],   # a device key that may open sessions
        name="hall-panel",
        shared_key=os.environ["CZ_SHARED_KEY"],   # the same key the other device has
        services={"api": "127.0.0.1:8080"},
        log=print,
    )
    running = asyncio.ensure_future(agent.run())

    session = await agent.connect("living-room-lamp", ["api"])   # waits until the device is connected
    response = await session.fetch("api", "/state")
    print(response.status, await response.json(), session.info.mode)

    await running

asyncio.run(main())
```

| | |
|---|---|
| `await agent.connect(device, services)` | Opens a session to another device by its name. The session offers what the calling side's session offers. |
| `await agent.list_devices()` | The devices this device may reach, without itself: name, alias, online, and the services it may use. |
| `agent.outgoing_sessions` | The `info` of the sessions this device opened that are still running. |

Sessions the device opened stay open while it reconnects to the platform, and end when the device stops, or when the device or its device key is revoked.

## Good to know

- Direct sessions need nothing from your code: the SDK finds the machine's addresses (IPv4 and IPv6), binds UDP and punches through the routers. Whether a session is direct depends on the networks: [Troubleshooting](https://connectivitizer.com/guides/troubleshooting.md).
- Certificates and pairing are not available in Python; both sides use the shared key.

## A screen in the Connectivitizer app

Your device can bring its own screen: one HTML page that the Connectivitizer app shows when someone taps the device, so there is no app to write. The device serves two files on the service the app connects to (`ui`, else `api`): `GET /.cz/ui.json`, the manifest `{"name": "Desk lamp", "entry": "/.cz/ui.html", "version": "1"}`, and `GET /.cz/ui.html`, the page.

The page, as `ui.html`: a switch, a slider and a value the device reports, with a comment at each part to show where yours go.

```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>
```

A web server for the page, with `ui.html` next to it. It listens on `127.0.0.1:8080`, which the device side above exposes as `api` (`services={"api": "127.0.0.1:8080"}`).

```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()
```

More controls to copy, a preview on your computer that needs no device, what a page can do (colours for the app's bar, the camera, the location, links), and finished examples, with a short start for anyone new to HTML: [Device screens](https://connectivitizer.com/guides/device-screen.md).
