Docs

C# / .NET: calling side and device side

The NuGet package Huelake.Connectivitizer.Client (.NET 10) connects an application to a service on a device (calling side) with an ordinary HttpClient, or hosts the device agent inside an application (device side). It supports both ways of trusting: a shared key and certificates with pairing.

Install

From nuget.org:

Bash
dotnet add package Huelake.Connectivitizer.Client

What you need

Decide first whether your application 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. It is shown once.
  • 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. If you prefer certificates, a one-time enrollment token (cze_…; web app: Devices → Enroll a device) instead of the device key.
  • 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 on both sides. It is generated in your browser and never reaches Connectivitizer. With certificates and pairing (below) you do not need it.
  • Device side: a folder for the state directory (keys, trust and settings). Choose one that survives updates and that only your application can read.

Keep the keys in user secrets, environment variables or a secret store, never in a committed appsettings.json.

Calling side, with a shared key

C#
using Huelake.Connectivitizer.Client;
using Huelake.Connectivitizer.Client.Security;

await using var client = new ConnectivitizerClient(new ConnectivitizerClientOptions
{
    ApiKey = configuration["Connectivitizer:ApiKey"],
    SharedKeys = [SharedKey.Parse(configuration["Connectivitizer:SharedKey"]!)],
});

await using var session = await client.ConnectAsync("living-room-lamp", ["api"]);   // device name, services
using var http = new HttpClient(session.CreateHttpHandler("api")) { BaseAddress = new Uri("http://api") };
Console.WriteLine(await http.GetStringAsync("/state"));

Console.WriteLine(session.Info.Mode);                 // direct | e2e-relay
Console.WriteLine(session.Info.EndToEndEncrypted);    // verified by this endpoint
Console.WriteLine(session.Info.DirectFailureReason);  // why not direct, if relayed

HttpClient and ClientWebSocket work unchanged through the handler. Create one HttpClient per session.

Device side, with a device key and a shared key

C#
using Huelake.Connectivitizer.Client;
using Huelake.Connectivitizer.Client.Security;
using Huelake.Connectivitizer.Client.State;

var state = new StateDirectory("<data folder>");   // keys, trust and settings of this installation

if (state.LoadDevice() is null)                     // first start only
{
    await AgentHost.LoginWithDeviceKeyAsync(state, deviceKey, "home-pc");
}
state.SaveSharedKeys([SharedKey.Parse(sharedKey)]);
state.SaveServices([new ServiceEntry { Name = "api", Target = "127.0.0.1:8080", Protocol = "http" }]);

await using ConnectivitizerAgent agent = AgentHost.Create(state, message => logger.LogInformation("{Message}", message));
await agent.RunAsync(stoppingToken);                // for as long as the application runs

Only the services in SaveServices are reachable. The device appears under Devices the first time it connects.

A device that calls another device

A device opens a session to another device over the connection to the platform it already has. It needs no API key: the device key it logs in with must have Its devices may open sessions to other devices switched on (web app: Credentials, when you create or edit the key), and the key's access rules must cover the other device.

C#
using Huelake.Connectivitizer.Client.Sessions;

await agent.WaitUntilConnectedAsync(stoppingToken);
await using TunnelSession session = await agent.ConnectAsync("cabin", ["api"], stoppingToken);
using var http = new HttpClient(session.CreateHttpHandler("api")) { BaseAddress = new Uri("http://api") };
string answer = await http.GetStringAsync("/state", stoppingToken);

The shared key is chosen as on the calling side: the one named like the other device, else the only one, else the one named default. agent.ListDevicesAsync() answers the devices the key may reach, and agent.OutgoingSessions the sessions the device has open to others. Without the right on the key the platform answers FORBIDDEN. A device that was enrolled with a token has no device key and cannot open sessions.

Certificates and pairing instead of a shared key

With certificates each endpoint has an identity of its own, and the two pin each other once ("pairing"); each endpoint then knows exactly which endpoint it talks to. The device enrolls with the one-time enrollment token instead of logging in with a device key:

C#
await AgentHost.EnrollAsync(state, "cze_…", "home-pc");

Pairing takes three steps with two strings, which you carry between the two sides however you like (copy and paste, a QR code):

C#
using Huelake.Connectivitizer.Client.Identity;

// 1. device
using EndpointIdentity identity = state.LoadIdentity();
string invitation = Pairing.CreateInvitation(state, identity, "home-pc");

// 2. calling application: creates its identity on first use, pins the device, answers
var appState = new StateDirectory("<app data folder>");
using EndpointIdentity appIdentity = appState.LoadOrCreateIdentity("my-app");
TrustStore trust = appState.OpenTrustStore();
(string response, _) = Pairing.Accept(invitation, appIdentity, "my-app", trust);

// 3. device: verifies the response, pins the application
Pairing.Complete(response, state, identity, state.OpenTrustStore());

The client then passes Identity = appIdentity, Trust = trust in its options instead of SharedKeys. cz pair create / accept / complete produce the same strings, so one side can be cz.

Good to know

  • Direct sessions need nothing from your code: the library finds the machine's addresses, binds UDP and punches through the routers. It can also connect directly over TCP when one side has a forwarded port (TcpListenPort, PublicTcpEndpoints). Whether a session is direct depends on the networks: Troubleshooting.
  • Errors carry a stable code in ErrorCode (PlatformException, TunnelException): see Error codes.

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


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


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


<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, the Target of the service api on the device side above.

C#
// 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"

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.