Skip to content

Instantly share code, notes, and snippets.

@masci
Last active August 3, 2020 11:47
Show Gist options
  • Save masci/804ba2679c8598630ca05919713ab106 to your computer and use it in GitHub Desktop.
Save masci/804ba2679c8598630ca05919713ab106 to your computer and use it in GitHub Desktop.
package main
import (
"context"
"fmt"
"io"
"log"
"os"
"os/signal"
"syscall"
"time"
rpc "github.com/arduino/arduino-cli/rpc/commands"
rpcmonitor "github.com/arduino/arduino-cli/rpc/monitor"
st "github.com/golang/protobuf/ptypes/struct"
"google.golang.org/grpc"
)
func main() {
conn, err := grpc.Dial("localhost:50051", grpc.WithInsecure(), grpc.WithBlock(), grpc.WithTimeout(100*time.Millisecond))
if err != nil {
log.Fatal("error connecting to arduino-cli rpc server, skip...")
}
defer conn.Close()
c1 := rpc.NewArduinoCoreClient(conn)
versionResp, err := c1.Version(context.Background(), &rpc.VersionReq{})
if err != nil {
log.Fatalf("Error getting version: %s\n", err)
}
fmt.Printf("CLI version: %v\n", versionResp)
c2 := rpcmonitor.NewMonitorClient(conn)
stream, err := c2.StreamingOpen(context.Background())
// prepare extra config params needed by the serial monitor
additionalFields := make(map[string]*st.Value, 1)
additionalFields["baudRate"] = &st.Value{
Kind: &st.Value_NumberValue{
NumberValue: float64(9600),
},
}
// open the monitor by sending a config message
if err := stream.Send(&rpcmonitor.StreamingOpenReq{
Content: &rpcmonitor.StreamingOpenReq_MonitorConfig{
MonitorConfig: &rpcmonitor.MonitorConfig{
Target: "/dev/ttyACM1",
Type: rpcmonitor.MonitorConfig_SERIAL,
AdditionalConfig: &st.Struct{
Fields: additionalFields,
},
},
},
}); err != nil {
log.Fatalf("Failed to init monitor: %v", err)
}
// we're good to go, handle CTRL+C to avoid shutting down the server
// abruptly
ctrlc := make(chan os.Signal)
signal.Notify(ctrlc, os.Interrupt, syscall.SIGTERM)
go func() {
<-ctrlc
stream.CloseSend()
}()
// read messages coming from the serial
go func() {
for {
in, err := stream.Recv()
if err == io.EOF {
// read done
return
}
if err != nil {
log.Fatalf("Failed to receive a message : %v", err)
}
log.Printf("Got message %s", in.Data)
}
}()
// send messages to the stream
ledStatus := 0
for {
if err := stream.Send(&rpcmonitor.StreamingOpenReq{
Content: &rpcmonitor.StreamingOpenReq_Data{
Data: []byte(fmt.Sprintf("%d", ledStatus)),
},
}); err != nil {
break
}
ledStatus = 1 - ledStatus
time.Sleep(1 * time.Second)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment