# Java and Kotlin (JVM, Android): calling side and device side

The library `com.huelake:connectivitizer-jvm` connects a Java or Kotlin program, or an Android app, to a service on a device (calling side), or makes a program a device that exposes local services (device side). It is written in Kotlin and has a Java-friendly API (builders, blocking calls, `CompletableFuture`). It runs on Java 11 or newer and on Android 9 (API 28) or newer; its only dependency is `kotlinx-coroutines-core`.

## Install

From the Connectivitizer Maven repository, https://packages.connectivitizer.com/maven (not Maven Central). The latest version is the `<release>` in https://packages.connectivitizer.com/maven/com/huelake/connectivitizer-jvm/maven-metadata.xml; use that number, not a dynamic version.

Gradle (Kotlin DSL):

```kotlin
// build.gradle.kts (in an Android project: settings.gradle.kts, inside dependencyResolutionManagement)
repositories {
    // com.huelake comes from the Connectivitizer repository only.
    exclusiveContent {
        forRepository { maven { url = uri("https://packages.connectivitizer.com/maven") } }
        filter { includeGroup("com.huelake") }
    }
    mavenCentral()
}

dependencies {
    implementation("com.huelake:connectivitizer-jvm:<version>")
}
```

Maven:

```xml
<repositories>
  <repository>
    <id>connectivitizer</id>
    <url>https://packages.connectivitizer.com/maven</url>
  </repository>
</repositories>

<dependency>
  <groupId>com.huelake</groupId>
  <artifactId>connectivitizer-jvm</artifactId>
  <version><!-- version --></version>
</dependency>
```

An Android app needs the `INTERNET` permission in its manifest and a `minSdk` of 28 or higher.

## 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. Then have these ready:

- Calling side: an **API key** (`czk_…`; web app: *Credentials → Create an API key*) for a program you run yourself. An app that other people install gets a key of its own with `Link.linkApp` 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*). The same key on both sides. It never reaches Connectivitizer.

Keep the keys in environment variables, a git-ignored properties file or a secret store (on Android: encrypted with a key from the Android Keystore), never in committed code.

## Calling side

Kotlin:

```kotlin
ConnectivitizerClient.builder()
    .apiKey(System.getenv("CZ_API_KEY"))
    .sharedKey(System.getenv("CZ_SHARED_KEY"))        // the same key the device has
    .build()
    .use { client ->
        val session = client.connect("living-room-lamp", listOf("api"))   // device name, services
        val response = session.fetch("api", "/state")
        println("${response.status} ${response.text()}")
        println(session.info.mode)                // "direct" or "e2e-relay"
        println(session.info.endToEndEncrypted)   // established by this endpoint, not claimed by the platform
    }
```

Java:

```java
try (var client = ConnectivitizerClient.builder()
        .apiKey(System.getenv("CZ_API_KEY"))
        .sharedKey(System.getenv("CZ_SHARED_KEY"))
        .build()) {
    var session = client.connectBlocking("living-room-lamp", List.of("api"));
    var response = session.fetchBlocking("api", "/state");
    System.out.println(response.getStatus() + " " + response.text());
    System.out.println(session.getInfo().getMode());
}
```

| | |
|---|---|
| `client.connect(device, services)` | Kotlin (suspend); from Java `connectBlocking` or `connectAsync` (a `CompletableFuture`). |
| `client.listDevices()` | The devices this program may reach: name, alias, online, and the services it may use (`listDevicesBlocking` from Java). |
| `session.fetch(service, path, method, headers, body)` | An HTTP request: `status`, `headers`, `text()`, `bytes()`, `chunks()` (a `Flow`). From Java `fetchBlocking`. |
| `session.webSocket(service, path)` | A WebSocket: `send(...)`, `receive()` (null once closed). |
| `session.openStream(service)` | The raw byte stream, for any other TCP protocol. |
| `session.info` | `mode`, `transport`, `endToEndEncrypted`, `trust`, `peerAddress`, `directFailureReason`. |

Errors are `ConnectivitizerException` (unchecked; from Java `catch (ConnectivitizerException e)` and `e.getCode()`) with a stable `code`: see [Error codes](https://connectivitizer.com/guides/errors.md). On Android, call the blocking methods off the main thread (or use the suspend functions from a coroutine).

## Linking an app instead of giving it a key

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

```kotlin
val linked = Link.linkApp("Lamp app", { prompt ->
    // open prompt.url in a browser (Android: an Intent with ACTION_VIEW); the person signs in on https://connectivitizer.com and approves
})
// linked.apiKey is returned this once: keep it in the keystore and pass it to apiKey(...) from then on
```

From Java: `Link.linkAppBlocking("Lamp app", prompt -> ...)`. It throws `LINK_DENIED` when the person refused and `LINK_EXPIRED` after ten minutes. The linked app is listed, and revoked, under *Credentials*.

## Device side

```kotlin
val agent = ConnectivitizerAgent.builder()
    .deviceKey(System.getenv("CZ_DEVICE_KEY"))   // from the workspace
    .name("nas")                                 // how apps address this device; it stays the same
    .sharedKey(System.getenv("CZ_SHARED_KEY"))
    .service("api", "127.0.0.1:8080")            // nothing else is reachable
    .log { println(it) }
    .build()
agent.run()   // reconnects by itself; stop with agent.stop(). From Java: runBlocking() and stopBlocking()
```

The device appears under *Devices* the first time it connects. `run()` throws 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`.

Kotlin:

```kotlin
val agent = ConnectivitizerAgent.builder()
    .deviceKey(System.getenv("CZ_DEVICE_KEY"))   // a device key that may open sessions
    .name("hall-panel")
    .sharedKey(System.getenv("CZ_SHARED_KEY"))   // the same key the other device has
    .service("api", "127.0.0.1:8080")
    .log { println(it) }
    .build()

coroutineScope {
    val running = launch { agent.run() }

    val session = agent.connect("living-room-lamp", listOf("api"))   // waits until the device is connected
    val response = session.fetch("api", "/state")
    println("${response.status} ${response.text()} ${session.info.mode}")

    running.join()
}
```

Java:

```java
var agent = ConnectivitizerAgent.builder()
        .deviceKey(System.getenv("CZ_DEVICE_KEY"))
        .name("hall-panel")
        .sharedKey(System.getenv("CZ_SHARED_KEY"))
        .service("api", "127.0.0.1:8080")
        .log(System.out::println)
        .build();
new Thread(agent::runBlocking).start();

var session = agent.connectBlocking("living-room-lamp", List.of("api"));   // waits until the device is connected
var response = session.fetchBlocking("api", "/state");
System.out.println(response.getStatus() + " " + response.text() + " " + session.getInfo().getMode());
```

| | |
|---|---|
| `agent.connect(device, services)` | Opens a session to another device by its name (suspend); from Java `connectBlocking` or `connectAsync` (a `CompletableFuture`). The session offers what the calling side's session offers. |
| `agent.listDevices()` | The devices this device may reach, without itself: name, alias, online, and the services it may use (`listDevicesBlocking` from Java). |
| `agent.outgoingSessions` | 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 library finds the machine's addresses (IPv4 and IPv6, VPN interfaces skipped), binds UDP and punches through the routers. Whether a session is direct depends on the networks: [Troubleshooting](https://connectivitizer.com/guides/troubleshooting.md).
- The library runs its protocol work on a thread of its own and its socket reads on the IO pool; it can be called from any thread.
- Certificates and pairing are not available in this library; 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` in the working directory. It listens on `127.0.0.1:8080`, which the device side above exposes as `api` (`.service("api", "127.0.0.1:8080")`).

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

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).
