Device node: a device's ports are wired in flows

- flow/nodes/device.py: `device` node with params `device` and `config`;
  provides the device's `in` ports, requires its `out` ports without
  waking anything, never run (Node.passive), down "Offline" from presence
- DeviceDef.io and DevicePort go; GET /devices/{id} computes `io` and
  `bindings` from the device nodes of published flows, in a fixed order,
  cached by FlowStore.revision; the credential's scope comes from them
- issues `unknown_device` and `device_port` (wired twice; against a report
  the wrong direction or dtype, or unlisted as advisory), rechecked when a
  device is created or deleted; ValidationIssue.advisory is a field
- a device publishing on a bound port is credited to its node by the
  server; the panel endpoint kind is gone from `_endpoints` and the canvas
- a rebuild that moves a device's bindings sends `dashboard_changed` with
  an empty name, which the firmware refetches on
- startup moves each device's `io` rows into device nodes in the flows
  declaring their messages, draft and published, one commit; rows no
  flow declares are logged and left out
- frontend: Device node settings (device, Publishes, Follows, a port
  picker from a report), palette shortcuts per reported port, DeviceDetail
  lists bindings with "Use in flow" in place of the I/O editor
- docs: devices, flow editor, node types, issues, API

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Melvin Strobl
2026-10-16 16:40:31 +02:00
co-authored by Claude Opus 5.5
parent 3ba407eec6
commit f8011d2a8a
35 changed files with 2195 additions and 494 deletions
+123 -194
View File
@@ -1,26 +1,23 @@
import { useQuery } from "@tanstack/react-query"
import { Link } from "@tanstack/react-router"
import { ArrowDown, ArrowUp, Plus, X } from "lucide-react"
import { useMutation, useQuery } from "@tanstack/react-query"
import { Link, useNavigate } from "@tanstack/react-router"
import { ArrowDown, ArrowLeft, ArrowRight, ArrowUp, X } from "lucide-react"
import { useState } from "react"
import {
type ApiError,
CloudService,
type DeviceDef,
type DevicePort,
type DevicePublic,
DevicesService,
FlowsService,
} from "@/client"
import { initials, resolveIcon } from "@/components/Dashboard/icons"
import { MessagePicker } from "@/components/Dashboard/panels"
import { dashboardsQueryOptions } from "@/components/Dashboard/queries"
import { qualifiedProblem } from "@/components/Flow/deriveEdges"
import { JsonField } from "@/components/Flow/JsonField"
import { flowsQueryOptions } from "@/components/Flow/queries"
import { InfoTip, PanelSection } from "@/components/Flow/SidePanel"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Segmented } from "@/components/ui/segmented"
import {
Select,
SelectContent,
@@ -34,6 +31,13 @@ import useAuth from "@/hooks/useAuth"
import useCustomToast from "@/hooks/useCustomToast"
import { ago, cn } from "@/lib/utils"
import { handleError } from "@/utils"
import {
DEVICE_TYPE,
deviceNodeOf,
freeNodeId,
type ReportedPort,
withPort,
} from "./ports"
import {
devicesQueryOptions,
pendingQueryOptions,
@@ -47,28 +51,6 @@ const CARD = "rounded-lg border border-border bg-card p-4 shadow-e1"
/** As many characters as a device puts on the wall. */
const CODE_LENGTH = 6
/** Port names the panel firmware knows; `gpio.` takes a pin number. */
// ponytail: free-text ports until a device reports what it has (PUT /devices/{id}/report)
const PORT_SUGGESTIONS = ["gpio.", "backlight", "touch", "mic", "speaker"]
const DIRECTIONS = [
["in", "In"],
["out", "Out"],
] as const
/** What the server accepts as a port name. */
const portOf = (value: string) =>
value.toLowerCase().replace(/[^a-z0-9_.]/g, "")
/** A new port the server will take: a name, and a message named with its flow. */
const ready = (port: DevicePort) =>
Boolean(port.port) && qualifiedProblem(port.message) === null
const objectOnly = (value: unknown) =>
value && typeof value === "object" && !Array.isArray(value)
? null
: "Config is a JSON object"
/** "Online", or when it was last heard from. */
export function presenceText(device: DevicePublic) {
if (device.online) return "Online"
@@ -159,7 +141,7 @@ export function DeviceDetail({ id }: { id: string }) {
/>
</section>
<section className={CARD}>
<DeviceIo device={device} canEdit={canEdit} onChange={write} />
<DevicePorts device={device} canEdit={canEdit} />
</section>
</div>
</div>
@@ -564,184 +546,131 @@ function Pairing({
}
/**
* The device's own inputs and outputs, each wired to a message.
*
* A new port is held here until it has a name and a qualified message, since
* the server refuses a port without either.
* The device's own ports as the published flows wire them: each one, the
* message it publishes or follows, and a link to the node holding it.
* Wiring is done in a flow, so this only reads.
*/
function DeviceIo({
function DevicePorts({
device,
canEdit,
onChange,
}: {
device: DeviceDef
device: DevicePublic
canEdit: boolean
onChange: (changes: Partial<DeviceDef>) => void
}) {
const [draft, setDraft] = useState<DevicePort | null>(null)
const io = device.io ?? []
const listId = `ports-${device.id}`
const write = (io: DevicePort[]) => onChange({ io })
const keepDraft = (next: DevicePort) => {
if (!ready(next)) return setDraft(next)
setDraft(null)
write([...io, next])
}
const bindings = device.bindings ?? []
return (
<PanelSection
title="I/O"
help="Hardware on the device itself, such as a GPIO pin or its microphone. In publishes to the message, Out follows it, and Config goes to the device as it is."
title="Ports"
help="Hardware on the device itself, such as a GPIO pin or its backlight. A device node in a flow wires each port to a message."
>
<datalist id={listId}>
{PORT_SUGGESTIONS.map((port) => (
<option key={port} value={port} />
))}
</datalist>
{/* `disabled` on a fieldset reaches every control inside it. */}
<fieldset disabled={!canEdit} className="grid min-w-0 gap-4">
{io.length === 0 && !draft ? (
<p className="text-sm text-muted-foreground">No ports yet.</p>
) : null}
{io.map((row, index) => (
<IoRow
// Ports have no id, and two may share a name until one is renamed.
key={index}
row={row}
listId={listId}
testId={`io-${device.id}-${index}`}
onChange={(next) =>
write(io.map((one, at) => (at === index ? next : one)))
}
onRemove={() => write(io.filter((_, at) => at !== index))}
/>
))}
{draft ? (
<IoRow
row={draft}
listId={listId}
testId={`io-${device.id}-new`}
onChange={keepDraft}
onType={(port) => setDraft({ ...draft, port })}
onRemove={() => setDraft(null)}
/>
) : null}
{canEdit && !draft ? (
<Button
variant="outline"
size="sm-touch"
className="justify-self-start"
data-testid={`add-port-${device.id}`}
onClick={() => setDraft({ port: "", message: "", direction: "in" })}
>
<Plus />
Add port
</Button>
) : null}
</fieldset>
{bindings.length === 0 ? (
<p className="text-sm text-muted-foreground">No ports wired yet.</p>
) : (
<ul className="grid gap-1" data-testid="device-bindings">
{bindings.map((binding) => {
const Way = binding.direction === "in" ? ArrowRight : ArrowLeft
const way = binding.direction === "in" ? "Publishes" : "Follows"
return (
<li
key={`${binding.flow}.${binding.node}.${binding.port}.${binding.message}`}
className="flex min-w-0 items-center gap-2 text-sm"
>
<span className="w-24 shrink-0 truncate font-mono">
{binding.port}
</span>
<Way
role="img"
aria-label={way}
className="size-4 shrink-0 text-muted-foreground"
/>
<Link
to="/flows/$flowName"
params={{ flowName: binding.flow }}
search={{ node: binding.node }}
className="min-w-0 flex-1 truncate font-mono hover:underline"
>
{binding.message}
</Link>
</li>
)
})}
</ul>
)}
{canEdit ? <UseInFlow device={device} /> : null}
</PanelSection>
)
}
function IoRow({
row,
listId,
testId,
onChange,
onType,
onRemove,
/**
* Put this device in a flow: its device node there, made when there is none,
* with `port` on it when one is given, and the flow opened on it. A draft,
* so nothing is wired until the flow is published.
*/
export function UseInFlow({
device,
port,
}: {
row: DevicePort
/** The datalist of port names to suggest. */
listId: string
testId: string
onChange: (next: DevicePort) => void
/** A new port's name as it is typed. A saved port commits on blur instead. */
onType?: (port: string) => void
onRemove: () => void
device: DevicePublic
port?: ReportedPort
}) {
const name = row.port || "new port"
const problem = row.message ? qualifiedProblem(row.message) : null
const navigate = useNavigate()
const { showErrorToast } = useCustomToast()
const { data } = useQuery(flowsQueryOptions())
const flows = data?.data ?? []
const place = useMutation({
mutationFn: async (flowName: string) => {
const { definition } = await FlowsService.readFlow({ name: flowName })
const nodes = definition.nodes ?? []
const existing = deviceNodeOf(nodes, device.id)
const node = existing ?? {
id: freeNodeId(nodes, device.id),
type: DEVICE_TYPE,
title: device.title || device.id,
params: { device: device.id, config: {} },
requires: [],
provides: [],
}
const placed = port ? withPort(node, port) : node
if (placed !== existing) {
await FlowsService.saveFlow({
name: flowName,
requestBody: {
...definition,
nodes: existing
? nodes.map((one) => (one === existing ? placed : one))
: [...nodes, placed],
},
})
}
return { flowName, node: placed.id }
},
onSuccess: ({ flowName, node }) =>
navigate({
to: "/flows/$flowName",
params: { flowName },
search: { node },
}),
onError: (error) => handleError.call(showErrorToast, error as ApiError),
})
if (flows.length === 0) return null
return (
<div className="grid gap-2" data-testid={testId}>
<div className="flex items-center gap-2">
{onType ? (
<Input
value={row.port}
placeholder="Port, e.g. gpio.4"
aria-label={`Port of ${name}`}
autoComplete="off"
list={listId}
onChange={(event) => onType(portOf(event.currentTarget.value))}
onBlur={() => onChange(row)}
/>
) : (
<Input
// Remounted with whatever was saved, so a refused name snaps back.
key={row.port}
defaultValue={row.port}
placeholder="Port, e.g. gpio.4"
aria-label={`Port of ${name}`}
autoComplete="off"
list={listId}
onBlur={(event) => {
const port = portOf(event.currentTarget.value)
event.currentTarget.value = port || row.port
if (port && port !== row.port) onChange({ ...row, port })
}}
/>
)}
<div className="shrink-0">
<Segmented
value={row.direction}
options={DIRECTIONS}
label={`Direction of ${name}`}
onChange={(direction) =>
onChange({
...row,
direction: direction as DevicePort["direction"],
})
}
/>
</div>
<Button
variant="ghost"
size="icon-touch"
className="shrink-0 text-muted-foreground"
aria-label={`Remove ${name}`}
title={`Remove ${name}`}
onClick={onRemove}
>
<X />
</Button>
</div>
<div className="flex items-center gap-2">
<div className="min-w-0 flex-1">
<MessagePicker
value={row.message}
label={`Message of ${name}`}
hideLabel
// A port the device publishes from needs a message a flow takes in.
filter={
row.direction === "in"
? (message) => message.writable !== false
: undefined
}
onPick={(message) => onChange({ ...row, message })}
/>
</div>
<JsonField
value={row.config ?? {}}
label={`Config of ${name}`}
check={objectOnly}
className="h-9 w-28 shrink-0"
onChange={(config) =>
onChange({ ...row, config: config as DevicePort["config"] })
}
/>
</div>
{problem ? <p className="text-xs text-destructive">{problem}</p> : null}
</div>
<Select value="" onValueChange={(flowName) => place.mutate(flowName)}>
<SelectTrigger
className="justify-self-start"
aria-label={`Use ${device.title || device.id} in a flow`}
disabled={place.isPending}
data-testid="use-in-flow"
>
<SelectValue placeholder="Use in flow" />
</SelectTrigger>
<SelectContent>
{flows.map((flow) => (
<SelectItem key={flow.name} value={flow.name}>
{flow.title || flow.name}
</SelectItem>
))}
</SelectContent>
</Select>
)
}
+79
View File
@@ -0,0 +1,79 @@
import type { DevicePublic, DType, MessageSpec, NodeDef_Input } from "@/client"
/** The node type a device is in a flow. */
export const DEVICE_TYPE = "device"
/** Port names the panel firmware knows; `gpio.` takes a pin number. */
// ponytail: free-text ports until a device reports what it has (D2, PUT /devices/{id}/report)
export const PORT_SUGGESTIONS = [
"gpio.",
"backlight",
"touch",
"mic",
"speaker",
]
/** One port as a device reports it. */
export type ReportedPort = {
port: string
direction: "in" | "out"
dtype?: DType
}
/** What the server accepts as a port name. */
export const portOf = (value: string) =>
value.toLowerCase().replace(/[^a-z0-9_.]/g, "")
/**
* The ports a device says it has, or null when it has not said.
*
* Read leniently: the report is the device's own word, and without one ports
* are free text.
*/
export function reportedPorts(device: DevicePublic | undefined) {
const ports = (device?.report as { ports?: unknown } | null | undefined)
?.ports
if (!Array.isArray(ports)) return null
return ports.filter(
(port): port is ReportedPort =>
typeof port?.port === "string" &&
(port.direction === "in" || port.direction === "out"),
)
}
/** The device node standing for `device` in a flow, if there is one. */
export function deviceNodeOf(nodes: NodeDef_Input[], device: string) {
return nodes.find(
(node) => node.type === DEVICE_TYPE && node.params?.device === device,
)
}
/**
* The node with one more port: an `in` port publishes, so it is an output,
* and an `out` port follows, so it is an input that never wakes anything.
* The message is named after the port until somebody names it.
*/
export function withPort(node: NodeDef_Input, port: ReportedPort) {
const spec: MessageSpec = {
name: port.port.replace(/\./g, "_"),
port: port.port,
dtype: port.dtype ?? "float",
}
if (port.direction === "in") {
if ((node.provides ?? []).some((one) => one.port === port.port)) return node
return { ...node, provides: [...(node.provides ?? []), spec] }
}
if ((node.requires ?? []).some((one) => one.port === port.port)) return node
return {
...node,
requires: [...(node.requires ?? []), { ...spec, trigger: false }],
}
}
/** A node id the flow does not have yet, `base` itself when it is free. */
export function freeNodeId(nodes: NodeDef_Input[], base: string) {
const taken = new Set(nodes.map((node) => node.id))
let id = base
for (let index = 2; taken.has(id); index += 1) id = `${base}_${index}`
return id
}
+10 -2
View File
@@ -69,8 +69,16 @@ export function useSaveDevice(id: string) {
mutationFn: (changes: Partial<DeviceDef>) => {
const current = stored()
if (!current) throw new Error(`No device named ${id}`)
// Presence is the list's, not part of what is saved.
const { online: _online, last_seen: _seen, ...device } = current
// Presence, the report and the wiring are the list's, not part of what
// is saved: the ports are wired in flows.
const {
online: _online,
last_seen: _seen,
report: _report,
io: _io,
bindings: _bindings,
...device
} = current
return DevicesService.saveDevice({
deviceId: id,
requestBody: { ...device, ...changes },