Add message IDs, transport interface, client package, extract protocol headers
This commit is contained in:
@@ -21,29 +21,29 @@ func FindDevice() (string, error) {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
func Open(portName string) (serial.Port, error) {
|
||||
return serial.Open(portName, &serial.Mode{BaudRate: 115200})
|
||||
type SerialTransport struct {
|
||||
port serial.Port
|
||||
}
|
||||
|
||||
// SendAndReceive sends data and reads the response with a timeout.
|
||||
func SendAndReceive(portName string, data []byte, timeout time.Duration) ([]byte, error) {
|
||||
port, err := Open(portName)
|
||||
func Open(portName string) (*SerialTransport, error) {
|
||||
port, err := serial.Open(portName, &serial.Mode{BaudRate: 115200})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("opening %s: %w", portName, err)
|
||||
}
|
||||
defer port.Close()
|
||||
return &SerialTransport{port: port}, nil
|
||||
}
|
||||
|
||||
port.SetReadTimeout(timeout)
|
||||
|
||||
_, err = port.Write(data)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("writing to %s: %w", portName, err)
|
||||
}
|
||||
func (t *SerialTransport) Send(data []byte) error {
|
||||
_, err := t.port.Write(data)
|
||||
return err
|
||||
}
|
||||
|
||||
func (t *SerialTransport) Receive(timeout time.Duration) ([]byte, error) {
|
||||
t.port.SetReadTimeout(timeout)
|
||||
var resp []byte
|
||||
buf := make([]byte, 256)
|
||||
for {
|
||||
n, err := port.Read(buf)
|
||||
n, err := t.port.Read(buf)
|
||||
if n > 0 {
|
||||
resp = append(resp, buf[:n]...)
|
||||
}
|
||||
@@ -53,3 +53,7 @@ func SendAndReceive(portName string, data []byte, timeout time.Duration) ([]byte
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (t *SerialTransport) Close() error {
|
||||
return t.port.Close()
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user