Stream-decode msgpack responses instead of waiting for read timeout

This commit is contained in:
Ian Gulliver
2026-04-04 19:54:46 +09:00
parent f8e4249047
commit 43bf0fe951
3 changed files with 15 additions and 23 deletions

View File

@@ -42,15 +42,10 @@ func (c *Client) send(msg any) (uint32, error) {
} }
func (c *Client) receive(expectedID uint32) (any, error) { func (c *Client) receive(expectedID uint32) (any, error) {
data, err := c.transport.Receive(c.timeout) c.transport.SetReadTimeout(c.timeout)
if err != nil { dec := msgpack.NewDecoder(c.transport.Reader())
return nil, fmt.Errorf("receive: %w", err)
}
if len(data) == 0 {
return nil, fmt.Errorf("no response")
}
var env Envelope var env Envelope
if err := msgpack.Unmarshal(data, &env); err != nil { if err := dec.Decode(&env); err != nil {
return nil, fmt.Errorf("decode envelope: %w", err) return nil, fmt.Errorf("decode envelope: %w", err)
} }
if env.MessageID != expectedID { if env.MessageID != expectedID {

View File

@@ -2,6 +2,7 @@ package picoserial
import ( import (
"fmt" "fmt"
"io"
"time" "time"
"go.bug.st/serial" "go.bug.st/serial"
@@ -38,20 +39,12 @@ func (t *SerialTransport) Send(data []byte) error {
return err return err
} }
func (t *SerialTransport) Receive(timeout time.Duration) ([]byte, error) { func (t *SerialTransport) SetReadTimeout(timeout time.Duration) {
t.port.SetReadTimeout(timeout) t.port.SetReadTimeout(timeout)
var resp []byte
buf := make([]byte, 256)
for {
n, err := t.port.Read(buf)
if n > 0 {
resp = append(resp, buf[:n]...)
} }
if err != nil || n == 0 {
break func (t *SerialTransport) Reader() io.Reader {
} return t.port
}
return resp, nil
} }
func (t *SerialTransport) Close() error { func (t *SerialTransport) Close() error {

View File

@@ -1,9 +1,13 @@
package transport package transport
import "time" import (
"io"
"time"
)
type Transport interface { type Transport interface {
Send(data []byte) error Send(data []byte) error
Receive(timeout time.Duration) ([]byte, error) SetReadTimeout(timeout time.Duration)
Reader() io.Reader
Close() error Close() error
} }