diff --git a/README.md b/README.md index 8cb815a..f0fdcea 100644 --- a/README.md +++ b/README.md @@ -23,12 +23,44 @@ Point the [BenchPod MCP server](https://pypi.org/project/embeddedci-mcp/) or the BENCHPOD_TLS=off BENCHPOD_WIRING=/tmp/wiring.json embeddedci-mcp --connection 127.0.0.1:18080 --la-voltage 3.3 ``` +## Firmware 4.0 protocol + +The simulator answers as BenchPod firmware 4.0.0 does: client API 2. Clients send +`"client_api":2` on every command; a command without it (or with a lower level) is refused with +`BP0030`, except `status`, `diag`, `ping`, `lease_release`, the update commands, `blob_status` and +`identity_public`. A refusal a client acts on carries a code and its args, no message: + +```bash +printf '{"cmd":"la_pins"}\n' | nc 127.0.0.1 18080 +# {"args":{"api":2,"client_api":0,"min_client_api":2},"code":"BP0030","message":"Update the BenchPod SDK, ...","status":"error"} +printf '{"cmd":"frobnicate","client_api":2}\n' | nc 127.0.0.1 18080 +# {"args":{"cmd":"frobnicate"},"code":"BP0002","status":"error"} +``` + +`status` reports `api`, `min_client_api`, `features_rev`, `fpga_image` and `hw` instead of a +`caps` list. Some requests with the 4.0 names: + +```json +{"cmd":"target_power","efuse":1,"enabled":true,"client_api":2} +{"cmd":"la_pull","la":1,"pull":"up","client_api":2} +{"cmd":"generate","waveform":"sine","freq_hz":1000,"path":"3v3","amplitude_v":1,"offset_v":1.65,"client_api":2} +{"cmd":"dac_out","path":"3v3","v":1.1,"client_api":2} +{"cmd":"la_capture","samples":20000,"sample_rate_hz":2000000,"client_api":2} +{"cmd":"capture_dual","adc_samples":4096,"adc_sample_rate_hz":400000,"la_samples":4096,"la_sample_rate_hz":1000000,"client_api":2} +{"cmd":"spi_start","sck":10,"mosi":11,"miso":12,"cs":13,"clock_hz":1000000,"client_api":2} +{"cmd":"power_profile","efuse":1,"sample_rate_hz":500,"duration_ms":1000,"client_api":2} +``` + +ADC samples come as `"b64"` unless the request says `"enc":"dec"`. SCPI is off, as on a new pod; +`lan_tls` `"scpi":true` from the cloud link (`podsim`) turns it on. The simulator serves plaintext +only: it reports `https_only` as the firmware does but keeps answering JSON on its plaintext port. + ## Emulated sensors `sensor_define`, `sensor_start`, `sensor_set`, `sensor_stop`, `sensor_status`, `sensor_regs`, `sensor_la`, `sensor_fault`, `sensor_fault_clear` and the `sensor_stimulus` commands take the definitions of the [sensor library](https://github.com/embeddedci-com/benchpod-sensors), or your -own, and answer as firmware 3.10.3 does. The register images, UART messages and analog values +own, and answer as firmware 4.0.0 does. The register images, UART messages and analog values come from the same engine the pod compiles definitions with, so the node reads what it would read from a real pod. Try `bmp280` on LA2 (SDA) and LA1 (SCL) and power-cycle the node. diff --git a/benchsim/analog.go b/benchsim/analog.go index f724dec..4e9902f 100644 --- a/benchsim/analog.go +++ b/benchsim/analog.go @@ -260,24 +260,24 @@ func (s *Sim) cmdDacOut(r request) (any, error) { } if p == "off" { d.path = "off" - return map[string]any{"path": "off", "mv": 0, "code": -1}, nil + return map[string]any{"path": "off", "mv": 0}, nil } d.path = p - if v, has := r.num("volts"); has || r.has("volts") { + if v, has := r.num("v"); has || r.has("v") { line := s.dacLineFor(idx) if !s.firmware { rng := dacRange[p] if !has || v < rng[0]-1e-9 || v > rng[1]+1e-9 { - return nil, errf("volts out of range for %s (%g..%g V)", p, rng[0], rng[1]) + return nil, errf("v out of range for %s (%g..%g V)", p, rng[0], rng[1]) } } code := max(0, min(int(math.Round((v-line.a)/line.b*256)), 65535)) got := line.volts(float64(code)) *d = dacState{path: p, code: float64(code)} return map[string]any{"path": name, "mv": int(math.Round(got * 1000)), "uv": int64(math.Round(got * 1e6)), - "code": min((code+128)>>8, 255), "code16": code}, nil + "code16": code}, nil } - return map[string]any{"path": name, "mv": 0, "code": -1}, nil + return map[string]any{"path": name, "mv": 0}, nil } func (s *Sim) cmdAdcRead(r request) (any, error) { @@ -335,9 +335,15 @@ func (s *Sim) cmdGenerate(r request) (any, error) { default: return nil, fwError("waveform must be sine|square|sawtooth") } - freq, ok := r.num("freq") - if !ok || freq <= 0 || freq > 100000 { - return nil, fwError("freq must be 0 < freq <= 100000 Hz") + freq := 1000.0 + if v, ok := r.num("freq_hz"); ok { + freq = v + } + if freq <= 0 || freq > 100000 { + return nil, fwError("freq_hz must be 0 < freq_hz <= 100000") + } + if !r.has("amplitude_v") && !r.has("amplitude_ua") { + return nil, errGenerateLevels } if r.has("amplitude_ua") { return nil, notInDemo("the 4-20 mA output") @@ -345,15 +351,15 @@ func (s *Sim) cmdGenerate(r request) (any, error) { path := r.str("path") rng, ok := dacRange[path] if !ok { - if r.has("amplitude") { - return nil, fwError("this firmware takes amplitude_v/offset_v with a path") - } - return nil, fwError("path must be 3v3|5v|12v") + return nil, fwError("path must be 3v3|5v|12v with amplitude_v") } amp, ok1 := r.num("amplitude_v") off, ok2 := r.num("offset_v") - if !ok1 || !ok2 || amp <= 0 { - return nil, fwError("missing amplitude_v/offset_v") + if !ok2 { + return nil, fwError("offset_v is required with amplitude_v") + } + if !ok1 || amp <= 0 { + return nil, fwError("amplitude_v must be above 0 V") } slack := (rng[1] - rng[0]) * 0.05 if off-amp < rng[0]-slack || off+amp > rng[1]+slack { @@ -373,6 +379,8 @@ func (s *Sim) cmdGenerate(r request) (any, error) { } s.snapshotAnalog(now) s.pod.analog.dac = d - return map[string]any{"running": true, "bits": 16, "path": path, "freq": freq, "cotrig": false, - "sample_rate_hz": 888888}, nil + if r.flag("on_capture") { // the demo has no co-trigger: the waveform starts now + return map[string]any{"cotrig": false}, nil + } + return nil, nil } diff --git a/benchsim/can.go b/benchsim/can.go index b22734a..094b8c3 100644 --- a/benchsim/can.go +++ b/benchsim/can.go @@ -53,7 +53,7 @@ func byteArray(v any) []int { return out } -func (s *Sim) cmdCanConfig(r request) (any, error) { +func (s *Sim) cmdCanStart(r request) (any, error) { bitrate := r.int("bitrate", 500000) mode := "normal" if r.has("mode") { @@ -117,7 +117,7 @@ func (s *Sim) cmdCanRead(r request) (any, error) { n := min(want, len(c.rx)) frames := []any{} for _, f := range c.rx[:n] { - frames = append(frames, map[string]any{"id": f.id, "ext": f.ext, "rtr": f.rtr, "dlc": len(f.data), "data": f.data, "ts": f.ts}) + frames = append(frames, map[string]any{"id": f.id, "ext": f.ext, "rtr": f.rtr, "dlc": len(f.data), "data": f.data, "ts_ms": f.ts}) } c.rx = append(c.rx[:0], c.rx[n:]...) return map[string]any{"frames": frames, "overflow": c.overflow}, nil @@ -170,7 +170,7 @@ func (s *Sim) cmdCanTerm(r request) (any, error) { return map[string]any{"term": on}, nil } -func (s *Sim) cmdCanDisable(request) (any, error) { +func (s *Sim) cmdCanStop(request) (any, error) { s.mu.Lock() defer s.mu.Unlock() s.pod.can.enabled = false diff --git a/benchsim/capture.go b/benchsim/capture.go index 5e2709c..e25315c 100644 --- a/benchsim/capture.go +++ b/benchsim/capture.go @@ -61,7 +61,7 @@ func (s *Sim) beginCapture(c *conn) error { } s.heavyRelease(c) } else if s.pod.capture { - return fwError("busy: a capture is running") + return coded(codePodBusy) } s.pod.capture = true return nil @@ -128,11 +128,7 @@ func (s *Sim) waitTrigger(ts *trigSpec) (int64, error) { return at, nil } if now >= deadline { - kind := "edge" - if ts.edge == "high" || ts.edge == "low" { - kind = "level" - } - return 0, errf("trigger timeout: no %s %s on LA%d within %d ms", ts.edge, kind, ts.la, ts.timeout/msNs) + return 0, coded(codeTriggerTimeout, "la", ts.la, "edge", ts.edge, "timeout_ms", int(ts.timeout/msNs)) } if ts.edge == "rising" || ts.edge == "falling" { from = now // edges after what was searched; a level can be checked from anywhere @@ -156,7 +152,7 @@ func laFrames(c *conn, edges [][2]int, n int, rate float64, first map[string]any } m := map[string]any{"status": "chunk", "la": true, "la_edges": edges[i:j], "la_upto": upto, "more": !(last && final)} if i == 0 || !c.sim.firmware { - m["status"], m["la_rate_hz"] = "ok", int(rate) + m["status"], m["la_sample_rate_hz"] = "ok", int(rate) } if i == 0 && c.sim.firmware { m["bits"] = 16 @@ -180,7 +176,7 @@ func laFrames(c *conn, edges [][2]int, n int, rate float64, first map[string]any func (s *Sim) cmdLaCapture(c *conn, r request) error { fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } s.mu.Lock() @@ -191,10 +187,10 @@ func (s *Sim) cmdLaCapture(c *conn, r request) error { } n := r.int("samples", 256) if n <= 0 || n > 4_000_000 { - return fail(fwError("samples out of range")) + return fail(coded(codeSamplesOutOfRange, "max", 4_000_000)) } - mhz, _ := r.num("sample_rate_mhz") - rate := laRate(mhz * 1e6) + hz, _ := r.num("sample_rate_hz") + rate := laRate(hz) n = s.clampSamples(n, maxLaSamples, rate) ts, err := parseTrigger(r) if err != nil { @@ -236,7 +232,7 @@ func (s *Sim) cmdLaCapture(c *conn, r request) error { // and only catches one by chance. func (s *Sim) cmdSensorLa(c *conn, r request) error { fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } s.mu.Lock() @@ -258,10 +254,10 @@ func (s *Sim) cmdSensorLa(c *conn, r request) error { } bytes := r.int("samples", 256) if bytes <= 0 || bytes > maxSensorLaB { - return fail(fwError("samples must be 1..4096")) + return fail(coded(codeSamplesOutOfRange, "max", maxSensorLaB)) } - mhz, _ := r.num("sample_rate_mhz") - rate := laRate(mhz * 1e6) + hz, _ := r.num("sample_rate_hz") + rate := laRate(hz) n := bytes * 4 if err := s.beginCapture(c); err != nil { return fail(err) @@ -316,24 +312,33 @@ func (s *Sim) cmdSensorLa(c *conn, r request) error { pair := (w>>(scl-1)&1)<<1 | (w >> (sda - 1) & 1) out[i/4] |= pair << ((3 - i%4) * 2) } - return sendSamples(c, out, 1024) + return sendSamples(c, out, 1024, int(rate)) } -// sendSamples writes a sample list the way bulk_begin does: chunks of "data" with "more". -func sendSamples(c *conn, data []int, per int) error { +// sendSamples writes a sample list the way bulk_begin does: chunks of "data" with "more", the +// first with the LA rate it ran at. +func sendSamples(c *conn, data []int, per, rateHz int) error { if len(data) == 0 { - return c.send(map[string]any{"status": "ok", "data": []int{}, "more": false}) + return c.send(map[string]any{"status": "ok", "la_sample_rate_hz": rateHz, "data": []int{}, "more": false}) } for i := 0; i < len(data); i += per { j := min(i+per, len(data)) - if err := c.send(map[string]any{"status": "ok", "data": data[i:j], "more": j < len(data)}); err != nil { + m := map[string]any{"status": "ok", "data": data[i:j], "more": j < len(data)} + if i == 0 { + m["la_sample_rate_hz"] = rateHz + } + if err := c.send(m); err != nil { return nil } } return nil } -// adcChunk is one dense ADC frame: base64url of little-endian uint16 ("enc":"b64") or decimal. +// wantsB64 is wants_b64: dense samples come as base64 unless the request says "enc":"dec" +// (firmware 4.0.0; up to 3.10.13 decimal was the default). +func wantsB64(r request) bool { return r.str("enc") != "dec" } + +// adcChunk is one dense ADC frame: base64url of little-endian uint16 (the default) or decimal. func adcChunk(counts []int, b64 bool) map[string]any { if !b64 { return map[string]any{"status": "ok", "data": counts} @@ -353,7 +358,9 @@ func (s *Sim) adcCounts(t0 int64, n int, rate float64) []int { return out } -func sendAdc(c *conn, counts []int, rate float64, b64, final bool) error { +// sendAdc sends the ADC region; laRate, when not 0, is the LA's rate in the same first frame +// (capture_dual). +func sendAdc(c *conn, counts []int, rate, laRate float64, b64, final bool) error { for i := 0; i < len(counts) || i == 0; i += samplesPerChnk { j := min(i+samplesPerChnk, len(counts)) m := adcChunk(counts[i:j], b64) @@ -362,7 +369,10 @@ func sendAdc(c *conn, counts []int, rate float64, b64, final bool) error { } if i == 0 { m["status"] = "ok" - m["adc_rate_hz"] = int(rate) + m["adc_sample_rate_hz"] = int(rate) + if laRate > 0 { + m["la_sample_rate_hz"] = int(laRate) + } m["bits"] = 16 } if final && j >= len(counts) && c.trigger != nil { @@ -381,18 +391,15 @@ func sendAdc(c *conn, counts []int, rate float64, b64, final bool) error { func (s *Sim) cmdCapture(c *conn, r request) error { fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } n := r.int("samples", 256) if n <= 0 || n > 32768 { - if s.firmware { - return fail(fwError("samples out of range (use capture_dual for deep captures)")) - } - return fail(fwError("samples out of range")) + return fail(coded(codeSamplesOutOfRange, "max", 32768)) } - mhz, _ := r.num("sample_rate_mhz") - rate := adcRate(mhz * 1e6) + hz, _ := r.num("sample_rate_hz") + rate := adcRate(hz) n = s.clampSamples(n, maxAdcSamples, rate) if err := s.beginCapture(c); err != nil { return fail(err) @@ -409,14 +416,14 @@ func (s *Sim) cmdCapture(c *conn, r request) error { s.advance(s.now()) counts := s.adcCounts(t0, n, rate) s.mu.Unlock() - return sendAdc(c, counts, rate, r.str("enc") == "b64", true) + return sendAdc(c, counts, rate, 0, wantsB64(r), true) } // cmdCaptureDual is one trigger for an ADC and an LA stream (either may be empty): the deep // ADC capture and the correlated capture. func (s *Sim) cmdCaptureDual(c *conn, r request) error { fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } na, nl := r.int("adc_samples", 0), r.int("la_samples", 0) @@ -424,7 +431,7 @@ func (s *Sim) cmdCaptureDual(c *conn, r request) error { return fail(fwError("adc_samples and la_samples are both 0")) } if s.firmware && (na+nl)*2 > 8<<20 { - return fail(fwError("capture too deep: LA+ADC+DAC exceed 8 MB PSRAM")) + return fail(coded(codePsramTooSmall)) } if na < 0 || nl < 0 || na+nl == 0 || na > 8_000_000 || nl > 4_000_000 { return fail(fwError("samples out of range")) @@ -437,9 +444,9 @@ func (s *Sim) cmdCaptureDual(c *conn, r request) error { return fail(err) } } - amhz, _ := r.num("adc_rate_mhz") - lmhz, _ := r.num("la_rate_mhz") - ar, lr := adcRate(amhz*1e6), laRate(lmhz*1e6) + ahz, _ := r.num("adc_sample_rate_hz") + lhz, _ := r.num("la_sample_rate_hz") + ar, lr := adcRate(ahz), laRate(lhz) na = s.clampSamples(na, maxAdcSamples, ar) if nl > 0 { nl = s.clampSamples(nl, maxLaSamples, lr) @@ -491,7 +498,11 @@ func (s *Sim) cmdCaptureDual(c *conn, r request) error { c.trigger = map[string]any{"la": ts.la, "edge": ts.edge, "fired": true} } if na > 0 { - if err := sendAdc(c, counts, ar, r.str("enc") == "b64", nl == 0); err != nil { + lrHz := 0.0 + if nl > 0 { + lrHz = lr + } + if err := sendAdc(c, counts, ar, lrHz, wantsB64(r), nl == 0); err != nil { return nil } } @@ -558,7 +569,7 @@ func (s *Sim) cmdCaptureRead(c *conn, r request) error { lc := s.pod.lastCap s.mu.Unlock() fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } if lc == nil { @@ -576,7 +587,7 @@ func (s *Sim) cmdCaptureRead(c *conn, r request) error { if off < na { for i := off; i < na; i += samplesPerChnk { j := min(i+samplesPerChnk, na) - m := adcChunk(lc.adc[i:j], r.str("enc") == "b64") + m := adcChunk(lc.adc[i:j], wantsB64(r)) m["status"] = "chunk" m["more"] = !(j >= na && lc.nl == 0) if err := c.send(m); err != nil { diff --git a/benchsim/dac.go b/benchsim/dac.go index 2415de9..bf54961 100644 --- a/benchsim/dac.go +++ b/benchsim/dac.go @@ -116,7 +116,7 @@ func (s *Sim) dacLimitsCheck(cmd string, r request) string { case "dac_out": path := r.str("path") why := route(path) - v, ok := r.num("volts") + v, ok := r.num("v") if why == "" && ok && pathIndex(path) == l.path { if v < float64(l.minMv)/1000-0.005 || v > float64(l.maxMv)/1000+0.005 { return fmt.Sprintf("refused: %s; %d mV is outside them", l.describe(), int(math.Round(v*1000))) @@ -226,37 +226,35 @@ func (s *Sim) cmdDacSet(r request) (any, error) { return nil, nil } -// cmdGenerateFw is handle_generate: the 8-bit levels form (no routing) and the calibrated 16-bit -// form (volts on a path, or microamps on the 4-20 mA output). +// errGenerateLevels is generate without a calibrated level: firmware 4.0.0 takes no 8-bit +// amplitude/offset. +const errGenerateLevels = fwError("amplitude_v (with path and offset_v) or amplitude_ua (with offset_ua) is required") + +// cmdGenerateFw is handle_generate: volts on a path, or microamps on the 4-20 mA output, built at +// the DAC's 16 bits. The reply is null, or {"cotrig":bool} with on_capture. func (s *Sim) cmdGenerateFw(_ *conn, r request) (any, error) { wave := r.str("waveform") freq := 1000.0 - if v, ok := r.num("freq"); ok { + if v, ok := r.num("freq_hz"); ok { freq = v } durMs := r.int("duration_ms", 0) - sixteen := r.has("amplitude_v") || r.has("amplitude_ua") if wave != "sine" && wave != "square" && wave != "sawtooth" { return nil, fwError("unknown waveform") } - if freq <= 0 { - return nil, fwError("generate failed") + if !r.has("amplitude_v") && !r.has("amplitude_ua") { + return nil, errGenerateLevels } s.mu.Lock() defer s.mu.Unlock() now := s.now() s.advance(now) - var amp, mid float64 - path := "" - if sixteen { - var err error - amp, mid, path, err = s.generate16Codes(r) - if err != nil { - return nil, err - } - } else { - amp = float64(r.int("amplitude", 127)) * 256 - mid = float64(r.int("offset", 128)) * 256 + amp, mid, path, err := s.generate16Codes(r) + if err != nil { + return nil, err + } + if freq <= 0 { + return nil, fwError("generate failed") } s.snapshotAnalog(now) a := &s.pod.analog @@ -272,12 +270,7 @@ func (s *Sim) cmdGenerateFw(_ *conn, r request) (any, error) { cotrigAsked := r.flag("on_capture") nd.armed = cotrigAsked a.dac = nd - switch { - case sixteen && cotrigAsked: - return map[string]any{"bits": 16, "cotrig": true}, nil - case sixteen: - return map[string]any{"bits": 16}, nil - case cotrigAsked: + if cotrigAsked { return map[string]any{"cotrig": true}, nil } return nil, nil @@ -333,7 +326,7 @@ func (s *Sim) generate16Codes(r request) (amp, mid float64, path string, err err // cmdLoadBin is handle_load_bin and load_bin_receive: raw bytes, then JSON again on the connection. func (s *Sim) cmdLoadBin(c *conn, r request) error { fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } if !r.has("total") { @@ -427,8 +420,8 @@ func (s *Sim) cmdReplay(c *conn, r request) (any, error) { if s.pod.tracePsram && s.pod.image != 1 { return nil, fwError("replay failed") } - mhz, _ := r.num("sample_rate_mhz") - rate := replayRate(mhz*1e6, s.pod.tracePsram) + hz, _ := r.num("sample_rate_hz") + rate := replayRate(hz, s.pod.tracePsram) s.snapshotAnalog(now) d := &s.pod.analog.dac cotrig := r.flag("on_capture") @@ -678,7 +671,7 @@ func (s *Sim) cmdLoopInput(c *conn, r request) (any, error) { now := s.now() s.advance(now) s.pod.loopSrc, s.pod.loopIn, s.pod.loopStep = src, in, step - return map[string]any{"source": src, "input": in, "step": step, "v": int(s.pod.analog.dac.codeAt(now))}, nil + return map[string]any{"source": src, "input": in, "step": step, "code16": int(s.pod.analog.dac.codeAt(now))}, nil } func (s *Sim) cmdLoopProbe(c *conn, _ request) (any, error) { @@ -701,7 +694,7 @@ func (s *Sim) cmdLoopProbe(c *conn, _ request) (any, error) { if d.loop != nil { in, tripped = d.loop.in, d.loop.tripped } - return map[string]any{"i": s.adcCount(now), "in": in, "source": s.pod.loopSrc, "v": int(math.Round(d.codeAt(now))), "tripped": tripped}, nil + return map[string]any{"i": s.adcCount(now), "in": in, "source": s.pod.loopSrc, "code16": int(math.Round(d.codeAt(now))), "tripped": tripped}, nil } func (s *Sim) cmdCurrentOut(r request) (any, error) { @@ -1030,24 +1023,28 @@ func (s *Sim) cmdPsramPing(c *conn, r request) (any, error) { // The policies and cloud link settings (command_handler_policy.c, pod_policy.c). -func (s *Sim) cmdSigPolicy(c *conn, r request) (any, error) { +// cmdSigPolicy: firmware 4.0.0 installs only signed images. "set":"required" is fine from every +// source; audit and permissive, and lan_unsigned true, are refused with BP0074. clear_floor is for +// the USB link only, which the simulator has not. +func (s *Sim) cmdSigPolicy(_ *conn, r request) (any, error) { s.mu.Lock() defer s.mu.Unlock() if r.has("set") { - order := map[string]int{"audit": 0, "permissive": 1, "required": 2} - v, ok := order[r.str("set")] - if !ok { - return nil, fwError("sig_policy: set must be audit, permissive or required") - } - if !c.cloud { - return nil, fwError("sig_policy: change it from the cloud or the USB console") - } - if v < order[s.flash.sigPolicy] { - return nil, errf("sig_policy: only the USB console can loosen the policy (now %s)", s.flash.sigPolicy) + switch v := r.str("set"); v { + case "required": + case "audit", "permissive": + return nil, coded(codeSignaturesAlwaysReqd, "setting", "sig_policy", "want", v) + default: + return nil, fwError("sig_policy: set must be required") } - s.flash.sigPolicy = r.str("set") } - return map[string]any{"policy": s.flash.sigPolicy, "enforces": true, "keys": 1}, nil + if r.has("lan_unsigned") && r.str("lan_unsigned") != "false" { + return nil, coded(codeSignaturesAlwaysReqd, "setting", "lan_unsigned", "want", r.str("lan_unsigned")) + } + if r.flag("clear_floor") { + return nil, coded(codeSettingDeviceOnly, "setting", "rollback_floor") + } + return map[string]any{"policy": s.flash.sigPolicy, "enforces": true, "keys": 1, "rollback_floor": nil}, nil } func (s *Sim) cmdLanPolicy(c *conn, r request) (any, error) { @@ -1059,7 +1056,7 @@ func (s *Sim) cmdLanPolicy(c *conn, r request) (any, error) { return nil, fwError("lan_policy: set must be open, locked or off") } if !c.cloud { - return nil, fwError("lan_policy: change it from the cloud or the USB console") + return nil, coded(codePolicyNotFromLan, "setting", "lan_policy") } s.flash.lanPolicy = p } @@ -1068,14 +1065,59 @@ func (s *Sim) cmdLanPolicy(c *conn, r request) (any, error) { func (s *Sim) cloudLinkGate(c *conn, verb string) error { if !c.cloud { - return errf("%s: change it from the cloud or over USB", verb) + return coded(codeSettingCloudOrUsb, "setting", verb) } if s.pod.capture || s.pod.heavy != nil || s.pod.load != nil { - return fwError("busy: a capture, upload or update is using the PSRAM bus; try again when it ends") + return coded(codeStorageBusBusy, "what", "a capture, upload or update is running") } return nil } +// cmdUsbNetwork: whether the pod's USB port is also a network adapter. Only the device changes +// it (the USB console, or a connection over the USB link, which the simulator has not): the LAN +// and the cloud get BP0043. +func (s *Sim) cmdUsbNetwork(_ *conn, r request) (any, error) { + s.mu.Lock() + defer s.mu.Unlock() + if r.has("enabled") { + if _, ok := r["enabled"].(bool); !ok { + return nil, fwError("usb_network: enabled must be true or false") + } + return nil, coded(codeSettingDeviceOnly, "setting", "usb_network") + } + return map[string]any{"enabled": s.flash.usbNet}, nil +} + +// cmdLanTLS: the LAN API over TLS. HTTPS-only (default on) and SCPI (default off) change from the +// cloud or over USB; the external LAN gets BP0042. The simulator serves plaintext only and keeps +// answering JSON on it whatever https_only says. +func (s *Sim) cmdLanTLS(c *conn, r request) (any, error) { + s.mu.Lock() + defer s.mu.Unlock() + for _, k := range []string{"https_only", "scpi"} { + if !r.has(k) { + continue + } + v, ok := r[k].(bool) + if !ok { + return nil, errf("lan_tls: %s must be true or false", k) + } + if !c.cloud { + return nil, coded(codeSettingCloudOrUsb, "setting", "lan_tls") + } + if k == "https_only" { + s.flash.httpsOff = !v + } else { + s.flash.scpi = v + } + } + if r.flag("regenerate") && !c.cloud { + return nil, coded(codeSettingCloudOrUsb, "setting", "lan_tls") + } + return map[string]any{"port": 8443, "https_only": !s.flash.httpsOff, "scpi": s.flash.scpi, "sessions": 0, + "error": "no certificate"}, nil +} + func (s *Sim) cmdCloudCa(c *conn, r request) (any, error) { s.mu.Lock() defer s.mu.Unlock() diff --git a/benchsim/e2e_test.go b/benchsim/e2e_test.go index 57aa016..21f727e 100644 --- a/benchsim/e2e_test.go +++ b/benchsim/e2e_test.go @@ -81,7 +81,7 @@ func TestMCPEndToEnd(t *testing.T) { // Connect as the host does, then the agent's first steps. expect(call("connect", nil), `"connected":\s*true`) - call("set_la_voltage", map[string]any{"voltage": 3.3}) + call("set_la_voltage", map[string]any{"la_voltage": 3.3}) expect(call("status", nil), `"la_voltage":\s*3\.3`) w := call("wiring", nil) expect(w, `"uart_rx":\s*3`) @@ -100,7 +100,7 @@ func TestMCPEndToEnd(t *testing.T) { expect(call("sensor_status", nil), `"instances":\s*\[\]`) expect(call("sensor_library", nil), `"bmp280"`) expect(call("sensor_show", map[string]any{"name": "bmp280"}), `temperature_c`) - call("set_pull", map[string]any{"las": []any{1, 2}, "enabled": true}) + call("set_pull", map[string]any{"la": []any{1, 2}, "pull": "up"}) call("pull_status", nil) call("sensor_start", map[string]any{"definition": "bme280", "instance": "env"}) expect(call("power_cycle_and_capture", map[string]any{"until_regex": "APP_OK"}), `chip id 0x60, not 0x58`) @@ -113,13 +113,13 @@ func TestMCPEndToEnd(t *testing.T) { // Story 3: the console: readings, then an over-temperature alarm from the emulated sensor. call("uart_open", nil) call("uart_write", map[string]any{"text": "alarm"}) - expect(call("uart_read", map[string]any{"until_regex": `ALARM .*press_pa=\d+ events=\d+`, "timeout": 3}), `env=ok env_c=24\.0`) + expect(call("uart_read", map[string]any{"until_regex": `ALARM .*press_pa=\d+ events=\d+`, "timeout_s": 3}), `env=ok env_c=24\.0`) call("sensor_set", map[string]any{"instance": "env", "values": map[string]any{"temperature_c": 55}}) - expect(call("uart_read", map[string]any{"until_regex": "EVT alarm set=overtemp", "timeout": 3}), `"matched":\s*true`) + expect(call("uart_read", map[string]any{"until_regex": "EVT alarm set=overtemp", "timeout_s": 3}), `"matched":\s*true`) expect(call("gpio_read", map[string]any{"la": []any{"ALARM"}}), `"level":\s*1`) call("la_pins", nil) call("sensor_set", map[string]any{"instance": "env", "values": map[string]any{"temperature_c": 30}}) - expect(call("uart_read", map[string]any{"until_regex": "EVT alarm clear=overtemp", "timeout": 3}), `"matched":\s*true`) + expect(call("uart_read", map[string]any{"until_regex": "EVT alarm clear=overtemp", "timeout_s": 3}), `"matched":\s*true`) // Story 4: "set the room temperature to 30 degC and see if the thermostat turns the heater // on": PA1 is the process sensor (0.5 V + 20 mV/degC) driven by the pod's 3.3 V DAC, PA4 the @@ -127,12 +127,12 @@ func TestMCPEndToEnd(t *testing.T) { call("dac_output", map[string]any{"path": "3v3", "volts": 0.5 + 0.02*30}) time.Sleep(100 * time.Millisecond) // the node samples PA1 every 10 ms call("uart_write", map[string]any{"text": "ctl on 40"}) - expect(call("uart_read", map[string]any{"until_regex": `CTL mode=on[^\r]*\r\n`, "timeout": 3}), `pv_c=30\.0`) + expect(call("uart_read", map[string]any{"until_regex": `CTL mode=on[^\r]*\r\n`, "timeout_s": 3}), `pv_c=30\.0`) time.Sleep(3 * time.Second) expect(call("adc_read", map[string]any{"source": "ext"}), `"voltage":\s*[1-3]\.`) expect(call("capture_adc", map[string]any{"samples": 4096, "source": "ext"}), `"mean":\s*[1-3]\.`) call("uart_write", map[string]any{"text": "ctl off"}) - call("uart_read", map[string]any{"until_regex": "CTL mode=off", "timeout": 3}) + call("uart_read", map[string]any{"until_regex": "CTL mode=off", "timeout_s": 3}) call("uart_close", nil) // Story 5: "capture the I2C bus". @@ -145,17 +145,17 @@ func TestMCPEndToEnd(t *testing.T) { // The boot log on the logic analyzer: power on 0.5 s out, trigger on the first start bit. call("power_off", nil) - call("power_on", map[string]any{"delay": 0.5}) + call("power_on", map[string]any{"delay_s": 0.5}) call("capture_la", map[string]any{"samples": 100000, "sample_rate_hz": 2e6, "trigger_la": "uart_rx", "trigger_edge": "falling"}) expect(call("decode_la", map[string]any{"protocol": "uart", "rx": 3, "baud": 115200}), `PROCESS-NODE`) // Story 6: "measure the board's current". time.Sleep(time.Second) - expect(call("measure_power", map[string]any{"duration": 1.0, "points": 20}), `"avg_current":\s*0\.04`) + expect(call("measure_power", map[string]any{"duration_s": 1.0, "points": 20}), `"avg_current":\s*0\.04`) // The rest of the allow-list. call("reset_target", nil) - expect(call("capture_uart", map[string]any{"duration": 2.0, "until_regex": "APP_OK"}), `reset=pin`) + expect(call("capture_uart", map[string]any{"duration_s": 2.0, "until_regex": "APP_OK"}), `reset=pin`) call("generate", map[string]any{"waveform": "sine", "freq_hz": 50, "amplitude": 0.5, "offset": 1.5}) call("dac_stop", nil) expect(call("sensor_stop", nil), `"env"`) diff --git a/benchsim/firmware.go b/benchsim/firmware.go index 3d00b64..4391bf4 100644 --- a/benchsim/firmware.go +++ b/benchsim/firmware.go @@ -63,7 +63,6 @@ func init() { "capture": {0, flagAnalog | flagStream | flagHeavy, nil, (*Sim).cmdCapture}, "capture_dual": {0, flagStream | flagHeavy, nil, (*Sim).cmdCaptureDual}, "capture_read": {0, flagStream | flagHeavy, nil, (*Sim).cmdCaptureRead}, - "stream": {0, flagAnalog | flagStream | flagHeavy, nil, (*Sim).cmdCapture}, "la_capture": {0, flagStream | flagHeavy, nil, (*Sim).cmdLaCapture}, "sensor_la": {0, flagStream | flagHeavy, nil, (*Sim).cmdSensorLa}, "can_read": {0, flagNoHW | flagHeavy, simple((*Sim).cmdCanRead), nil}, @@ -74,11 +73,11 @@ func init() { "eth": {0, flagNoHW | flagMixed, nil, nil}, "sig_policy": {0, flagMixed, (*Sim).cmdSigPolicy, nil}, "lan_policy": {0, flagMixed, (*Sim).cmdLanPolicy, nil}, - "usb_network": {0, flagMixed, nil, nil}, + "usb_network": {0, flagMixed, (*Sim).cmdUsbNetwork, nil}, "module": {0, flagNoHW | flagMixed, nil, nil}, "cloud_ca": {0, flagMixed, (*Sim).cmdCloudCa, nil}, "cloud_proxy": {0, flagMixed, (*Sim).cmdCloudProxy, nil}, - "lan_tls": {0, flagMixed, nil, nil}, + "lan_tls": {0, flagMixed, (*Sim).cmdLanTLS, nil}, "generate": {1, flagAnalog, (*Sim).cmdGenerateFw, nil}, "measure": {1, flagAnalog | flagStream, nil, nil}, "load": {1, flagAnalog | flagStream, nil, nil}, @@ -95,7 +94,8 @@ func init() { "adc_range": {1, flagAnalog, simple((*Sim).cmdAdcRange), nil}, "dac_control_loop": {1, flagAnalog, (*Sim).cmdControlLoop, nil}, "dac_loop_input": {1, flagAnalog, (*Sim).cmdLoopInput, nil}, - "la": {1, 0, simple((*Sim).cmdLa), nil}, + "la_step": {1, 0, simple((*Sim).cmdLaStep), nil}, + "la_pull": {1, 0, simple((*Sim).cmdLaPull), nil}, "gpio": {1, 0, simple((*Sim).cmdGpio), nil}, "la_voltage": {1, flagNoHW, simple((*Sim).cmdLaVoltage), nil}, "nrst": {1, flagNoHW, simple((*Sim).cmdNrst), nil}, @@ -118,11 +118,11 @@ func init() { "sensor_stimulus": {1, 0, simple((*Sim).cmdSensorStimulus), nil}, "sensor_stimulus_start": {1, 0, simple((*Sim).cmdSensorStimulusStart), nil}, "sensor_stimulus_stop": {1, 0, simple((*Sim).cmdSensorStimulusStop), nil}, - "can_config": {1, flagNoHW, simple((*Sim).cmdCanConfig), nil}, + "can_start": {1, flagNoHW, simple((*Sim).cmdCanStart), nil}, "can_write": {1, flagNoHW, simple((*Sim).cmdCanWrite), nil}, "can_term": {1, flagNoHW, simple((*Sim).cmdCanTerm), nil}, "can_respond": {1, flagNoHW, simple((*Sim).cmdCanRespond), nil}, - "can_disable": {1, flagNoHW, simple((*Sim).cmdCanDisable), nil}, + "can_stop": {1, flagNoHW, simple((*Sim).cmdCanStop), nil}, "speedtest": {1, flagNoHW | flagStream, nil, nil}, "fpga_image": {1, 0, (*Sim).cmdFpgaImage, nil}, "psram_recover": {1, 0, simple((*Sim).cmdPsramRecover), nil}, @@ -146,13 +146,17 @@ func mixedWrite(cmd string, r request) bool { case "dac_limits": return r.has("path") || (r.has("enabled") && r.str("enabled") == "false") case "calibrate": - return r.has("source") || r.has("dac") || r.has("adc") || notFalse("clear") - case "sig_policy", "lan_policy", "usb_network": + return r.has("source") || r.has("dac") || r.has("adc") || r.has("comp_hf_dc_e4") || notFalse("clear") + case "sig_policy": + return r.has("set") || notFalse("clear_floor") + case "lan_policy": return r.has("set") + case "usb_network": + return r.has("enabled") case "cloud_ca", "cloud_proxy": return r.has("set") || r.str("clear") == "true" case "lan_tls": - return r.has("https_only") || r.str("regenerate") == "true" + return r.has("https_only") || r.has("scpi") || r.str("regenerate") == "true" case "module": return r.has("eeprom") && r.str("eeprom") != "read" case "eth": @@ -195,7 +199,12 @@ func (s *Sim) fwDispatch(c *conn, r request) { } fail := func(err error) { note(err) - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) + } + // A client older than min_client_api is refused first, before every other gate. + if err := clientAPIGate(cmd, r); err != nil { + fail(err) + return } s.mu.Lock() lanPolicy := s.flash.lanPolicy @@ -203,7 +212,7 @@ func (s *Sim) fwDispatch(c *conn, r request) { s.mu.Unlock() if !c.cloud { if tier >= 2 && lanPolicy != "open" { - fail(errf("locked: %s needs the cloud or USB", cmd)) + fail(coded(codeLanLocked, "cmd", cmd)) return } light := known && row.flags&flagHeavy == 0 && tier == 0 @@ -211,12 +220,12 @@ func (s *Sim) fwDispatch(c *conn, r request) { if holder == "" { holder = "cloud" } - fail(errf("busy: a cloud job holds this pod (%s, %d s left)", holder, left)) + fail(coded(codeLeaseBusy, "holder", "a cloud job", "purpose", holder, "left_s", left)) return } } if c.maxTier >= 0 && tier > c.maxTier { - fail(errf("forbidden: %s needs an organization owner or admin", cmd)) + fail(coded(codeRoleRequired, "cmd", cmd)) return } if c.single && row.flags&flagStream != 0 { @@ -247,14 +256,14 @@ func (s *Sim) fwDispatch(c *conn, r request) { } switch { case !known: - fail(fwError("unknown cmd")) + fail(coded(codeUnknownCommand, "cmd", cmd)) case row.raw != nil: note(row.raw(s, c, r)) case row.fn != nil: data, err := row.fn(s, c, r) note(err) if err != nil { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return } _ = c.send(okReply(data)) @@ -318,6 +327,11 @@ func (s *Sim) serveStream(c net.Conn, cloud bool, maxTier int) { continue } if t := bytes.TrimLeft(line, " \t"); t[0] != '{' { + if !s.scpiOn() { + // SCPI is off (the 4.0.0 default): one line, then the connection closes. + _, _ = cn.Write([]byte("SCPI is off on this BenchPod: switch it on over USB or from the cloud (console: lan-tls scpi on)\n")) + return + } s.scpiLine(cn, string(t)) continue } @@ -341,6 +355,12 @@ func (s *Sim) scpiLine(c *conn, line string) { } } +func (s *Sim) scpiOn() bool { + s.mu.Lock() + defer s.mu.Unlock() + return s.flash.scpi +} + func (s *Sim) firmwareVersion() string { s.mu.Lock() defer s.mu.Unlock() @@ -370,8 +390,24 @@ func (b *bufConn) SetReadDeadline(time.Time) error { return nil } func (b *bufConn) SetWriteDeadline(time.Time) error { return nil } // Exec runs one command as a single-reply caller: over the cloud command channel (cloud true, -// streaming verbs refused) or as a LAN client. The data is the reply's data, or errMsg its refusal. +// streaming verbs refused) or as a LAN client. The data is the reply's data, or errMsg its refusal: +// the message, or the code ("BP0031") of a coded one, as the cloud envelope's "error" carries it. func (s *Sim) Exec(req map[string]any, cloud bool) (data json.RawMessage, errMsg string) { + r := s.ExecReply(req, cloud) + return r.Data, r.Error +} + +// Reply is one command's single reply: Data when it ran, else Error (the message, or the code +// when there is none) with Code and Args for a coded refusal. +type Reply struct { + Data json.RawMessage + Error string + Code string + Args map[string]any +} + +// ExecReply is Exec with the refusal's code and args, for the cloud envelope. +func (s *Sim) ExecReply(req map[string]any, cloud bool) Reply { s.mu.Lock() cn := s.cmdConn s.mu.Unlock() @@ -385,21 +421,27 @@ func (s *Sim) Exec(req map[string]any, cloud bool) (data json.RawMessage, errMsg var r struct { Status string `json:"status"` Message string `json:"message"` + Code string `json:"code"` + Args map[string]any `json:"args"` Data json.RawMessage `json:"data"` } if json.Unmarshal(line, &r) != nil { - return nil, "reply too large for the cloud channel" + return Reply{Error: "BP0054", Code: "BP0054", Args: map[string]any{"bytes": len(line), "limit": 1791}} } if r.Status == "error" { - return nil, r.Message + msg := r.Message + if msg == "" { + msg = r.Code + } + return Reply{Error: msg, Code: r.Code, Args: r.Args} } - return r.Data, "" + return Reply{Data: r.Data} } // heavyBegin is heavy_begin: one owner of the capture hardware at a time. Callers hold s.mu. func (s *Sim) heavyBegin(c *conn) error { if s.heavyInFlight() || (s.pod.heavy != nil && s.pod.heavy != c.heavyKey()) { - return fwError("busy") + return coded(codePodBusy) } s.pod.heavy = c.heavyKey() return nil @@ -442,19 +484,21 @@ func (s *Sim) fwStatus(c *conn, _ request) (any, error) { out := map[string]any{ "device": "benchpod", "version": version, "board": podBoard, "net": "connected", "ip": "127.0.0.1", "rssi_dbm": nil, "wifi": "off", "cloud": s.cloudState(), - "usb": map[string]any{"net": "off", "setting": "on", "off_reason": "wifi", "link": false, "ip": "", "host_ip": "", "source": "3.0A", "source_ma": 3000}, + "usb": map[string]any{"net": false, "enabled": s.flash.usbNet, "off_reason": "wifi", "link": false, "ip": "", + "host_ip": "", "source": "3.0A", "source_ma": 3000}, "rx_dropped": 0, "tx_dropped": 0, "adc_bits": 16, "adc_fullscale_mv": 4096, "adc_channels": 1, "la_vccio_mv": s.pod.laMV, "board_rev": "v3", "board_rev_mv": 1650, "nrst_pin": true, "flash_kb": 2048, - "ota_sig": true, "sig_policy": s.flash.sigPolicy, "sig_keys": 1, "sig_policy_cmd": true, - "lan_policy": s.flash.lanPolicy, "lan_policy_cmd": true, "tunnel_max_tier": true, "lease_state": true, - "cloud_ca": true, "cloud_proxy": true, - "lan_tls": map[string]any{"port": 8443, "https_only": false, "sha256": ""}, + "sig_policy": s.flash.sigPolicy, "sig_keys": 1, "lan_policy": s.flash.lanPolicy, + "lan_tls": map[string]any{"port": 8443, "https_only": !s.flash.httpsOff, "scpi": s.flash.scpi, "sha256": ""}, "lease": map[string]any{"held": held, "holder": holder, "left_s": left}, + "local_lease": map[string]any{"held": false}, "gateware": podGateware, "gateware_embedded": podGateware, "loop_tripped": s.loopTripped(), "uart_rx_overflow": false, "psram": "ok", "psram_ok": true, "heap_free": 120000, "heap_min": 90000, "stack_min": 800, "reset": "power-on", "last_crash": "none", "stacks": map[string]any{}, "analog": true, - "safe_mode": false, "safe_reason": "", "caps": s.capsList(), "sensors_format": 1, "sensors_digital": true, + "safe_mode": false, "safe_reason": "", "sensors_digital": true, + "features_rev": featuresRev, "api": apiLevel, "min_client_api": minClientAPI, + "fpga_image": fpgaImageName(s.pod.image), "hw": podHW, } if !c.single { out["adc_cal_a_uv"] = int64(math.Round(adcCalA * 1e6)) @@ -475,22 +519,6 @@ func (s *Sim) cloudState() string { func adcFullscaleMv() int64 { return int64(math.Round(math.Abs(adcCalB) * 32768 * 1000)) } -// capsList is cloud_caps_emit_list for an analog board on the running gateware image. -func (s *Sim) capsList() []string { - caps := []string{"signal", "gpio", "power", "swd", "uart", "la", "analyzer", "command", - "tunnel", "ota", "la_pins", "power_profile", "capture_b64", "can", "sensors", "usb_net", - "usb_net_setting", "lan_tls", "wifi_scan", "pod_current", "analog", "scope", "dac_limits", "calibrate", - "cal_dmm", "current_out", "dac", "dac_dc", "dac_replay"} - switch s.pod.image { - case 0: - caps = append(caps, "dac_control_loop") - case 1: - caps = append(caps, "dac_deep_replay") - } - return append(caps, "dac_cotrig", "generate16", "dac_loop_sources", "dac_loop_input_map", "gpio_read", - "capture_trigger", "spi_master", "spi_stream", "nrst_pin", "usb_cc") -} - // Capabilities is the firmware's capabilities frame (cloud_caps.c), without device_id and the // boot health the link side adds. func (s *Sim) Capabilities() map[string]any { @@ -500,27 +528,24 @@ func (s *Sim) Capabilities() map[string]any { if version == "" { version = podFirmware } - deep := s.pod.image == 1 maxSamples := 2048 - if deep { + if s.pod.image == 1 { maxSamples = 4 << 20 } + // Firmware 4.0.0 sends no per-feature flags: the server looks the features up from + // features_rev, the gateware, the image and the facts. What is left are values. return map[string]any{ - "firmware_version": version, "ota": true, "flash_kb": 2048, "blob_slots": true, "ota_sig": true, - "sig_policy": s.flash.sigPolicy, "sig_policy_cmd": true, "ws_auth_v2": true, "lease_state": true, - "cloud_ca": true, "cloud_proxy": true, "lan_policy": s.flash.lanPolicy, "lan_policy_cmd": true, - "tunnel_max_tier": true, "lan_tls": true, "wifi_scan": true, "serial": false, "scope": true, "analog": true, - "analyzer": true, "command": true, "tunnel": true, "adc_bits": 16, "adc_fullscale_mv": 4096, "adc_channels": 1, + "firmware_version": version, "flash_kb": 2048, "sig_policy": s.flash.sigPolicy, "ws_auth_v2": true, + "lan_policy": s.flash.lanPolicy, "features_rev": featuresRev, "api": apiLevel, "min_client_api": minClientAPI, + "gateware_version": podGateware, "fpga_image": fpgaImageName(s.pod.image), + "analog": true, "nrst_pin": true, "sensors_digital": true, "wifi_scan": true, "pod_current": true, + "adc_low_range": false, "adc_bits": 16, "adc_fullscale_mv": 4096, "adc_channels": 1, "adc_cal_a_uv": int64(math.Round(adcCalA * 1e6)), "adc_cal_b_nv": int64(math.Round(adcCalB * 1e9)), - "adc_cal_unwrap": true, "adc_low_range": false, "adc_range": "normal", "adc_range_fs_mv": adcFullscaleMv(), - "dac": true, "dac_replay": true, "dac_dc": true, "dac_bits": 8, "dac_replay_bits": 16, - "dac_fullscale_mv": 4096, "dac_channels": 1, "dac_deep_replay": deep, "dac_replay_max_samples": maxSamples, - "dac_control_loop": s.pod.image == 0, "dac_loop_sources": true, "dac_loop_input_map": true, "dac_cotrig": true, - "generate_bits": 16, "la_pins": true, "gpio_read": true, "capture_trigger": true, "spi_master": true, - "spi_stream": true, "nrst_pin": true, "power_profile": true, "capture_b64": true, "dac_limits": true, - "calibrate": true, "cal_dmm": true, "can": true, "pod_current": true, "current_out": true, - "current_out_min_ua": currentOutUa(0), "current_out_max_ua": currentOutUa(0xFFFF), "sensors": true, - "sensors_format": 1, "sensors_digital": true, "board": podBoard, "uplink": "eth", + "adc_cal_unwrap": true, "adc_range": "normal", "adc_range_fs_mv": adcFullscaleMv(), + "dac_bits": 8, "dac_replay_bits": 16, "dac_fullscale_mv": 4096, "dac_channels": 1, + "dac_replay_max_samples": maxSamples, "generate_bits": 16, "la_max_rate_hz": 48000000, + "current_out_min_ua": currentOutUa(0), "current_out_max_ua": currentOutUa(0xFFFF), + "board": podBoard, "uplink": "eth", } } diff --git a/benchsim/firmware_test.go b/benchsim/firmware_test.go index 988d002..2bbf73f 100644 --- a/benchsim/firmware_test.go +++ b/benchsim/firmware_test.go @@ -16,6 +16,7 @@ func TestFirmwareRebootThenDUTBootsAgain(t *testing.T) { for round := 0; round < 2; round++ { exec := func(cmd map[string]any) { t.Helper() + cmd["client_api"] = 2 if _, msg := s.Exec(cmd, true); msg != "" { t.Fatalf("%v: %s", cmd, msg) } @@ -23,13 +24,13 @@ func TestFirmwareRebootThenDUTBootsAgain(t *testing.T) { exec(map[string]any{"cmd": "la_voltage", "mv": float64(3300)}) here, there := net.Pipe() go s.ServeTunnel(there, 3) - line, _ := json.Marshal(map[string]any{"cmd": "uart_proxy_start", "rx": 3, "tx": 4, "baud": 115200}) + line, _ := json.Marshal(map[string]any{"cmd": "uart_proxy_start", "rx": 3, "tx": 4, "baud": 115200, "client_api": 2}) go here.Write(append(line, '\n')) br := bufio.NewReader(here) if _, err := br.ReadString('\n'); err != nil { t.Fatal(err) } - exec(map[string]any{"cmd": "target_power", "efuse": float64(1), "state": float64(1)}) + exec(map[string]any{"cmd": "target_power", "efuse": float64(1), "enabled": true}) seen := "" _ = here.SetReadDeadline(time.Now().Add(8 * time.Second)) for !strings.Contains(seen, "APP_OK") { @@ -44,3 +45,216 @@ func TestFirmwareRebootThenDUTBootsAgain(t *testing.T) { s.Reboot() } } + +// Firmware 4.0.0 refuses a client below client API 2 (BP0030, with a message) except on the +// verbs every client may send, and answers an unknown verb with BP0002. +func TestClientAPIGate(t *testing.T) { + s := New(WithFirmware("4.0.0", Hooks{})) + defer s.Close() + r := s.ExecReply(map[string]any{"cmd": "la_pins", "client_api": 1}, false) + if r.Code != "BP0030" || r.Args["client_api"] != 1.0 || r.Args["min_client_api"] != 2.0 || r.Args["api"] != 2.0 || + !strings.HasPrefix(r.Error, "Update the BenchPod SDK, MCP or CLI") { + t.Fatalf("old client: %+v", r) + } + if r := s.ExecReply(map[string]any{"cmd": "la_pins"}, false); r.Code != "BP0030" || r.Args["client_api"] != 0.0 { + t.Fatalf("no client_api: %+v", r) + } + for _, cmd := range []string{"status", "ping", "ota_status", "blob_status"} { + if r := s.ExecReply(map[string]any{"cmd": cmd}, false); r.Code == "BP0030" { + t.Fatalf("%s refused for an old client: %+v", cmd, r) + } + } + if r := s.ExecReply(map[string]any{"cmd": "frobnicate"}, false); r.Code != "BP0030" { + t.Fatalf("unknown verb from an old client: %+v", r) + } + r = s.ExecReply(map[string]any{"cmd": "frobnicate", "client_api": 2}, false) + if r.Code != "BP0002" || r.Error != "BP0002" || r.Args["cmd"] != "frobnicate" { + t.Fatalf("unknown verb: %+v", r) + } + if r := s.ExecReply(map[string]any{"cmd": "la_pins", "client_api": 2}, false); r.Error != "" { + t.Fatalf("la_pins: %+v", r) + } +} + +// The 4.0.0 names: rates in Hz (sample_rate_hz, adc_sample_rate_hz, la_sample_rate_hz), base64 +// ADC samples by default, and no stream verb. +func TestCaptureNames(t *testing.T) { + _, addr := startSim(t, WithFirmware("4.0.0", Hooks{}), WithLaVoltage(3300)) + fs := frames(t, addr, map[string]any{"cmd": "capture_dual", "adc_samples": 300, "adc_sample_rate_hz": 200000, + "la_samples": 400, "la_sample_rate_hz": 1e6}) + if fs[0]["adc_sample_rate_hz"] != 200000.0 || fs[0]["la_sample_rate_hz"] != 1e6 || fs[0]["b64"] == nil { + t.Fatalf("first frame: %v", fs[0]) + } + var la map[string]any + for _, f := range fs { + if f["la"] == true { + la = f + break + } + } + if la == nil || la["la_sample_rate_hz"] != 1e6 { + t.Fatalf("no LA frame with its rate: %v", fs) + } + if fs := frames(t, addr, map[string]any{"cmd": "capture_read", "offset": 0, "enc": "dec"}); fs[0]["data"] == nil { + t.Fatalf("capture_read enc dec: %v", fs[0]) + } + if msg := refused(t, addr, map[string]any{"cmd": "stream", "samples": 100}); msg != "BP0002 cmd=stream" { + t.Fatal(msg) + } + if msg := refused(t, addr, map[string]any{"cmd": "capture", "samples": 40000}); msg != "BP0067 max=32768" { + t.Fatal(msg) + } +} + +// The 4.0.0 field names of SPI, power_profile, dac_out, the loop and CAN. +func TestRenamedFields(t *testing.T) { + _, addr := startSim(t, WithFirmware("4.0.0", Hooks{}), WithLaVoltage(3300)) + spi := ok(t, addr, map[string]any{"cmd": "spi_start", "sck": 10, "mosi": 11, "miso": 12, "cs": 13, "clock_hz": 1000000}).(map[string]any) + if spi["clock_hz"] != 1e6 || spi["hz"] != nil { + t.Fatalf("spi_start: %v", spi) + } + if st := ok(t, addr, map[string]any{"cmd": "spi_status"}).(map[string]any); st["clock_hz"] != 1e6 { + t.Fatalf("spi_status: %v", st) + } + ok(t, addr, map[string]any{"cmd": "spi_stop"}) + out := ok(t, addr, map[string]any{"cmd": "dac_out", "path": "3v3", "v": 1.5}).(map[string]any) + if mv := out["mv"].(float64); mv < 1495 || mv > 1505 || out["code16"] == nil || out["code"] != nil { + t.Fatalf("dac_out: %v", out) + } + if p := ok(t, addr, map[string]any{"cmd": "dac_loop_probe"}).(map[string]any); p["code16"] == nil || p["v"] != nil { + t.Fatalf("dac_loop_probe: %v", p) + } + fs := frames(t, addr, map[string]any{"cmd": "power_profile", "action": "start", "efuse": 1, "sample_rate_hz": 200}) + if fs[0]["data"].(map[string]any)["sample_rate_hz"] != 200.0 { + t.Fatalf("power_profile start: %v", fs[0]) + } + frames(t, addr, map[string]any{"cmd": "power_profile", "action": "stop"}) + if msg := refused(t, addr, map[string]any{"cmd": "power_profile", "action": "start", "sample_rate_hz": 1000}); msg != "sample_rate_hz must be 100..500" { + t.Fatal(msg) + } + ok(t, addr, map[string]any{"cmd": "can_start", "bitrate": 500000}) + ok(t, addr, map[string]any{"cmd": "can_stop"}) + for _, old := range []string{"can_config", "can_disable", "la"} { + if msg := refused(t, addr, map[string]any{"cmd": old}); msg != "BP0002 cmd="+old { + t.Fatalf("%s: %s", old, msg) + } + } +} + +// la_pull and la_step replace la; target_power, target_status and la_pull use booleans. +func TestLaPullAndBooleans(t *testing.T) { + _, addr := startSim(t, WithFirmware("4.0.0", Hooks{})) + if msg := refused(t, addr, map[string]any{"cmd": "la_pull"}); msg != "BP0001" { + t.Fatal(msg) + } + ok(t, addr, map[string]any{"cmd": "la_voltage", "mv": 1800}) + p := ok(t, addr, map[string]any{"cmd": "la_pull", "la": 3, "pull": "up"}).(map[string]any) + if p["state"] != "up" || p["pullups_available"] != true || p["pullup"] != nil || p["ohms"] != nil || p["pull"] != nil || + len(p["dirs"].([]any)) != 1 { + t.Fatalf("la_pull set: %v", p) + } + if m := ok(t, addr, map[string]any{"cmd": "la_pull"}).(map[string]any); m["la_pullup_mask"] != 4.0 || m["pullups_available"] != true { + t.Fatalf("la_pull mask: %v", m) + } + if msg := refused(t, addr, map[string]any{"cmd": "la_pull", "la": 7, "pull": "up"}); msg != "BP0024 have=down la=7 want=up" { + t.Fatal(msg) + } + if msg := refused(t, addr, map[string]any{"cmd": "la_pull", "la": 9, "pull": "up"}); msg != "BP0023 la=9" { + t.Fatal(msg) + } + if q := ok(t, addr, map[string]any{"cmd": "la_pull", "la": 3, "pullup": "off"}).(map[string]any); q["state"] != "up" { + t.Fatalf("pullup is not read any more: %v", q) + } + if msg := refused(t, addr, map[string]any{"cmd": "la_step", "la": 5}); msg != "missing steps" { + t.Fatal(msg) + } + if msg := refused(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "state": 1}); msg != "enabled must be true or false" { + t.Fatal(msg) + } + tp := ok(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "enabled": true}).(map[string]any) + if tp["enabled"] != true { + t.Fatalf("target_power: %v", tp) + } + e1 := ok(t, addr, map[string]any{"cmd": "target_status"}).(map[string]any)["efuse1"].(map[string]any) + if e1["enabled"] != true || e1["fault"] != false || e1["valid"] != true || e1["flt_pin"] != 0.0 { + t.Fatalf("target_status: %v", e1) + } +} + +// generate takes only volts on a path or microamps (no 8-bit amplitude/offset), freq_hz, and +// replies null or {"cotrig":bool}. +func TestGenerateForms(t *testing.T) { + for _, fw := range []bool{true, false} { + var opts []Option + if fw { + opts = append(opts, WithFirmware("4.0.0", Hooks{})) + } + _, addr := startSim(t, opts...) + msg := refused(t, addr, map[string]any{"cmd": "generate", "waveform": "sine", "freq_hz": 100, "amplitude": 100, "offset": 128}) + if msg != "amplitude_v (with path and offset_v) or amplitude_ua (with offset_ua) is required" { + t.Fatalf("firmware %v: 8-bit form: %s", fw, msg) + } + req := map[string]any{"cmd": "generate", "waveform": "sine", "freq_hz": 100, "path": "3v3", "amplitude_v": 1, "offset_v": 1.65} + if d := ok(t, addr, req); d != nil { + t.Fatalf("firmware %v: generate: %v", fw, d) + } + req["on_capture"] = true + if d, _ := ok(t, addr, req).(map[string]any); d == nil || d["cotrig"] == nil || d["bits"] != nil { + t.Fatalf("firmware %v: generate on_capture: %v", fw, d) + } + ok(t, addr, map[string]any{"cmd": "dac_stop"}) + } +} + +// Signatures are always required, the LAN cannot change lan_tls or usb_network, and SCPI is off +// until the cloud switches it on. +func TestPolicies(t *testing.T) { + s, addr := startSim(t, WithFirmware("4.0.0", Hooks{})) + sp := ok(t, addr, map[string]any{"cmd": "sig_policy", "set": "required"}).(map[string]any) + if sp["policy"] != "required" || sp["lan_unsigned"] != nil { + t.Fatalf("sig_policy: %v", sp) + } + for _, want := range []string{"audit", "permissive"} { + r := s.ExecReply(map[string]any{"cmd": "sig_policy", "set": want, "client_api": 2}, true) + if r.Code != "BP0074" || r.Args["setting"] != "sig_policy" || r.Args["want"] != want { + t.Fatalf("sig_policy %s from the cloud: %+v", want, r) + } + } + tls := ok(t, addr, map[string]any{"cmd": "lan_tls"}).(map[string]any) + if tls["https_only"] != true || tls["scpi"] != false { + t.Fatalf("lan_tls defaults: %v", tls) + } + if msg := refused(t, addr, map[string]any{"cmd": "lan_tls", "scpi": true}); msg != "BP0042 setting=lan_tls" { + t.Fatal(msg) + } + if msg := refused(t, addr, map[string]any{"cmd": "usb_network", "enabled": false}); msg != "BP0043 setting=usb_network" { + t.Fatal(msg) + } + if u := ok(t, addr, map[string]any{"cmd": "usb_network"}).(map[string]any); u["enabled"] != true { + t.Fatalf("usb_network: %v", u) + } + st := ok(t, addr, map[string]any{"cmd": "status"}).(map[string]any) + if usb := st["usb"].(map[string]any); usb["net"] != false || usb["enabled"] != true { + t.Fatalf("status.usb: %v", usb) + } + scpi := func() string { + c, err := net.Dial("tcp", addr) + if err != nil { + t.Fatal(err) + } + defer c.Close() + _ = c.SetDeadline(time.Now().Add(5 * time.Second)) + _, _ = c.Write([]byte("*IDN?\n")) + line, _ := bufio.NewReader(c).ReadString('\n') + return line + } + if line := scpi(); !strings.HasPrefix(line, "SCPI is off on this BenchPod") { + t.Fatalf("SCPI off: %q", line) + } + if r := s.ExecReply(map[string]any{"cmd": "lan_tls", "scpi": true, "client_api": 2}, true); r.Error != "" { + t.Fatalf("lan_tls scpi from the cloud: %+v", r) + } + if line := scpi(); !strings.HasPrefix(line, "EmbeddedCI,BenchPod,0,4.0.0") { + t.Fatalf("SCPI on: %q", line) + } +} diff --git a/benchsim/pins.go b/benchsim/pins.go index f3fae97..032ccce 100644 --- a/benchsim/pins.go +++ b/benchsim/pins.go @@ -1,7 +1,6 @@ package benchsim import ( - "fmt" "sort" ) @@ -18,27 +17,34 @@ var pullOhms = map[int]string{1: "4.7k", 2: "4.7k", 3: "2.2k", 4: "2.2k", 5: "10 func pullDown(la int) bool { return la == 7 || la == 8 } -// releaseHint is the firmware's "how to free it" text for a pin conflict. -func (s *Sim) releaseHint(la int) string { - if on := s.sensorsOn(la); len(on) > 0 { - return fmt.Sprintf(`stop the sensor emulation first ({"cmd":"sensor_stop","instance":"%s"})`, on[0].name) +func (s *Sim) requireLaVoltage() error { + if s.pod.laMV == 0 { + return coded(codeLaVoltageNotSet) } - switch fn := s.pod.pins[la].fn; fn { - case "gpio": - return fmt.Sprintf(`release it with {"cmd":"gpio","la":%d,"mode":"off"}`, la) - case "uart_rx", "uart_tx": - return "stop the uart proxy first" - case "spi_sck", "spi_mosi", "spi_miso", "spi_cs": - return `stop the SPI session first ({"cmd":"spi_stop"})` + return nil +} + +// pinInUse is BP0031 for a pin another function holds: owner is "gpio" or "sensor:env (i2c_sda)". +func (s *Sim) pinInUse(la int) error { + inst := "" + if on := s.sensorsOn(la); len(on) > 0 { + inst = on[0].name } - return "" + return coded(codeLaPinInUse, "la", la, "owner", s.pinOwnerText(la), "function", s.pod.pins[la].fn, "instance", inst) } -func (s *Sim) requireLaVoltage() error { - if s.pod.laMV == 0 { - return fwError("la voltage not set; set it with la_voltage (mv 1800 or 3300) first") +// noPullDown is why a function cannot share its line with an engaged pull-down (fn_attr's +// no_pull_down), "" when it can. +func noPullDown(fn string) string { + switch fn { + case "uart_rx", "uart_tx", "sensor_tx", "sensor_rx": + return "the line idles high" + case "i2c_sda", "i2c_scl": + return "an open-drain bus needs pull-ups" + case "gpio open_drain": + return "a released line would read low" } - return nil + return "" } // claim checks that every channel is free (or already owned by one of the replaceable @@ -54,14 +60,11 @@ func (s *Sim) checkClaim(fn string, las []int, replaceable ...string) error { free = free || owner == r } if !free { - return errf("pin conflict: LA%d is in use by %s; %s", la, s.pinOwnerText(la), s.releaseHint(la)) + return s.pinInUse(la) } if pullDown(la) && s.pod.pulls&(1<<(la-1)) != 0 { - switch fn { - case "uart_rx", "uart_tx": - return errf("pull conflict: LA%d has its 10k pull-down engaged, which %s can't work with (the line idles high); disable it first", la, fn) - case "i2c_sda", "i2c_scl": - return errf("pull conflict: LA%d has its 10k pull-down engaged, which %s can't work with (an open-drain bus needs pull-ups); disable it first", la, fn) + if why := noPullDown(fn); why != "" { + return coded(codeLaPullDownEngaged, "la", la, "ohms", pullOhms[la], "function", fn, "reason", why) } } } @@ -95,7 +98,7 @@ func (s *Sim) pinEntry(la int) map[string]any { if pullDown(la) { dir = "down" } - e["pull"] = map[string]any{"dir": dir, "ohms": ohms, "on": s.pod.pulls&(1<<(la-1)) != 0} + e["pull"] = map[string]any{"dir": dir, "ohms": ohms, "on": s.pod.pulls&(1<<(la-1)) != 0, "dirs": []string{dir}} } return e } @@ -183,7 +186,8 @@ func (s *Sim) cmdGpio(r request) (any, error) { } for _, la := range las { if mode == "open_drain" && pullDown(la) && s.pod.pulls&(1<<(la-1)) != 0 { - return nil, errf("pull conflict: LA%d has its 10k pull-down engaged, which gpio open_drain can't work with (a released line would read low); disable it first", la) + return nil, coded(codeLaPullDownEngaged, "la", la, "ohms", pullOhms[la], "function", "gpio open_drain", + "reason", noPullDown("gpio open_drain")) } } lv := level @@ -214,52 +218,85 @@ func (s *Sim) cmdGpio(r request) (any, error) { return map[string]any{"pins": s.pinList(las)}, nil } -// cmdLa is the pull-resistor half of the firmware's `la` command (the step-train form is not -// simulated). -func (s *Sim) cmdLa(r request) (any, error) { +// cmdLaStep is la_step: a step pulse train (firmware up to 3.10.13: la with steps). The +// simulator checks the request and does not run the train. +func (s *Sim) cmdLaStep(r request) (any, error) { s.mu.Lock() defer s.mu.Unlock() if err := s.requireLaVoltage(); err != nil { return nil, err } - if r.has("steps") { - return nil, notInDemo("la step trains") + if !r.has("steps") { + return nil, fwError("missing steps") + } + if s.firmware { + return nil, fwError("la_step is not modeled by the simulator") + } + return nil, notInDemo("la_step") +} + +// pullDirs is every way LA la can pull: this board has one fixed resistor per channel on LA1-LA8. +func pullDirs(la int) []string { + switch { + case la < 1 || la > 8: + return []string{} + case pullDown(la): + return []string{"down"} + } + return []string{"up"} +} + +// cmdLaPull is la_pull (firmware up to 3.10.13: la without steps): the pull bitmask without +// "la", a channel's pull state with it, and "pull" up, down or off switches it first. +func (s *Sim) cmdLaPull(r request) (any, error) { + s.mu.Lock() + defer s.mu.Unlock() + if err := s.requireLaVoltage(); err != nil { + return nil, err } - avail := b2i(s.pod.laMV == 3300) + avail := s.pod.laMV != 0 if !r.has("la") { return map[string]any{"la_pullup_mask": s.pod.pulls, "pullups_available": avail}, nil } la := r.int("la", 0) - if la < 1 || la > 8 { - return nil, fwError("no pull-up on this la") - } - if r.has("pullup") { - v := r.str("pullup") - on := v == "on" || v == "1" || v == "true" - if on { - if s.pod.laMV != 3300 { - return nil, fwError("pull-ups are 3V3-referenced; not available with the LA bank at 1.8 V") + if la < 1 || la > 14 { + return nil, errf("LA%d is not a pin (use 1..14)", max(la, 0)) + } + dirs := pullDirs(la) + if r.has("pull") { + want := r.str("pull") + if want != "up" && want != "down" && want != "off" { + return nil, fwError("pull must be up, down or off") + } + if want != "off" { + if len(dirs) == 0 { + return nil, coded(codeLaNoPull, "la", la) } - if pullDown(la) { - switch fn := s.pod.pins[la].fn; fn { - case "uart_rx", "uart_tx", "i2c_sda", "i2c_scl", "sensor_tx", "sensor_rx": - return nil, errf("pull conflict: LA%d is used by %s, which can't work with the 10k pull-down (stop it first)", la, fn) + if want != dirs[0] { + return nil, coded(codeLaPullDirection, "la", la, "want", want, "have", dirs[0]) + } + if want == "down" { + fn := s.pod.pins[la].fn + if fn == "gpio" && s.pod.pins[la].mode == "open_drain" { + fn = "gpio open_drain" + } + if why := noPullDown(fn); why != "" { + return nil, coded(codeLaPullDownConflict, "la", la, "ohms", pullOhms[la], "function", fn, "reason", why) } } s.pod.pulls |= 1 << (la - 1) - } else { + } else if len(dirs) > 0 { s.pod.pulls &^= 1 << (la - 1) } now := s.now() s.advance(now) s.touchBase(now) } - dir := "up" - if pullDown(la) { - dir = "down" + state := "off" + if len(dirs) > 0 && s.pod.pulls&(1<<(la-1)) != 0 { + state = dirs[0] } - return map[string]any{"la": la, "pullup": b2i(s.pod.pulls&(1<<(la-1)) != 0), "ohms": pullOhms[la], - "pull": dir, "pullups_available": avail}, nil + return map[string]any{"la": la, "state": state, "dirs": dirs, "pullups_available": avail}, nil } // baseWord is the idle level of every LA channel right now: what the DUT's pins, the pod's diff --git a/benchsim/pod.go b/benchsim/pod.go index ff1c6d1..1f51f89 100644 --- a/benchsim/pod.go +++ b/benchsim/pod.go @@ -1,14 +1,16 @@ package benchsim import ( + "fmt" "math" "sort" + "strings" "time" ) // What the simulated pod reports about itself: a rev3 analog BenchPod on current firmware. const ( - podFirmware = "3.10.3" + podFirmware = "4.0.0" podBoard = "stm32h563" podGateware = 54 // The front-SMA ADC fit (cal_data.h ADC_CAL_EXT): volts = a + b*count, 16-bit unwrapped. @@ -16,13 +18,22 @@ const ( adcCalB = -0.0010026443 ) -// podCaps is the caps[] list of status: the features the simulator implements. The SDK turns a -// missing flag into a clear "needs newer pod firmware" refusal, so leaving out what is not -// simulated (CAN, SPI, OTA, calibration, the 4-20 mA output) fails cleanly on the host. -var podCaps = []string{ - "scope", "la", "uart", "analog", "command", "dac", "dac_dc", "generate16", "la_pins", - "gpio_read", "capture_trigger", "power_profile", "capture_b64", "nrst_pin", "sensors", - "pod_current", +// podHW are the hardware facts status and the capabilities frame send (features.toml [facts]): +// clients look the pod's features up in the features table from features_rev, the gateware, the +// image and these. Firmware 4.0.0 sends no caps list. +var podHW = []string{"wifi", "usb_cc", "pod_current"} + +// fpgaImageName is the running gateware image as status and the capabilities frame name it. +func fpgaImageName(image int) string { + switch image { + case 0: + return "loop" + case 1: + return "deep" + case 2: + return "emu" + } + return "unknown" } type efuseState struct{ enabled, fault bool } @@ -74,16 +85,18 @@ type leaseState struct { // podFlash is what the firmware keeps in flash across a reset. type podFlash struct { lanPolicy, sigPolicy string - limits *dacLimits - proxyHost string - proxyPort int - proxyUser, proxyPass string - caCerts []map[string]any - calOffsetUV int64 - calSet bool - dacCal [3]*dacLine - adcGain [3]*float64 - chip spiFlashChip + // usbNet is usb_network enabled; httpsOff is lan_tls https_only false; scpi is lan_tls scpi. + usbNet, httpsOff, scpi bool + limits *dacLimits + proxyHost string + proxyPort int + proxyUser, proxyPass string + caCerts []map[string]any + calOffsetUV int64 + calSet bool + dacCal [3]*dacLine + adcGain [3]*float64 + chip spiFlashChip } func (p *podState) init() { @@ -147,11 +160,13 @@ func (s *Sim) cmdStatus(request) (any, error) { "adc_bits": 16, "adc_fullscale_mv": 4096, "adc_channels": 1, "la_vccio_mv": s.pod.laMV, "adc_cal_a_uv": int64(math.Round(adcCalA * 1e6)), "adc_cal_b_nv": int64(math.Round(adcCalB * 1e9)), "adc_cal_unwrap": true, "nrst_pin": true, "flash_kb": 2048, "analog": true, - "lan_policy": "open", "lan_policy_cmd": true, "lease_state": true, - "lease": map[string]any{"held": false, "holder": "", "left_s": 0}, - "gateware": podGateware, "gateware_embedded": podGateware, + "sig_policy": "required", "sig_keys": 1, "lan_policy": "open", + "lease": map[string]any{"held": false, "holder": "", "left_s": 0}, + "local_lease": map[string]any{"held": false}, + "gateware": podGateware, "gateware_embedded": podGateware, "uptime_ms": s.now() / 1e6, "reset": "power-on", "last_crash": "none", "safe_mode": false, - "caps": podCaps, "sensors_format": 1, "sensors_digital": true, + "sensors_digital": true, "features_rev": featuresRev, "api": apiLevel, "min_client_api": minClientAPI, + "fpga_image": fpgaImageName(s.pod.image), "hw": podHW, "simulator": "benchsim: a simulated BenchPod wired to a simulated NUCLEO-F446RE process node", }, nil } @@ -165,16 +180,18 @@ func (s *Sim) cmdLaVoltage(r request) (any, error) { return nil, fwError("la voltage must be 1800 or 3300 (mv)") } if mv != s.pod.laMV && s.pod.laMV != 0 { + var used []string for la := 1; la <= 14; la++ { if fn := s.pod.pins[la].fn; fn != "none" && fn != "gpio" { - return nil, errf("la voltage change refused: LA%d is in use by %s; %s", la, s.pinOwnerText(la), s.releaseHint(la)) + used = append(used, fmt.Sprintf("LA%d (%s)", la, fn)) } } + if len(used) > 0 { + return nil, coded(codeLaVoltagePinsInUse, "pins", strings.Join(used, ", ")) + } } + // The pulls go to the bank rail (la_pull_1v8): engaged ones stay on when it switches. s.pod.laMV = mv - if mv == 1800 { - s.pod.pulls = 0 // the resistors are 3V3-referenced: the pod drops them at 1.8 V - } s.advance(s.now()) s.touchBase(s.now()) } @@ -182,11 +199,17 @@ func (s *Sim) cmdLaVoltage(r request) (any, error) { } func (s *Sim) cmdTargetPower(r request) (any, error) { + if !r.has("efuse") { + return nil, fwError("missing efuse") + } + on, isBool := r["enabled"].(bool) + if !isBool { + return nil, fwError("enabled must be true or false") + } n := r.int("efuse", 0) if n != 1 && n != 2 { - return nil, fwError("efuse must be 1 or 2") + return nil, fwError("invalid efuse") } - on := r.flag("state") delay := r.int("delay_ms", 0) if delay < 0 || delay > 600000 { return nil, fwError("delay_ms out of range") @@ -217,7 +240,7 @@ func (s *Sim) cmdTargetPower(r request) (any, error) { } else { s.applyPower(now, n, on) } - return map[string]any{"efuse": n, "enabled": b2i(on), "delay_ms": delay}, nil + return map[string]any{"efuse": n, "enabled": on, "delay_ms": delay}, nil } func (s *Sim) cmdTargetStatus(request) (any, error) { @@ -225,7 +248,8 @@ func (s *Sim) cmdTargetStatus(request) (any, error) { defer s.mu.Unlock() s.advance(s.now()) rail := func(e efuseState) map[string]any { - return map[string]any{"enabled": b2i(e.enabled), "fault": b2i(e.fault), "valid": b2i(e.enabled)} + return map[string]any{"enabled": e.enabled, "fault": e.fault, "valid": e.enabled, "flt_pin": b2i(e.fault), + "reverse_blocks": 0, "profile": nil} } return map[string]any{"efuse1": rail(s.pod.efuse[1]), "efuse2": rail(s.pod.efuse[2]), "status_supported": true}, nil } diff --git a/benchsim/power.go b/benchsim/power.go index f6b2f05..5ff349d 100644 --- a/benchsim/power.go +++ b/benchsim/power.go @@ -26,19 +26,19 @@ func achievedRate(req float64) float64 { func (s *Sim) cmdPowerProfile(c *conn, r request) error { fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } action := r.str("action") efuse := r.int("efuse", 1) - rate := float64(r.int("rate_hz", 500)) + rate := float64(r.int("sample_rate_hz", 500)) keep := r.int("keep_samples", 0) if action == "" || action == "start" { if efuse != 1 && efuse != 2 { return fail(fwError("efuse must be 1 or 2")) } - if rate < 100 || rate > 1000 { - return fail(fwError("rate_hz must be 100..1000")) + if rate < 100 || rate > 500 { + return fail(fwError("sample_rate_hz must be 100..500")) } if keep < 0 || keep > 4096 { return fail(fwError("keep_samples must be 0..4096")) @@ -70,7 +70,7 @@ func (s *Sim) cmdPowerProfile(c *conn, r request) error { s.pod.profile = &powerSession{efuse: efuse, rateHz: rate, keep: keep, start: now, maxEnd: now + int64(max(1, min(maxMs, 600000)))*msNs} s.mu.Unlock() - return c.send(okReply(map[string]any{"started": true, "efuse": efuse, "rate_hz": int(rate)})) + return c.send(okReply(map[string]any{"started": true, "efuse": efuse, "sample_rate_hz": int(rate)})) case "status": s.mu.Lock() p := s.pod.profile @@ -169,7 +169,7 @@ func (s *Sim) profileFrames(p powerSession, end int64, truncated bool) []map[str return sum / float64(n) } stats := map[string]any{ - "efuse": p.efuse, "rate_hz": math.Round(rate*10) / 10, "adc_rate_hz": p.rateHz, "n": n, + "efuse": p.efuse, "sample_rate_hz": math.Round(rate*10) / 10, "adc_sample_rate_hz": p.rateHz, "n": n, "duration_ms": (end - p.start) / msNs, "avg_ua": math.Round(avg(sumUA)), "min_ua": minUA, "peak_ua": peakUA, "avg_mv": math.Round(avg(sumMV)), "min_mv": minMV, "max_mv": maxMV, diff --git a/benchsim/protocol.go b/benchsim/protocol.go index c16d604..dbcf26d 100644 --- a/benchsim/protocol.go +++ b/benchsim/protocol.go @@ -7,6 +7,7 @@ import ( "fmt" "math" "net" + "sort" "strconv" "strings" ) @@ -108,6 +109,130 @@ func errReply(msg string) map[string]any { return map[string]any{"status": "error", "message": msg} } +// errorReply is the reply line for a refusal: a coded one as {"status":"error","code":..., +// "args":{...}} (no message, firmware 4.0.0), any other as {"status":"error","message":...}. +func errorReply(err error) map[string]any { + var ce *codedError + if errors.As(err, &ce) { + return ce.reply() + } + return errReply(err.Error()) +} + +// codedError is a refusal with a stable error code (bp_errors.c): the client renders the +// catalog's message from the code and its args. +type codedError struct { + code int + args map[string]any +} + +// coded builds a codedError from key, value pairs. +func coded(code int, kv ...any) error { + e := &codedError{code: code} + if len(kv) > 0 { + e.args = map[string]any{} + for i := 0; i+1 < len(kv); i += 2 { + e.args[kv[i].(string)] = kv[i+1] + } + } + return e +} + +// Code is the code as the pod writes it, "BP0031". +func (e *codedError) Code() string { return fmt.Sprintf("BP%04d", e.code) } + +// Error is the firmware's short form, "BP0031 la=4 owner=gpio" (bp_err_render), keys sorted. +func (e *codedError) Error() string { + keys := make([]string, 0, len(e.args)) + for k := range e.args { + keys = append(keys, k) + } + sort.Strings(keys) + var b strings.Builder + b.WriteString(e.Code()) + for _, k := range keys { + fmt.Fprintf(&b, " %s=%v", k, e.args[k]) + } + return b.String() +} + +func (e *codedError) reply() map[string]any { + m := map[string]any{"status": "error", "code": e.Code()} + if len(e.args) > 0 { + m["args"] = e.args + } + if e.code == codeClientTooOld { // the one coded refusal that keeps a message, for old clients + m["message"] = fmt.Sprintf("Update the BenchPod SDK, MCP or CLI: this firmware needs client API %v or newer (this client sent %v)", + e.args["min_client_api"], e.args["client_api"]) + } + return m +} + +// The error codes the simulator sends (errors/catalog.toml). +const ( + codeLaVoltageNotSet = 1 + codeUnknownCommand = 2 + codeLeaseBusy = 25 + codeClientTooOld = 30 + codeLaPinInUse = 31 + codeLaPullDownEngaged = 32 + codeLaVoltagePinsInUse = 37 + codeLaPullDownConflict = 33 + codeLanLocked = 40 + codePolicyNotFromLan = 41 + codeSettingCloudOrUsb = 42 + codeSettingDeviceOnly = 43 + codeRoleRequired = 45 + codePodBusy = 47 + codeStorageBusBusy = 48 + codeSignaturesAlwaysReqd = 74 + codeTriggerTimeout = 38 + codeSamplesOutOfRange = 67 + codePsramTooSmall = 72 + codeLaNoPull = 23 + codeLaPullDirection = 24 +) + +// The client API level (features.toml): what this firmware speaks and the lowest it takes. +const ( + apiLevel = 2 + minClientAPI = 2 + featuresRev = 11 +) + +// anyClient are the verbs every client may send whatever its client_api (CMD_F_ANY_CLIENT), so +// an old client can still read the pod, let go of it and update it. +var anyClient = map[string]bool{ + "status": true, "diag": true, "ping": true, "lease_release": true, "ota_status": true, + "ota_begin": true, "ota_data": true, "ota_end": true, "ota_commit": true, "ota_abort": true, + "ota_selftest": true, "blob_status": true, "identity_public": true, +} + +// clientAPIGate is cmd_gate_client_api: a command whose top-level client_api (none = 0) is below +// min_client_api is refused with BP0030, before every other gate. +func clientAPIGate(cmd string, r request) error { + if anyClient[cmd] { + return nil + } + n := 0 + switch v := r["client_api"].(type) { + case float64: + if v >= 0 && v == math.Trunc(v) { + n = int(min(v, math.MaxInt32)) + } + case int: + n = max(v, 0) + case string: + if x, err := strconv.Atoi(v); err == nil && x >= 0 { + n = x + } + } + if n >= minClientAPI { + return nil + } + return coded(codeClientTooOld, "client_api", n, "min_client_api", minClientAPI, "api", apiLevel) +} + // conn is one client connection: one request, then its reply (or a stream, or raw UART). type conn struct { net.Conn @@ -161,7 +286,8 @@ var simpleHandlers = map[string]func(s *Sim, r request) (any, error){ "power_status": (*Sim).cmdPowerStatus, "nrst": (*Sim).cmdNrst, "usb_cc": (*Sim).cmdUsbCc, - "la": (*Sim).cmdLa, + "la_step": (*Sim).cmdLaStep, + "la_pull": (*Sim).cmdLaPull, "la_pins": (*Sim).cmdLaPins, "gpio": (*Sim).cmdGpio, "sensor_define": (*Sim).cmdSensorDefine, @@ -191,19 +317,24 @@ func (s *Sim) dispatch(c *conn, req request) { if cmd == "" { err := fwError("missing cmd") s.logCmd(req, err) - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) + return + } + if err := clientAPIGate(cmd, req); err != nil { + s.logCmd(req, err) + _ = c.send(errorReply(err)) return } if err := s.analogGuard(cmd); err != nil { s.logCmd(req, err) - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return } if h, ok := simpleHandlers[cmd]; ok { data, err := h(s, req) s.logCmd(req, err) if err != nil { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return } _ = c.send(okReply(data)) @@ -226,10 +357,10 @@ func (s *Sim) dispatch(c *conn, req request) { default: err = notInDemo(cmd) if !knownPodCommands[cmd] { - err = errf("unknown command: %s", cmd) + err = coded(codeUnknownCommand, "cmd", cmd) } s.logCmd(req, err) - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return } // The stream handlers sent their own replies (or an error before the first one). @@ -242,10 +373,10 @@ var knownPodCommands = map[string]bool{ "dap_start": true, "load_bin": true, "replay": true, "ota_begin": true, "ota_data": true, "ota_end": true, "fpga_image": true, "dac_control_loop": true, "dac_loop_input": true, "dac_loop_probe": true, "dac_limits": true, "current_out": true, "calibrate": true, - "calibration": true, "can_config": true, "can_write": true, "can_read": true, - "can_status": true, "can_term": true, "can_respond": true, "can_disable": true, + "calibration": true, "can_start": true, "can_write": true, "can_read": true, + "can_status": true, "can_term": true, "can_respond": true, "can_stop": true, "spi_start": true, - "spi_stop": true, "spi_xfer": true, "spi_stream": true, "spi_flash": true, "usb_net": true, - "lan_tls": true, "sig_policy": true, "lan_policy": true, "wifi": true, "dac_set": true, + "spi_stop": true, "spi_xfer": true, "spi_stream": true, "spi_flash": true, "usb_network": true, + "lan_tls": true, "sig_policy": true, "lan_policy": true, "wifi_status": true, "dac_set": true, "measure": true, "psram_recover": true, "cloud_config": true, "flash_self": true, } diff --git a/benchsim/sensors.go b/benchsim/sensors.go index 8dd889c..134555a 100644 --- a/benchsim/sensors.go +++ b/benchsim/sensors.go @@ -696,7 +696,7 @@ func (s *Sim) sensorClaimCheck(kind string, pins map[string]int) error { } } if !shared { - return errf("pin conflict: LA%d is in use by %s; %s", la, s.pinOwnerText(la), s.releaseHint(la)) + return s.pinInUse(la) } } if pullDown(la) && s.pod.pulls&(1<<(la-1)) != 0 { diff --git a/benchsim/sensors_test.go b/benchsim/sensors_test.go index 36d57c1..395c05e 100644 --- a/benchsim/sensors_test.go +++ b/benchsim/sensors_test.go @@ -123,7 +123,7 @@ func TestSensorStartChecks(t *testing.T) { t.Fatalf("shared line owner: %v", o) } msg := refused(t, addr, map[string]any{"cmd": "sensor_start", "instance": "temp", "pins": map[string]any{"sda": 2, "scl": 3}}) - if msg != `pin conflict: LA2 is in use by sensor:env (i2c_sda); stop the sensor emulation first ({"cmd":"sensor_stop","instance":"env"})` { + if msg != "BP0031 function=i2c_sda instance=env la=2 owner=sensor:env (i2c_sda)" { t.Fatalf("conflict: %q", msg) } if msg := refused(t, addr, map[string]any{"cmd": "gpio", "la": 1, "mode": "output"}); !strings.Contains(msg, "sensor:env (i2c_scl)") { @@ -266,12 +266,12 @@ func TestSensorUARTAndAnalog(t *testing.T) { if v := out(); v > 1.2 { t.Fatalf("60 degC: %v V", v) } - msg := refused(t, addr, map[string]any{"cmd": "dac_out", "path": "3v3", "volts": 1}) + msg := refused(t, addr, map[string]any{"cmd": "dac_out", "path": "3v3", "v": 1}) if msg != `the dac output is played by sensor:ntc; stop it first ({"cmd":"sensor_stop","instance":"ntc"})` { t.Fatalf("dac_out: %q", msg) } ok(t, addr, map[string]any{"cmd": "dac_stop"}) - ok(t, addr, map[string]any{"cmd": "dac_out", "path": "3v3", "volts": 1}) + ok(t, addr, map[string]any{"cmd": "dac_out", "path": "3v3", "v": 1}) } func TestSensorEmulationImage(t *testing.T) { diff --git a/benchsim/sim.go b/benchsim/sim.go index f85141b..f33c703 100644 --- a/benchsim/sim.go +++ b/benchsim/sim.go @@ -126,7 +126,7 @@ func New(opts ...Option) *Sim { done: make(chan struct{}), } s.pod.init() - s.flash = podFlash{lanPolicy: "open", sigPolicy: "audit"} + s.flash = podFlash{lanPolicy: "open", sigPolicy: "required", usbNet: true} s.cmdConn = &conn{} s.dut.init() for _, o := range opts { diff --git a/benchsim/sim_test.go b/benchsim/sim_test.go index c3fbe11..b81b45a 100644 --- a/benchsim/sim_test.go +++ b/benchsim/sim_test.go @@ -3,10 +3,12 @@ package benchsim import ( "bufio" "encoding/json" + "fmt" "math" "net" "regexp" "runtime" + "sort" "strings" "testing" "time" @@ -26,8 +28,16 @@ func startSim(t *testing.T, opts ...Option) (*Sim, string) { } // frames sends one command on a fresh connection and reads reply lines until "more" is false. +// It sends "client_api":2 as the 4.0 clients do, unless req has its own. func frames(t *testing.T, addr string, req map[string]any) []map[string]any { t.Helper() + if _, has := req["client_api"]; !has { + withAPI := map[string]any{"client_api": 2} + for k, v := range req { + withAPI[k] = v + } + req = withAPI + } c, err := net.Dial("tcp", addr) if err != nil { t.Fatal(err) @@ -66,16 +76,34 @@ func ok(t *testing.T, addr string, req map[string]any) any { return r["data"] } -// refused sends a command that must fail and returns its message. +// refused sends a command that must fail and returns its message, or for a coded refusal its +// short form ("BP0031 la=4 owner=gpio", args sorted by key). func refused(t *testing.T, addr string, req map[string]any) string { t.Helper() r := frames(t, addr, req)[0] if r["status"] != "error" { t.Fatalf("%v: want an error, got %v", req, r) } + if code, _ := r["code"].(string); code != "" { + return shortForm(code, r["args"]) + } return r["message"].(string) } +func shortForm(code string, args any) string { + m, _ := args.(map[string]any) + keys := make([]string, 0, len(m)) + for k := range m { + keys = append(keys, k) + } + sort.Strings(keys) + out := code + for _, k := range keys { + out += fmt.Sprintf(" %s=%v", k, m[k]) + } + return out +} + // console is a UART proxy session on the node's console. type console struct { t *testing.T @@ -90,7 +118,7 @@ func openConsole(t *testing.T, addr string) *console { t.Fatal(err) } t.Cleanup(func() { _ = c.Close() }) - _, _ = c.Write([]byte(`{"cmd":"uart_proxy_start","rx":3,"tx":4,"baud":115200}` + "\n")) + _, _ = c.Write([]byte(`{"cmd":"uart_proxy_start","rx":3,"tx":4,"baud":115200,"client_api":2}` + "\n")) ack := make([]byte, 0, 64) one := make([]byte, 1) for { @@ -143,13 +171,14 @@ func TestStatusAndLaVoltage(t *testing.T) { if st["version"] != podFirmware || st["board"] != podBoard { t.Fatalf("status: %v", st) } - if !strings.Contains(strings.Join(toStrings(st["caps"]), ","), "sensors") || st["sensors_format"] != 1.0 { - t.Fatalf("caps: %v", st["caps"]) + if _, has := st["caps"]; has || st["api"] != 2.0 || st["min_client_api"] != 2.0 || st["features_rev"] != 11.0 || + st["fpga_image"] != "loop" || st["sig_policy"] != "required" { + t.Fatalf("status levels: %v", st) } if ok(t, addr, map[string]any{"cmd": "ping"}) != "pong" { t.Fatal("ping") } - if msg := refused(t, addr, map[string]any{"cmd": "la_capture", "samples": 64}); !strings.HasPrefix(msg, "la voltage not set") { + if msg := refused(t, addr, map[string]any{"cmd": "la_capture", "samples": 64}); msg != "BP0001" { t.Fatalf("la_capture before la_voltage: %s", msg) } if msg := refused(t, addr, map[string]any{"cmd": "la_voltage", "mv": 2500}); !strings.Contains(msg, "1800 or 3300") { @@ -162,7 +191,7 @@ func TestStatusAndLaVoltage(t *testing.T) { if msg := refused(t, addr, map[string]any{"cmd": "dap_start", "swclk": 11, "swdio": 12}); !strings.Contains(msg, "not available in the demo simulator") { t.Fatal(msg) } - if msg := refused(t, addr, map[string]any{"cmd": "frobnicate"}); msg != "unknown command: frobnicate" { + if msg := refused(t, addr, map[string]any{"cmd": "frobnicate"}); msg != "BP0002 cmd=frobnicate" { t.Fatal(msg) } } @@ -180,7 +209,7 @@ func TestBootLogAndConsole(t *testing.T) { _, addr := startSim(t, WithLaVoltage(3300)) k := openConsole(t, addr) start := time.Now() - ok(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "state": 1}) + ok(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "enabled": true}) boot := k.expect(`APP_OK\r\n`, 4*time.Second) if d := time.Since(start); d < 900*time.Millisecond || d > 2*time.Second { t.Errorf("APP_OK after %v, want about 1 s", d) @@ -203,7 +232,7 @@ func TestBootLogAndConsole(t *testing.T) { if mv := v["mv"].(float64); math.Abs(mv-1500) > 5 { t.Errorf("adc_read of PA4 at 1500 mV: %v", v) } - ok(t, addr, map[string]any{"cmd": "dac_out", "path": "3v3", "volts": 1.1}) + ok(t, addr, map[string]any{"cmd": "dac_out", "path": "3v3", "v": 1.1}) time.Sleep(50 * time.Millisecond) k.send("ain") ain := k.expect(`AIN [^\r]*\r\n`, 2*time.Second) @@ -219,7 +248,7 @@ func TestBootLogAndConsole(t *testing.T) { k.expect(`APP_OK`, 2*time.Second) // The console holds LA3/LA4: a GPIO claim on them is the firmware's pin conflict. - if msg := refused(t, addr, map[string]any{"cmd": "gpio", "la": 3, "mode": "output"}); !strings.HasPrefix(msg, "pin conflict: LA3 is in use by uart_rx") { + if msg := refused(t, addr, map[string]any{"cmd": "gpio", "la": 3, "mode": "output"}); msg != "BP0031 function=uart_rx instance= la=3 owner=uart_rx" { t.Fatal(msg) } } @@ -299,13 +328,13 @@ func decodeUART(edges [][2]int, n, ch int, rate, baud float64) string { func TestLaCaptureShowsTheBootLog(t *testing.T) { t.Parallel() _, addr := startSim(t, WithLaVoltage(3300)) - ok(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "state": 1, "delay_ms": 300}) - fs := frames(t, addr, map[string]any{"cmd": "la_capture", "samples": 60000, "sample_rate_mhz": 2.0, + ok(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "enabled": true, "delay_ms": 300}) + fs := frames(t, addr, map[string]any{"cmd": "la_capture", "samples": 60000, "sample_rate_hz": 2e6, "trigger": map[string]any{"la": 3, "edge": "falling"}, "trigger_timeout_ms": 5000}) var edges [][2]int n := 0 for _, f := range fs { - if f["la"] != true || f["la_rate_hz"].(float64) != 2e6 { + if f["la"] != true || f["la_sample_rate_hz"].(float64) != 2e6 { t.Fatalf("frame: %v", f) } for _, e := range f["la_edges"].([]any) { @@ -327,7 +356,7 @@ func TestTriggerTimeout(t *testing.T) { _, addr := startSim(t, WithLaVoltage(3300)) msg := refused(t, addr, map[string]any{"cmd": "la_capture", "samples": 1000, "trigger": map[string]any{"la": 9, "edge": "rising"}, "trigger_timeout_ms": 100}) - if !regexp.MustCompile(`trigger timeout: no rising edge on LA9`).MatchString(msg) { + if msg != "BP0038 edge=rising la=9 timeout_ms=100" { t.Fatal(msg) } } @@ -335,23 +364,27 @@ func TestTriggerTimeout(t *testing.T) { func TestPowerProfileAndAdcCapture(t *testing.T) { t.Parallel() _, addr := startSim(t, WithDUTPowered()) - fs := frames(t, addr, map[string]any{"cmd": "power_profile", "efuse": 1, "rate_hz": 500, "keep_samples": 200, "duration_ms": 500}) + fs := frames(t, addr, map[string]any{"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 500, "keep_samples": 200, "duration_ms": 500}) stats := fs[len(fs)-1]["stats"].(map[string]any) if avg := stats["avg_ua"].(float64); avg < 40000 || avg > 50000 { t.Fatalf("idle current %v uA", avg) } - if r := stats["rate_hz"].(float64); r < 360 || r > 370 { + if r := stats["sample_rate_hz"].(float64); r < 360 || r > 370 { t.Fatalf("rate %v", r) } - ok(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "state": 0}) - fs = frames(t, addr, map[string]any{"cmd": "power_profile", "efuse": 1, "rate_hz": 200, "keep_samples": 0, "duration_ms": 200}) + ok(t, addr, map[string]any{"cmd": "target_power", "efuse": 1, "enabled": false}) + fs = frames(t, addr, map[string]any{"cmd": "power_profile", "efuse": 1, "sample_rate_hz": 200, "keep_samples": 0, "duration_ms": 200}) if avg := fs[len(fs)-1]["stats"].(map[string]any)["avg_ua"].(float64); avg != 0 { t.Fatalf("rail off draws %v uA", avg) } - fs = frames(t, addr, map[string]any{"cmd": "capture", "samples": 5000, "enc": "b64"}) - if fs[0]["adc_rate_hz"].(float64) != adcMaxRateHz || fs[0]["b64"] == nil { + fs = frames(t, addr, map[string]any{"cmd": "capture", "samples": 5000}) + if fs[0]["adc_sample_rate_hz"].(float64) != adcMaxRateHz || fs[0]["b64"] == nil || fs[0]["data"] != nil { t.Fatalf("capture frame: %v", fs[0]) } + fs = frames(t, addr, map[string]any{"cmd": "capture", "samples": 100, "sample_rate_hz": 100000, "enc": "dec"}) + if fs[0]["adc_sample_rate_hz"].(float64) != 100000 || fs[0]["b64"] != nil || len(fs[0]["data"].([]any)) == 0 { + t.Fatalf("decimal capture frame: %v", fs[0]) + } } // TestBmp280RoundTrip reads the engine's BMP280 image back with the node's own compensation code. @@ -394,7 +427,7 @@ func TestCloseEndsEveryConnection(t *testing.T) { go func() { c, err := net.Dial("tcp", addr) if err == nil { - _, _ = c.Write([]byte(`{"cmd":"power_profile","efuse":1,"duration_ms":60000}` + "\n")) + _, _ = c.Write([]byte(`{"cmd":"power_profile","efuse":1,"duration_ms":60000,"client_api":2}` + "\n")) } }() time.Sleep(200 * time.Millisecond) diff --git a/benchsim/spi.go b/benchsim/spi.go index 052d597..58725f9 100644 --- a/benchsim/spi.go +++ b/benchsim/spi.go @@ -53,9 +53,9 @@ func (s *Sim) cmdSpiStart(r request) (any, error) { } } } - hz := r.int("hz", 1000000) + hz := r.int("clock_hz", 1000000) if hz <= 0 { - return nil, fwError("invalid hz") + return nil, fwError("invalid clock_hz") } mode := r.int("mode", 0) if mode != 0 && mode != 3 { @@ -80,7 +80,7 @@ func (s *Sim) cmdSpiStart(r request) (any, error) { half := max(1, 24000000/hz/2) got := 24000000 / (2 * half) s.pod.spi = &spiMaster{sck: v[0], mosi: v[1], miso: v[2], cs: v[3], hz: got, mode: mode} - return map[string]any{"sck": v[0], "mosi": v[1], "miso": v[2], "cs": v[3], "hz": got, "mode": mode}, nil + return map[string]any{"sck": v[0], "mosi": v[1], "miso": v[2], "cs": v[3], "clock_hz": got, "mode": mode}, nil } func (s *Sim) cmdSpiStop(request) (any, error) { @@ -98,7 +98,7 @@ func (s *Sim) cmdSpiStatus(request) (any, error) { if m == nil { return map[string]any{"active": false}, nil } - return map[string]any{"active": true, "sck": m.sck, "mosi": m.mosi, "miso": m.miso, "cs": m.cs, "hz": m.hz, "mode": m.mode, "cs_held": m.csHeld}, nil + return map[string]any{"active": true, "sck": m.sck, "mosi": m.mosi, "miso": m.miso, "cs": m.cs, "clock_hz": m.hz, "mode": m.mode, "cs_held": m.csHeld}, nil } // flashExchange is the W25Q on the wire for one CS-low stretch: it answers tx and, when CS rises, diff --git a/benchsim/uartproxy.go b/benchsim/uartproxy.go index e8e8126..ca448da 100644 --- a/benchsim/uartproxy.go +++ b/benchsim/uartproxy.go @@ -21,7 +21,7 @@ const proxyPoll = 5 * time.Millisecond func (s *Sim) cmdUartProxy(c *conn, r request) error { fail := func(err error) error { - _ = c.send(errReply(err.Error())) + _ = c.send(errorReply(err)) return err } if !r.has("rx") { diff --git a/podsim/commands.go b/podsim/commands.go index 01e815f..4895a7f 100644 --- a/podsim/commands.go +++ b/podsim/commands.go @@ -4,6 +4,8 @@ import ( "encoding/json" "fmt" "time" + + "github.com/embeddedci-com/benchpod-sim/benchsim" ) // CmdLogEntry is one command the pod saw, for tests to assert on. @@ -91,8 +93,8 @@ func (p *Pod) onCommandRequest(gen int, data []byte) { p.mu.Lock() if p.st.busy { p.mu.Unlock() - p.logCmd("cloud", req.Command, "error", "device busy") - p.respondError(gen, req.RequestID, "device busy") + p.logCmd("cloud", req.Command, "error", "BP0052") + p.respondCoded(gen, req.RequestID, benchsim.Reply{Error: "BP0052", Code: "BP0052"}) return } p.st.busy = true @@ -107,7 +109,8 @@ func (p *Pod) onCommandRequest(gen int, data []byte) { if delay > 0 { time.Sleep(delay) } - res, errMsg := p.execute(req.Command) + res, rep := p.execute(req.Command) + errMsg := rep.Error status := "ok" if errMsg != "" { status = "error" @@ -124,7 +127,7 @@ func (p *Pod) onCommandRequest(gen int, data []byte) { return } if errMsg != "" { - p.respondError(gen, req.RequestID, errMsg) + p.respondCoded(gen, req.RequestID, rep) return } _ = p.send(gen, map[string]any{ @@ -135,10 +138,23 @@ func (p *Pod) onCommandRequest(gen int, data []byte) { } func (p *Pod) respondError(gen int, requestID, msg string) { - _ = p.send(gen, map[string]any{ + p.respondCoded(gen, requestID, benchsim.Reply{Error: msg}) +} + +// respondCoded is an error command.response: "error" is the message, or the code when there is +// none, with "code" and "args" beside it for a coded refusal. +func (p *Pod) respondCoded(gen int, requestID string, r benchsim.Reply) { + m := map[string]any{ "type": "command.response", "request_id": requestID, "device_id": p.DeviceID(), - "status": "error", "error": msg, - }) + "status": "error", "error": r.Error, + } + if r.Code != "" { + m["code"] = r.Code + if len(r.Args) > 0 { + m["args"] = r.Args + } + } + _ = p.send(gen, m) } // RunLAN runs a command as a LAN client would (the pod's own command port): the lease gate @@ -190,7 +206,7 @@ func (p *Pod) onLeaseState(data []byte) { } // execute runs one command from the cloud channel: the Sim is the firmware's command layer. -func (p *Pod) execute(cmd map[string]any) (any, string) { +func (p *Pod) execute(cmd map[string]any) (any, benchsim.Reply) { if name, _ := cmd["cmd"].(string); name == "lease_state" { p.mu.Lock() defer p.mu.Unlock() @@ -200,13 +216,13 @@ func (p *Pod) execute(cmd map[string]any) (any, string) { out["holder"] = holder out["expires_in_s"] = int(time.Until(p.st.lease.Deadline).Seconds()) } - return out, "" + return out, benchsim.Reply{} } - data, msg := p.sim.Exec(cmd, true) - if msg != "" { - return nil, msg + r := p.sim.ExecReply(cmd, true) + if r.Error != "" { + return nil, r } - return data, "" + return r.Data, benchsim.Reply{} } // hostCommand answers the verbs this side owns; the Sim calls it after its gates. diff --git a/podsim/pod.go b/podsim/pod.go index 8b44f04..f2fc616 100644 --- a/podsim/pod.go +++ b/podsim/pod.go @@ -106,7 +106,7 @@ type lease struct { // New makes a pod with a fresh identity. func New(cfg Config) (*Pod, error) { if cfg.Firmware == "" { - cfg.Firmware = "3.8.0" + cfg.Firmware = "4.0.0" } if cfg.Board == "" { cfg.Board = "stm32h563"