github.com/bluenviron/gomavlib/v2@v2.2.1-0.20240308101627-2c07e3da629c/examples/message-write/main.go (about)

     1  package main
     2  
     3  import (
     4  	"log"
     5  
     6  	"github.com/bluenviron/gomavlib/v2"
     7  	"github.com/bluenviron/gomavlib/v2/pkg/dialects/ardupilotmega"
     8  )
     9  
    10  // this example shows how to:
    11  // 1) create a node which communicates with a serial endpoint
    12  // 2) wait for a specific incoming message
    13  // 3) write a reply message
    14  
    15  func main() {
    16  	// create a node which communicates with a serial endpoint
    17  	node, err := gomavlib.NewNode(gomavlib.NodeConf{
    18  		Endpoints: []gomavlib.EndpointConf{
    19  			gomavlib.EndpointSerial{
    20  				Device: "/dev/ttyUSB0",
    21  				Baud:   57600,
    22  			},
    23  		},
    24  		Dialect:     ardupilotmega.Dialect,
    25  		OutVersion:  gomavlib.V2, // change to V1 if you're unable to communicate with the target
    26  		OutSystemID: 10,
    27  	})
    28  	if err != nil {
    29  		panic(err)
    30  	}
    31  	defer node.Close()
    32  
    33  	for evt := range node.Events() {
    34  		if frm, ok := evt.(*gomavlib.EventFrame); ok {
    35  			log.Printf("received: id=%d, %+v\n", frm.Message().GetID(), frm.Message())
    36  
    37  			// if message is a parameter read request addressed to this node
    38  			if msg, ok := frm.Message().(*ardupilotmega.MessageParamRequestRead); ok &&
    39  				msg.TargetSystem == 10 &&
    40  				msg.TargetComponent == 1 &&
    41  				msg.ParamId == "test_parameter" {
    42  
    43  				// reply to sender (and no one else) and provide the requested parameter
    44  				node.WriteMessageTo(frm.Channel, &ardupilotmega.MessageParamValue{
    45  					ParamId:    "test_parameter",
    46  					ParamValue: 123456,
    47  					ParamType:  ardupilotmega.MAV_PARAM_TYPE_UINT32,
    48  				})
    49  			}
    50  		}
    51  	}
    52  }