Add message IDs, transport interface, client package, extract protocol headers
This commit is contained in:
90
lib/client/client.go
Normal file
90
lib/client/client.go
Normal file
@@ -0,0 +1,90 @@
|
||||
package client
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/theater/picomap/lib/halfsiphash"
|
||||
"github.com/theater/picomap/lib/msgpack"
|
||||
"github.com/theater/picomap/lib/transport"
|
||||
)
|
||||
|
||||
var HashKey = [8]byte{}
|
||||
|
||||
type Client struct {
|
||||
transport transport.Transport
|
||||
timeout time.Duration
|
||||
nextID atomic.Uint32
|
||||
}
|
||||
|
||||
func New(t transport.Transport, timeout time.Duration) *Client {
|
||||
return &Client{transport: t, timeout: timeout}
|
||||
}
|
||||
|
||||
func (c *Client) Close() error {
|
||||
return c.transport.Close()
|
||||
}
|
||||
|
||||
func (c *Client) send(msg any) (uint32, error) {
|
||||
id := c.nextID.Add(1)
|
||||
payload, err := msgpack.Marshal(msg)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("encode inner: %w", err)
|
||||
}
|
||||
checksum := halfsiphash.Sum32(payload, HashKey)
|
||||
env := Envelope{MessageID: id, Checksum: checksum, Payload: payload}
|
||||
data, err := msgpack.Marshal(&env)
|
||||
if err != nil {
|
||||
return 0, fmt.Errorf("encode envelope: %w", err)
|
||||
}
|
||||
return id, c.transport.Send(data)
|
||||
}
|
||||
|
||||
func (c *Client) receive(expectedID uint32) (any, error) {
|
||||
data, err := c.transport.Receive(c.timeout)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("receive: %w", err)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, fmt.Errorf("no response")
|
||||
}
|
||||
var env Envelope
|
||||
if err := msgpack.Unmarshal(data, &env); err != nil {
|
||||
return nil, fmt.Errorf("decode envelope: %w", err)
|
||||
}
|
||||
if env.MessageID != expectedID {
|
||||
return nil, fmt.Errorf("message id mismatch: got %d, want %d", env.MessageID, expectedID)
|
||||
}
|
||||
expected := halfsiphash.Sum32(env.Payload, HashKey)
|
||||
if env.Checksum != expected {
|
||||
return nil, fmt.Errorf("checksum mismatch: got %08x, want %08x", env.Checksum, expected)
|
||||
}
|
||||
var inner any
|
||||
if err := msgpack.Unmarshal(env.Payload, &inner); err != nil {
|
||||
return nil, fmt.Errorf("decode inner: %w", err)
|
||||
}
|
||||
if devErr, ok := inner.(*DeviceError); ok {
|
||||
return nil, devErr
|
||||
}
|
||||
return inner, nil
|
||||
}
|
||||
|
||||
func (c *Client) roundTrip(req any) (any, error) {
|
||||
id, err := c.send(req)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.receive(id)
|
||||
}
|
||||
|
||||
func (c *Client) BOOTSEL() error {
|
||||
resp, err := c.roundTrip(&RequestBOOTSEL{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, ok := resp.(*ResponseBOOTSEL); !ok {
|
||||
return fmt.Errorf("unexpected response: %T", resp)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user