53 lines
981 B
Go
53 lines
981 B
Go
package picoserial
|
|
|
|
import (
|
|
"fmt"
|
|
"io"
|
|
"time"
|
|
|
|
"go.bug.st/serial"
|
|
"go.bug.st/serial/enumerator"
|
|
)
|
|
|
|
func FindDevice() (string, error) {
|
|
ports, err := enumerator.GetDetailedPortsList()
|
|
if err != nil {
|
|
return "", fmt.Errorf("enumerating ports: %w", err)
|
|
}
|
|
for _, p := range ports {
|
|
if p.IsUSB {
|
|
return p.Name, nil
|
|
}
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
type SerialTransport struct {
|
|
port serial.Port
|
|
}
|
|
|
|
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)
|
|
}
|
|
return &SerialTransport{port: port}, nil
|
|
}
|
|
|
|
func (t *SerialTransport) Send(data []byte) error {
|
|
_, err := t.port.Write(data)
|
|
return err
|
|
}
|
|
|
|
func (t *SerialTransport) SetReadTimeout(timeout time.Duration) {
|
|
t.port.SetReadTimeout(timeout)
|
|
}
|
|
|
|
func (t *SerialTransport) Reader() io.Reader {
|
|
return t.port
|
|
}
|
|
|
|
func (t *SerialTransport) Close() error {
|
|
return t.port.Close()
|
|
}
|