From 8d6f7db12a0ada0dea43ea338aff4eaf9a8eafd1 Mon Sep 17 00:00:00 2001 From: AntoineH Date: Wed, 4 Sep 2024 16:24:06 +0200 Subject: [PATCH] Implement listen command --- src/cmd/motor/listen.go | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/src/cmd/motor/listen.go b/src/cmd/motor/listen.go index 0562f55..6db3db1 100644 --- a/src/cmd/motor/listen.go +++ b/src/cmd/motor/listen.go @@ -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) + } +} \ No newline at end of file