Skip to content

Commit

Permalink
add serial to json example
Browse files Browse the repository at this point in the history
  • Loading branch information
twpayne committed Sep 21, 2023
1 parent 4c3d280 commit 9b0506d
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions examples/serial-to-json/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package main

import (
"encoding/json"
"flag"
"fmt"
"log"
"os"

"github.com/bluenviron/gomavlib/v2"
"github.com/bluenviron/gomavlib/v2/pkg/dialects/common"
"github.com/bluenviron/gomavlib/v2/pkg/frame"
)

// this example shows how to:
// 1) create a node which communicates with a serial endpoint
// 2) convert any message to a generic JSON object
// the output of this example can be combined with a JSON parser like jq to display individual messages, for example:
// go run ./examples/serial-to-json | jq 'select(.MessageType == "*minimal.MessageHeartbeat")'

func main() {
baudRate := flag.Int("b", 57600, "baud rate")
port := flag.String("p", "/dev/ttyUSB0", "port")
flag.Parse()

// create a node which communicates with a serial endpoint
node, err := gomavlib.NewNode(gomavlib.NodeConf{
Endpoints: []gomavlib.EndpointConf{
gomavlib.EndpointSerial{
Device: *port,
Baud: *baudRate,
},
},
Dialect: common.Dialect,
OutVersion: gomavlib.V2, // change to V1 if you're unable to communicate with the target
OutSystemID: 10,
})
if err != nil {
log.Panic(err)
}
defer node.Close()

jsonEncoder := json.NewEncoder(os.Stdout)
for evt := range node.Events() {
switch evt := evt.(type) {
case *gomavlib.EventFrame:
// add the message type to the JSON object
if err := jsonEncoder.Encode(struct {
MessageType string
Frame *frame.Frame
}{
MessageType: fmt.Sprintf("%T", evt.Message()),
Frame: &evt.Frame,
}); err != nil {
// some messages contain floating point NaN values which cannot be encoded in JSON
// silently ignore these errors
if err.Error() != "json: unsupported value: NaN" {
log.Panic(err)
}
}
case *gomavlib.EventParseError:
log.Print(evt.Error)
}
}
}

0 comments on commit 9b0506d

Please sign in to comment.