Skip to content

Commit

Permalink
add serial to json example (#80)
Browse files Browse the repository at this point in the history
  • Loading branch information
twpayne authored Sep 23, 2023
1 parent 26b77a4 commit fb76b0a
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 0 deletions.
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,7 @@ Features:
* [events](examples/events/main.go)
* [router](examples/router/main.go)
* [router-edit](examples/router-edit/main.go)
* [serial-to-json](examples/serial-to-json/main.go)
* [stream-requests](examples/stream-requests/main.go)
* [readwriter](examples/readwriter/main.go)

Expand Down
61 changes: 61 additions & 0 deletions examples/serial-to-json/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
package main

import (
"encoding/json"
"flag"
"fmt"
"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 {
panic(err)
}
defer node.Close()

jsonEncoder := json.NewEncoder(os.Stdout)
for evt := range node.Events() {
if frm, ok := evt.(*gomavlib.EventFrame); ok {
// add the message type to the JSON object
if err := jsonEncoder.Encode(struct {
MessageType string
Frame *frame.Frame
}{
MessageType: fmt.Sprintf("%T", frm.Message()),
Frame: &frm.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" {
panic(err)
}
}
}
}
}

0 comments on commit fb76b0a

Please sign in to comment.