A logic analyzer: watch wires, cables and pins over time (right-click: Watch in analyzer), saved with the circuit

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
This commit is contained in:
Fabian @ Blax Software 2026-10-28 12:36:30 +01:00
parent 652b048dbc
commit 33318d84ca
11 changed files with 465 additions and 1 deletions

View File

@ -5689,3 +5689,115 @@ button.tile:hover {
.face-thing.nested:not(.sel) { .face-thing.nested:not(.sel) {
stroke-dasharray: 3 2; stroke-dasharray: 3 2;
} }
/* Logic analyzer: above the bottom bar, as wide as it. */
.analyzer {
position: absolute;
left: var(--bar-x);
width: var(--bar-w);
bottom: 76px;
z-index: 19;
display: flex;
flex-direction: column;
max-height: 40vh;
background: rgb(19 24 31 / 0.97);
border: 1px solid var(--border);
border-radius: 12px;
box-shadow: 0 10px 30px rgb(0 0 0 / 0.4);
font-size: 12px;
}
.analyzer-head {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px 6px 12px;
border-bottom: 1px solid var(--border);
}
.analyzer-empty {
padding: 12px;
}
.analyzer-body {
display: flex;
overflow-y: auto;
min-height: 0;
}
.analyzer-names {
flex: none;
border-right: 1px solid var(--border);
}
.analyzer-names li {
display: flex;
align-items: center;
gap: 6px;
padding: 0 4px 0 12px;
border-bottom: 1px solid rgb(37 46 58 / 0.5);
}
.analyzer-names li > .truncate {
flex: 1;
min-width: 0;
}
.analyzer-val {
color: var(--on);
font-family: var(--font-mono);
font-size: 11px;
}
.analyzer-wave {
position: relative;
flex: 1;
min-width: 0;
overflow: hidden;
cursor: crosshair;
}
.analyzer-wave svg {
display: block;
}
.analyzer-bit {
fill: none;
stroke: var(--on);
stroke-width: 1.5;
}
.analyzer-bus {
fill: var(--on-dim);
stroke: var(--on);
stroke-width: 1;
}
.analyzer-bus-text {
fill: var(--text);
font-family: var(--font-mono);
font-size: 10px;
}
.analyzer-mark {
stroke: var(--border);
stroke-width: 1;
}
.analyzer-cursor {
stroke: var(--accent);
stroke-width: 1;
}
.analyzer-cycle {
position: absolute;
right: 6px;
top: 2px;
color: var(--muted);
font-size: 10px;
pointer-events: none;
}
.analyzer-head .hint {
margin: 0;
}

View File

@ -0,0 +1,145 @@
<script setup lang="ts">
// The logic analyzer: the watched signals of the open circuit over time, a
// lane each. A wire is a square wave, a cable a bus with its value. One
// step per clock half-cycle while the clock runs, and one for every other
// change. Point at the waves to read every value at that moment; the wheel
// scrolls back through time.
import { probeBits, probeName } from '~/lib/logic/probes'
const ed = useEditor()
const def = ed.def
const probes = computed(() => def.value.probes ?? [])
const CELL = 10 // pixels per sample
const NAME_W = 150
const LANE_H = 26
const wave = ref<HTMLElement>()
const width = ref(600)
let ro: ResizeObserver | undefined
onMounted(() => {
ro = new ResizeObserver(() => (width.value = wave.value?.clientWidth ?? 600))
if (wave.value) ro.observe(wave.value)
})
onBeforeUnmount(() => ro?.disconnect())
// The trace grows in place: a new object each time, so what reads it follows.
const samples = computed(() => ({ v: ed.traceVersion.value, list: ed.trace.value }))
const total = computed(() => samples.value.list.length)
/** How far back from the newest sample the view is (0: following the newest). */
const back = ref(0)
const count = computed(() => Math.max(1, Math.floor(width.value / CELL)))
const view = computed(() => {
const all = samples.value.list
const end = Math.max(0, all.length - back.value)
const start = Math.max(0, end - count.value)
return { start, list: all.slice(start, end) }
})
function onWheel(e: WheelEvent) {
const step = Math.round((Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY) / 20) || Math.sign(e.deltaY)
back.value = Math.max(0, Math.min(Math.max(0, total.value - count.value), back.value + step))
}
/** The sample pointed at (in the view), else the newest. */
const at = ref<number | null>(null)
function onMove(e: PointerEvent) {
const r = wave.value!.getBoundingClientRect()
const i = Math.floor((e.clientX - r.left) / CELL)
at.value = i >= 0 && i < view.value.list.length ? i : null
}
const shown = computed(() => view.value.list[at.value ?? view.value.list.length - 1])
const bits = (i: number) => probeBits(def.value, probes.value[i]!)
const hexOf = (v: number, b: number) => (b === 1 ? String(v) : `0x${v.toString(16).toUpperCase().padStart(Math.ceil(b / 4), '0')}`)
const valueText = (i: number) => {
const s = shown.value
if (!s) return '–'
const v = s.vals[i] ?? 0
const b = bits(i)
return b === 1 ? String(v) : `${v} · ${hexOf(v, b)}`
}
/** A wire's square wave. */
function square(i: number): string {
const top = 5
const low = LANE_H - 5
let d = ''
view.value.list.forEach((s, k) => {
const y = s.vals[i] ? top : low
d += k ? `L${k * CELL} ${y}H${(k + 1) * CELL}` : `M0 ${y}H${CELL}`
})
return d
}
/** A cable's runs of one value: a long hexagon each, named by its value when there is room. */
function runs(i: number): { x: number; w: number; v: number }[] {
const out: { x: number; w: number; v: number }[] = []
view.value.list.forEach((s, k) => {
const v = s.vals[i] ?? 0
const last = out[out.length - 1]
if (last && last.v === v) last.w += CELL
else out.push({ x: k * CELL, w: CELL, v })
})
return out
}
const hexagon = (r: { x: number; w: number }) => {
const m = Math.min(3, r.w / 3)
const t = 5
const b = LANE_H - 5
const c = LANE_H / 2
return `M${r.x} ${c}L${r.x + m} ${t}H${r.x + r.w - m}L${r.x + r.w} ${c}L${r.x + r.w - m} ${b}H${r.x + m}Z`
}
/** Clock steps: where a new clock cycle began, numbered now and then. */
const marks = computed(() => {
const out: { x: number; n?: number }[] = []
view.value.list.forEach((s, k) => {
const prev = view.value.list[k - 1]
if (prev && s.cycle !== prev.cycle) out.push({ x: k * CELL, ...(s.cycle % 5 === 0 ? { n: s.cycle } : {}) })
})
return out
})
const name = (i: number) => probeName(def.value, probes.value[i]!, ed.getDef.value)
</script>
<template>
<section class="analyzer" aria-label="Logic analyzer">
<header class="analyzer-head">
<Icon name="lucide:activity" class="size-4 text-(--accent)" />
<span class="font-semibold">Logic analyzer</span>
<span class="hint">{{ total }} {{ total === 1 ? 'step' : 'steps' }}<template v-if="back"> · {{ back }} back</template></span>
<button v-if="back" class="btn-sm" title="Follow the newest again" @click="back = 0"><Icon name="lucide:chevrons-right" class="size-3.5" /> Now</button>
<span class="grow" />
<button class="icon-btn" title="Start over" :disabled="!total" @click="ed.clearTrace()"><Icon name="lucide:eraser" class="size-4" /></button>
<button class="icon-btn" title="Close (the signals stay watched)" @click="ed.analyzerOpen.value = false"><Icon name="lucide:x" class="size-4" /></button>
</header>
<p v-if="!probes.length" class="hint analyzer-empty">
Right-click a wire, a cable or a pin and choose <strong>Watch in analyzer</strong>. Then run the clock, step it, or flip switches.
</p>
<div v-else class="analyzer-body">
<ul class="analyzer-names" :style="{ width: `${NAME_W}px` }">
<li v-for="(p, i) in probes" :key="`${p.node}:${p.pin}`" :style="{ height: `${LANE_H}px` }">
<span class="truncate" :title="name(i)">{{ name(i) }}</span>
<span class="analyzer-val tabular-nums">{{ valueText(i) }}</span>
<button class="icon-btn" title="Stop watching" @click="ed.unwatch(i)"><Icon name="lucide:x" class="size-3" /></button>
</li>
</ul>
<div ref="wave" class="analyzer-wave" @wheel.prevent="onWheel" @pointermove="onMove" @pointerleave="at = null">
<svg :width="view.list.length * CELL" :height="probes.length * LANE_H">
<line v-for="(m, k) in marks" :key="`m${k}`" :x1="m.x" :x2="m.x" y1="0" :y2="probes.length * LANE_H" class="analyzer-mark" />
<g v-for="(p, i) in probes" :key="`${p.node}:${p.pin}`" :transform="`translate(0 ${i * LANE_H})`">
<path v-if="bits(i) === 1" :d="square(i)" class="analyzer-bit" />
<template v-else>
<template v-for="(r, k) in runs(i)" :key="k">
<path :d="hexagon(r)" class="analyzer-bus" />
<text v-if="r.w >= 26" :x="r.x + r.w / 2" :y="LANE_H / 2 + 3.5" text-anchor="middle" class="analyzer-bus-text">{{ hexOf(r.v, bits(i)) }}</text>
</template>
</template>
</g>
<line v-if="at !== null" :x1="at * CELL + CELL / 2" :x2="at * CELL + CELL / 2" y1="0" :y2="probes.length * LANE_H" class="analyzer-cursor" />
</svg>
<span v-if="shown" class="analyzer-cycle tabular-nums">tick {{ shown.cycle }}</span>
</div>
</div>
</section>
</template>

View File

@ -45,6 +45,7 @@ watch(
</main> </main>
<EditorSelectionPanel v-if="hasSelection" /> <EditorSelectionPanel v-if="hasSelection" />
<EditorToolbar /> <EditorToolbar />
<EditorAnalyzer v-if="ed.analyzerOpen.value" />
<EditorBottomBar /> <EditorBottomBar />
</div> </div>
</template> </template>

View File

@ -10,6 +10,7 @@ import { dropLinks, dropPins, fitStart, type DropPin } from '~/lib/logic/fit'
import type { CanvasOps, MenuEntry } from '~/composables/useMenu' import type { CanvasOps, MenuEntry } from '~/composables/useMenu'
import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables' import { cableInUse, LANE, plugLayout, ribbon, RIBBON_MAX } from '~/lib/logic/cables'
import { latchLayout, latchSeam } from '~/lib/logic/latch' import { latchLayout, latchSeam } from '~/lib/logic/latch'
import { probeAt } from '~/lib/logic/probes'
import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move' import { moveParts, moveStart, type MoveStart } from '~/lib/logic/move'
import { wirePath, type HopSpan } from '~/lib/draw' import { wirePath, type HopSpan } from '~/lib/draw'
import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet' import { downloadSheet, printSheet, sheetSvg } from '~/lib/sheet'
@ -1670,6 +1671,8 @@ function openMenuAt(target: Element, at: Pt, x: number, y: number) {
const pull = endActions(n).find(x => x.key === 'pull') const pull = endActions(n).find(x => x.key === 'pull')
if (pull) here.push({ label: 'Pull the cable out', icon: pull.icon, run: () => pull.run(new PointerEvent('pointerdown')) }) if (pull) here.push({ label: 'Pull the cable out', icon: pull.icon, run: () => pull.run(new PointerEvent('pointerdown')) })
} }
const probe = p && !p.port ? probeAt(def.value, n, pin, dir, ed.getDef.value) : null
if (probe) here.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => ed.watchSignal(probe) })
if (dir === 'in' && ed.canInvert(n, pin)) { if (dir === 'in' && ed.canInvert(n, pin)) {
const on = n.invert?.includes(pin) const on = n.invert?.includes(pin)
here.push({ label: on ? 'Take the bubble off this input' : 'Invert this input', icon: 'lucide:circle-dot', keys: 'Alt+click', run: () => ed.toggleInvert(n, pin) }) here.push({ label: on ? 'Take the bubble off this input' : 'Invert this input', icon: 'lucide:circle-dot', keys: 'Alt+click', run: () => ed.toggleInvert(n, pin) })

View File

@ -252,6 +252,9 @@ const moreEntries = computed<MenuEntry[]>(() => {
<select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock"> <select v-model.number="ed.hz.value" class="tb-select" title="Clock speed" :disabled="!hasClock">
<option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option> <option v-for="s in SPEEDS" :key="s.value" :value="s.value">{{ s.label }}</option>
</select> </select>
<button class="bar-btn" :class="{ active: ed.analyzerOpen.value }" title="Logic analyzer: watched signals over time" @click="ed.analyzerOpen.value = !ed.analyzerOpen.value">
<Icon name="lucide:activity" class="size-4" />
</button>
<span v-if="hasClock" class="cycles tabular-nums" title="Clock cycles since this circuit was opened">{{ ed.cycles.value.toLocaleString() }} ticks</span> <span v-if="hasClock" class="cycles tabular-nums" title="Clock cycles since this circuit was opened">{{ ed.cycles.value.toLocaleString() }} ticks</span>
<span class="status" :class="ed.status.value" :title="ed.status.value === 'oscillating' ? 'A loop keeps flipping and never settles (e.g. a NOT feeding itself)' : 'Simulation state'"> <span class="status" :class="ed.status.value" :title="ed.status.value === 'oscillating' ? 'A loop keeps flipping and never settles (e.g. a NOT feeding itself)' : 'Simulation state'">
<span class="dot" />{{ statusText }} <span class="dot" />{{ statusText }}

View File

@ -25,6 +25,7 @@ import { challengeName, challengeOpen, defUsable, isCampaign, KIND_NAMES, kindUn
import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles' import { apiId, makePuzzle, scoreSolution, weekKey, weeklyId } from '~/lib/logic/puzzles'
import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide' import { baseOf, MAX_GATE_INPUTS, NAND_BASE, wideGate } from '~/lib/logic/wide'
import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges' import { CHALLENGES, challengeSteps, type Challenge } from '~/lib/logic/challenges'
import { probeValue } from '~/lib/logic/probes'
import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch' import { latchedTo, latchInto, latchTarget, syncLatches } from '~/lib/logic/latch'
import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library' import { cleanBundle, importBundle, importProblem, LIBRARY_LIMITS, libraryBundle, ownedEntry, publishProblem, type LibraryBundle, type LibraryMeta } from '~/lib/logic/library'
import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile' import { compile, INVERTIBLE, invertedPins, rowSource } from '~/lib/logic/compile'
@ -80,7 +81,7 @@ import {
type AccountUser, type AccountUser,
type ProjectMeta, type ProjectMeta,
} from '~/lib/logic/storage' } from '~/lib/logic/storage'
import type { CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types' import type { CircuitNode, ComponentDef, ConnectorType, HeldState, LampColor, LibraryOrigin, NodeKind, Probe, PanelControl, PanelRow, PinRef, Project, PuzzleSpec, WireColor } from '~/lib/logic/types'
/** A challenge check plus how many transistors the solution uses. */ /** A challenge check plus how many transistors the solution uses. */
/** How everyone did on a puzzle, from the server. */ /** How everyone did on a puzzle, from the server. */
@ -541,6 +542,62 @@ function create() {
} }
let raf = 0 let raf = 0
// ── Logic analyzer ────────────────────────────────────────────────
/** The analyzer panel is open. */
const analyzerOpen = ref(false)
/** What the watched signals were, oldest first: one sample per clock half-step, and on every other change. */
const trace = shallowRef<{ cycle: number; vals: number[]; edge: boolean }[]>([])
const traceVersion = ref(0)
const TRACE_MAX = 1000
let traceKey = ''
/** Takes a sample of the watched signals; without `edge`, only when one of them changed. */
function sample(edge = false) {
const s = sim.value
const d = def.value
const ps = d.probes
if (!s || !ps?.length) return
// Other signals (or another circuit): start over.
const key = `${d.id}|${ps.map(p => `${p.node}:${p.pin}`).join(',')}`
if (key !== traceKey) {
traceKey = key
trace.value = []
}
const vals = ps.map(p => probeValue(d, p, (n, pin) => s.pin(n, pin)))
const list = trace.value
const last = list[list.length - 1]
if (!edge && last && last.vals.every((v, i) => v === vals[i])) return
list.push({ cycle: cycles.value, vals, edge })
if (list.length > TRACE_MAX) list.splice(0, list.length - TRACE_MAX)
traceVersion.value++
}
function clearTrace() {
trace.value = []
traceVersion.value++
sample(true)
}
/** Watches a signal in the analyzer (and opens it). */
function watchSignal(p: Probe | null) {
if (!p) return
const d = def.value
if (!(d.probes ?? []).some(x => x.node === p.node && x.pin === p.pin)) {
d.probes = [...(d.probes ?? []), { node: p.node, pin: p.pin }]
commit(false)
}
analyzerOpen.value = true
nextTick(() => sample(true))
}
function unwatch(i: number) {
const d = def.value
if (!d.probes) return
d.probes = d.probes.filter((_, k) => k !== i)
if (!d.probes.length) delete d.probes
commit(false)
}
function startLoop() { function startLoop() {
let lastT = performance.now() let lastT = performance.now()
let acc: number[] = [] let acc: number[] = []
@ -571,6 +628,7 @@ function create() {
for (let k = 0; acc[i]! >= half && k < 16; k++) { for (let k = 0; acc[i]! >= half && k < 16; k++) {
acc[i]! -= half acc[i]! -= half
s.run(BUDGET) s.run(BUDGET)
sample(true)
if (s.toggleClock(i) && i === counted) rises++ if (s.toggleClock(i) && i === counted) rises++
} }
if (acc[i]! > half) acc[i] = 0 if (acc[i]! > half) acc[i] = 0
@ -590,6 +648,7 @@ function create() {
status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy' status.value = settled ? 'stable' : unsettled > 30 ? 'oscillating' : 'busy'
if (s.changes !== lastChanges) { if (s.changes !== lastChanges) {
lastChanges = s.changes lastChanges = s.changes
if (settled) sample()
tick.value++ tick.value++
} }
} }
@ -608,11 +667,14 @@ function create() {
s.setClock(0) s.setClock(0)
s.run(BUDGET) s.run(BUDGET)
} }
sample(true)
s.setClock(1) s.setClock(1)
s.run(BUDGET) s.run(BUDGET)
cycles.value++ cycles.value++
sample(true)
s.setClock(0) s.setClock(0)
s.run(BUDGET) s.run(BUDGET)
sample(true)
tick.value++ tick.value++
} }
@ -2752,6 +2814,12 @@ function create() {
val, val,
faceVal, faceVal,
startLoop, startLoop,
analyzerOpen,
trace,
traceVersion,
clearTrace,
watchSignal,
unwatch,
step, step,
rebuild, rebuild,
resetState, resetState,

View File

@ -7,6 +7,7 @@ import { cableInUse, cableOf } from '~/lib/logic/cables'
import { INVERTIBLE } from '~/lib/logic/compile' import { INVERTIBLE } from '~/lib/logic/compile'
import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry' import { cableBits, chipPins, portName, type Pt } from '~/lib/logic/geometry'
import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops' import { SINK_KINDS, SOURCE_KINDS } from '~/lib/logic/ops'
import { probeAt, probeOfWire } from '~/lib/logic/probes'
import { KIND_NAMES } from '~/lib/logic/progress' import { KIND_NAMES } from '~/lib/logic/progress'
import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types' import { LAMP_COLORS, WIRE_COLORS, type CircuitNode, type NodeKind } from '~/lib/logic/types'
import { baseOf, gateFamily, inputCount } from '~/lib/logic/wide' import { baseOf, gateFamily, inputCount } from '~/lib/logic/wide'
@ -147,6 +148,11 @@ export function useMenu() {
) )
} }
if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) }) if (n.kind === 'input') out.push({ label: n.on ? 'Switch off' : 'Switch on', icon: n.on ? 'lucide:toggle-right' : 'lucide:toggle-left', run: () => ed.toggleInput(n) })
if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) {
const dir = SOURCE_KINDS.includes(n.kind) ? 'out' : 'in'
const pin = dir === 'out' ? ed.shape(n).outputs[0]?.key : ed.shape(n).inputs[0]?.key
if (pin) out.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => ed.watchSignal(probeAt(ed.def.value, n, pin, dir, get)) })
}
if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) }) if (NAMED.includes(n.kind)) out.push({ label: n.kind === 'note' ? 'Edit text' : 'Rename', icon: 'lucide:pencil', keys: 'Double-click', run: () => rename(n.id) })
const swaps = swapChoices([n]) const swaps = swapChoices([n])
if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps }) if (swaps.length) out.push({ label: 'Change to', icon: 'lucide:replace', children: swaps })
@ -420,6 +426,8 @@ export function useMenu() {
{ label: 'Place the ends yourself', icon: 'lucide:move', keys: 'Ctrl+Shift+G', run: () => ed.startCable() }, { label: 'Place the ends yourself', icon: 'lucide:move', keys: 'Ctrl+Shift+G', run: () => ed.startCable() },
) )
} }
const signals = [...new Map(list.map(w => [`${w.from.node}:${w.from.pin}`, probeOfWire(w)])).values()]
if (signals.length <= 8) out.push({ label: 'Watch in analyzer', icon: 'lucide:activity', run: () => signals.forEach(p => ed.watchSignal(p)) })
if (list.length === 1) out.push({ label: 'Select the whole signal', icon: 'lucide:git-branch', keys: 'Double-click', run: () => ed.selectNet(list[0]!.id) }) if (list.length === 1) out.push({ label: 'Select the whole signal', icon: 'lucide:git-branch', keys: 'Double-click', run: () => ed.selectNet(list[0]!.id) })
const colors = new Set(list.map(w => w.color)) const colors = new Set(list.map(w => w.color))
out.push({ out.push({

55
app/lib/logic/probes.ts Normal file
View File

@ -0,0 +1,55 @@
// The logic analyzer's signals: wires and cables of a circuit you watch.
// Each is a pin of a part there (an output, or an input's wire); a cable
// pin reads its whole cable as one number, wire 0 the lowest bit.
import { cableBits, shapeOf, type DefLookup } from './geometry'
import { pinName } from './labels'
import type { CircuitNode, ComponentDef, Probe } from './types'
/** How many bits a signal has: 1 for a wire, the cable's wires for a cable pin. */
export function probeBits(def: ComponentDef, p: Probe): number {
const n = def.nodes.find(x => x.id === p.node)
if ((n?.kind === 'bundle' && p.pin === 'q') || (n?.kind === 'split' && p.pin === 'a')) return cableBits(n)
return 1
}
/** A signal's value now, read with \`pin(node, pin)\` (the simulator's). */
export function probeValue(def: ComponentDef, p: Probe, pin: (node: string, pin: string) => number): number {
const n = def.nodes.find(x => x.id === p.node)
if (n && ((n.kind === 'bundle' && p.pin === 'q') || (n.kind === 'split' && p.pin === 'a'))) {
// A cable: its wires as they leave the bundle (a split reads the bundle that feeds it).
const bundle = n.kind === 'bundle' ? n : def.nodes.find(x => x.id === def.wires.find(w => w.to.node === n.id && w.to.pin === 'a')?.from.node)
if (!bundle || bundle.kind !== 'bundle') return 0
let v = 0
for (let i = 0; i < cableBits(n); i++) if (pin(bundle.id, `b${i}`)) v += 2 ** i
return v
}
return pin(p.node, p.pin)
}
/** What a signal is called: its own name, else the pin's or the part's. */
export function probeName(def: ComponentDef, p: Probe, get: DefLookup): string {
if (p.label?.trim()) return p.label.trim()
const n = def.nodes.find(x => x.id === p.node)
if (!n) return '?'
const own = n.label?.trim() && !n.autoLabel ? n.label.trim() : ''
const pin = pinName(n, p.pin, get)
const part = own || (n.kind === 'chip' ? (n.chip && get(n.chip)?.name) || 'Component' : n.kind)
if (n.kind === 'bundle' || n.kind === 'split') return own || `Cable ${probeBits(def, p)}`
if (['input', 'button', 'clock', 'output', 'lamp'].includes(n.kind)) return own || part
return pin ? `${part} ${pin}` : part
}
/** The signal a wire carries: the pin it comes from. */
export const probeOfWire = (w: { from: { node: string; pin: string } }): Probe => ({ node: w.from.node, pin: w.from.pin })
/**
* The signal at a pin: an output itself, an input by the wire into it (or,
* with none, the pin, which reads 0).
*/
export function probeAt(def: ComponentDef, node: CircuitNode, pin: string, dir: 'in' | 'out', get: DefLookup): Probe | null {
if (dir === 'out') return { node: node.id, pin }
const w = def.wires.find(x => x.to.node === node.id && x.to.pin === pin)
if (w) return probeOfWire(w)
return shapeOf(node, get).inputs.some(p => p.key === pin) ? { node: node.id, pin } : null
}

View File

@ -143,6 +143,11 @@ export function toProject(data: unknown): Project {
if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide if (d.wide !== undefined && !(d.wide && typeof d.wide.base === 'string' && Number.isInteger(d.wide.n) && d.wide.n >= 2 && d.wide.n <= 16)) delete d.wide
if (d.design !== undefined) cleanDesign(d) if (d.design !== undefined) cleanDesign(d)
if (d.from !== undefined) cleanOrigin(d) if (d.from !== undefined) cleanOrigin(d)
if (d.probes !== undefined) {
d.probes = Array.isArray(d.probes) ? d.probes.filter(p => p && typeof p.node === 'string' && typeof p.pin === 'string').slice(0, 64) : []
for (const p of d.probes) if (p.label !== undefined && typeof p.label !== 'string') delete p.label
if (!d.probes.length) delete d.probes
}
for (const n of d.nodes) cleanNode(n) for (const n of d.nodes) cleanNode(n)
for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color for (const w of d.wires) if (w.color && !WIRE_COLORS.includes(w.color)) delete w.color
for (const w of d.wires) if (w.pts !== undefined && !cornersOk(w.pts)) delete w.pts for (const w of d.wires) if (w.pts !== undefined && !cornersOk(w.pts)) delete w.pts

View File

@ -145,6 +145,16 @@ export interface ComponentDef {
design?: FaceDesign design?: FaceDesign
/** Set when the component came from the public library (or was published there from here). */ /** Set when the component came from the public library (or was published there from here). */
from?: LibraryOrigin from?: LibraryOrigin
/** Signals watched in the logic analyzer, top to bottom. */
probes?: Probe[]
}
/** A signal watched in the logic analyzer: a pin of a part (a cable pin reads the whole cable). */
export interface Probe {
node: string
pin: string
/** A name of its own for the analyzer. */
label?: string
} }
/** Where a component of the public library came from: the entry, its version and who published it. */ /** Where a component of the public library came from: the entry, its version and who published it. */

54
tests/probes.test.ts Normal file
View File

@ -0,0 +1,54 @@
import { describe, expect, it } from 'vitest'
import { bundleWires } from '../app/lib/logic/cables'
import { compile } from '../app/lib/logic/compile'
import { createProject, lookup } from '../app/lib/logic/ops'
import { probeAt, probeBits, probeName, probeOfWire, probeValue } from '../app/lib/logic/probes'
import { toProject } from '../app/lib/logic/project'
import { Simulator } from '../app/lib/logic/sim'
import type { ComponentDef } from '../app/lib/logic/types'
/** Four switches into a cable, the cable to four lamps. */
function setup() {
const p = createProject({ examples: false })
const def: ComponentDef = {
id: 'root',
name: 'Root',
symbol: 'box',
nodes: [
...[0, 1, 2, 3].map(i => ({ id: `s${i}`, kind: 'input' as const, x: 0, y: i * 2, label: `S${i}` })),
...[0, 1, 2, 3].map(i => ({ id: `l${i}`, kind: 'lamp' as const, x: 30, y: 10 + i * 2 })),
],
wires: [0, 1, 2, 3].map(i => ({ id: `w${i}`, from: { node: `s${i}`, pin: 'q' }, to: { node: `l${i}`, pin: 'a' } })),
}
p.components.push(def)
const res = bundleWires(def, ['w0', 'w1', 'w2', 'w3'], lookup(p))
if (!res.ok) throw new Error(res.error)
return { p, def }
}
describe('analyzer signals', () => {
it('a cable reads as one number, wire 0 the lowest bit; a wire as 0 or 1', () => {
const { p, def } = setup()
const s = new Simulator(compile(lookup(p), def.id))
s.setSource('s0', true)
s.setSource('s2', true)
s.run()
const cable = def.wires.find(w => def.nodes.find(n => n.id === w.from.node)?.kind === 'bundle')!
const cp = probeOfWire(cable)
expect(probeBits(def, cp)).toBe(4)
expect(probeValue(def, cp, (n, pin) => s.pin(n, pin))).toBe(5)
const lamp = def.nodes.find(n => n.id === 'l2')!
const lp = probeAt(def, lamp, 'a', 'in', lookup(p))!
expect(probeBits(def, lp)).toBe(1)
expect(probeValue(def, lp, (n, pin) => s.pin(n, pin))).toBe(1)
expect(probeName(def, { node: 's1', pin: 'q' }, lookup(p))).toBe('S1')
expect(probeName(def, cp, lookup(p))).toBe('Cable 4')
})
it('watched signals are saved with the circuit and survive loading', () => {
const { p, def } = setup()
def.probes = [{ node: 's0', pin: 'q' }, { node: 'x', pin: 'q', label: 'mine' }]
const back = toProject(JSON.parse(JSON.stringify(p)))!
expect(back.components.find(c => c.id === 'root')!.probes).toEqual(def.probes)
})
})