github.com/bluenviron/gomavlib/v2@v2.2.1-0.20240308101627-2c07e3da629c/examples/serial-to-json/main.go (about) 1 package main 2 3 import ( 4 "encoding/json" 5 "flag" 6 "fmt" 7 "os" 8 9 "github.com/bluenviron/gomavlib/v2" 10 "github.com/bluenviron/gomavlib/v2/pkg/dialects/common" 11 "github.com/bluenviron/gomavlib/v2/pkg/frame" 12 ) 13 14 // this example shows how to: 15 // 1) create a node which communicates with a serial endpoint 16 // 2) convert any message to a generic JSON object 17 // the output of this example can be combined with a JSON parser like jq to display individual messages, for example: 18 // go run ./examples/serial-to-json | jq 'select(.MessageType == "*minimal.MessageHeartbeat")' 19 20 func main() { 21 baudRate := flag.Int("b", 57600, "baud rate") 22 port := flag.String("p", "/dev/ttyUSB0", "port") 23 flag.Parse() 24 25 // create a node which communicates with a serial endpoint 26 node, err := gomavlib.NewNode(gomavlib.NodeConf{ 27 Endpoints: []gomavlib.EndpointConf{ 28 gomavlib.EndpointSerial{ 29 Device: *port, 30 Baud: *baudRate, 31 }, 32 }, 33 Dialect: common.Dialect, 34 OutVersion: gomavlib.V2, // change to V1 if you're unable to communicate with the target 35 OutSystemID: 10, 36 }) 37 if err != nil { 38 panic(err) 39 } 40 defer node.Close() 41 42 jsonEncoder := json.NewEncoder(os.Stdout) 43 for evt := range node.Events() { 44 if frm, ok := evt.(*gomavlib.EventFrame); ok { 45 // add the message type to the JSON object 46 if err := jsonEncoder.Encode(struct { 47 MessageType string 48 Frame *frame.Frame 49 }{ 50 MessageType: fmt.Sprintf("%T", frm.Message()), 51 Frame: &frm.Frame, 52 }); err != nil { 53 // some messages contain floating point NaN values which cannot be encoded in JSON 54 // silently ignore these errors 55 if err.Error() != "json: unsupported value: NaN" { 56 panic(err) 57 } 58 } 59 } 60 } 61 }