Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand Down
40 changes: 24 additions & 16 deletions benchsim/analog.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -335,25 +335,31 @@ 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")
}
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 {
Expand All @@ -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
}
6 changes: 3 additions & 3 deletions benchsim/can.go
Original file line number Diff line number Diff line change
Expand Up @@ -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") {
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
89 changes: 50 additions & 39 deletions benchsim/capture.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand All @@ -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
Expand All @@ -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()
Expand All @@ -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 {
Expand Down Expand Up @@ -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()
Expand All @@ -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)
Expand Down Expand Up @@ -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}
Expand All @@ -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)
Expand All @@ -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 {
Expand All @@ -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)
Expand All @@ -409,22 +416,22 @@ 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)
if s.firmware && na == 0 && nl == 0 {
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"))
Expand All @@ -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)
Expand Down Expand Up @@ -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
}
}
Expand Down Expand Up @@ -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 {
Expand All @@ -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 {
Expand Down
Loading