Implement listen command
This commit is contained in:
parent
9d85ad0773
commit
8d6f7db12a
1 changed files with 37 additions and 0 deletions
|
@ -8,8 +8,17 @@ import (
|
|||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"context"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
pb "github.com/AntoineHX/multi-motors-controller/src/proto"
|
||||
)
|
||||
|
||||
//Cobra CLI
|
||||
// listenCmd represents the listen command
|
||||
var listenCmd = &cobra.Command{
|
||||
Use: "listen",
|
||||
|
@ -17,6 +26,8 @@ var listenCmd = &cobra.Command{
|
|||
Long: `listen command descritpion`,
|
||||
Run: func(cmd *cobra.Command, args []string) {
|
||||
fmt.Println("listen called with ID: ", cmd.Flag("id").Value)
|
||||
updateConfig()
|
||||
listen() //Blocking call
|
||||
},
|
||||
}
|
||||
|
||||
|
@ -33,3 +44,29 @@ func init() {
|
|||
// is called directly, e.g.:
|
||||
// listenCmd.Flags().Uint16("id", 0, "Identifier number")
|
||||
}
|
||||
|
||||
// Could have been done with a coroutine and a range on a channel if launched from the server thread
|
||||
func listen(){
|
||||
// Set up a connection to the server.
|
||||
var addr = fmt.Sprintf("%s:%d", ip, curr_config.Port) //Defined in controller/serve
|
||||
conn, err := grpc.NewClient(addr, grpc.WithTransportCredentials(insecure.NewCredentials()))
|
||||
if err != nil {
|
||||
log.Fatalf("did not connect: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
c := pb.NewMotorClient(conn)
|
||||
|
||||
for{
|
||||
// Contact the server and print out its response.
|
||||
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||
defer cancel()
|
||||
r, err := c.GetData(ctx, &pb.Empty{})
|
||||
if err != nil {
|
||||
log.Fatalf("could not send: %v", err)
|
||||
}
|
||||
log.Printf("Motor state: %f° | %f°/s | %s", r.GetAngle(), r.GetVelocity(), r.GetError())
|
||||
|
||||
// Wait for a second
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue