github.com/bluenviron/gomavlib/v2@v2.2.1-0.20240308101627-2c07e3da629c/endpoint_serial.go (about) 1 package gomavlib 2 3 import ( 4 "context" 5 "io" 6 7 "github.com/tarm/serial" 8 9 "github.com/bluenviron/gomavlib/v2/pkg/reconnector" 10 ) 11 12 var serialOpenFunc = func(device string, baud int) (io.ReadWriteCloser, error) { 13 return serial.OpenPort(&serial.Config{ 14 Name: device, 15 Baud: baud, 16 }) 17 } 18 19 // EndpointSerial sets up a endpoint that works with a serial port. 20 type EndpointSerial struct { 21 // the name of the device of the serial port (i.e: /dev/ttyUSB0) 22 Device string 23 24 // baud rate (i.e: 57600) 25 Baud int 26 } 27 28 type endpointSerial struct { 29 conf EndpointConf 30 reconnector *reconnector.Reconnector 31 } 32 33 func (conf EndpointSerial) init(_ *Node) (Endpoint, error) { 34 // check device existence 35 test, err := serialOpenFunc(conf.Device, conf.Baud) 36 if err != nil { 37 return nil, err 38 } 39 test.Close() 40 41 t := &endpointSerial{ 42 conf: conf, 43 reconnector: reconnector.New( 44 func(ctx context.Context) (io.ReadWriteCloser, error) { 45 return serialOpenFunc(conf.Device, conf.Baud) 46 }, 47 ), 48 } 49 50 return t, nil 51 } 52 53 func (t *endpointSerial) isEndpoint() {} 54 55 func (t *endpointSerial) Conf() EndpointConf { 56 return t.conf 57 } 58 59 func (t *endpointSerial) close() { 60 t.reconnector.Close() 61 } 62 63 func (t *endpointSerial) oneChannelAtAtime() bool { 64 return true 65 } 66 67 func (t *endpointSerial) provide() (string, io.ReadWriteCloser, error) { 68 conn, ok := t.reconnector.Reconnect() 69 if !ok { 70 return "", nil, errTerminated 71 } 72 73 return "serial", conn, nil 74 }