Skip to content

Devices on a LAN

A plug, a light or a camera on a LAN does not send uplinks: it is asked. Its codec turns each command into requests (HTTP, TCP, UDP) that the caller makes against the device’s address, and is called again with each answer until it says the command is done or failed.

function encodeDownlink(input) {
var ip = input.ip;
// ip.command the command, e.g. 'switch.on'
// ip.params its parameters
// ip.device {address, name, credentials?}
// ip.results the answers so far, one per request, in order
// ip.memo what the codec kept for this device
var r = (ip.results || [])[0];
if (!r) return { data: { status: 'pending', intents: [
{ op: 'ip.http', method: 'GET', path: '/api/relay', port: 80 } ] } };
if (!r.ok) return { data: { status: 'failed', reason: 'undeliverable', error: r.error } };
return { data: { status: 'done', data: JSON.parse(r.body) } };
}
  1. The caller calls encodeDownlink with the command and no results.
  2. The codec answers pending with the next request (intents[0]).
  3. The caller makes it and calls again from the start, with the answer appended to results.
  4. The codec walks its steps again, finds each answered, and either asks the next or answers done (with data) or failed (with reason and error).

Replaying from the start keeps the codec free of state between calls: what it does is a function of the command and the answers. The examples/http-plug package in the repository is a complete one.

op Fields Answer
ip.http address? port, method, path, headers, body or body_b64, timeout_ms, max_bytes {ok, status, headers, body} (body_b64 for an answer that is not text)
ip.tcp port, send_b64, until_b64 (read until these bytes), timeout_ms, max_bytes {ok, b64}
ip.udp port, send_b64, response (wait for one), timeout_ms, max_bytes {ok, b64}

The caller sends every request to the device’s own address, whatever the codec says, and only on the LAN; label names a step in logs. A request that could not be made answers {ok: false, error}.

A caller may make other kinds. Pulzr makes cloud.https requests to a vendor’s cloud for a device’s key, only to the hosts the package lists in device.json cloud.hosts; an answer still pending may carry show (a QR or text for the person waiting), and a done answer may carry login ({username, password}), which becomes the device’s credentials.

status With
pending intents: [request], show? Make the request and call again
Done data What the command answers
failed reason, error invalid (bad parameters), unknown (no such command), undeliverable (the device did not answer), busy, error

The top-level memo (beside data) replaces what the caller keeps for the device: a protocol variant learned on the first command, a session. Keep secrets out of data and memo; the device’s login comes in as device.credentials.

A device that pushes events (a camera’s motion stream, a broadcast) is decoded by decodeUplink({ip: {event: {b64, ts}, device, memo}}), which answers readings in data.