aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorDimitri Sokolyuk <demon@dim13.org>2017-08-20 18:16:34 +0200
committerDimitri Sokolyuk <demon@dim13.org>2017-08-20 18:16:34 +0200
commita084b871c5056403ffc7d520ccc4b285e263b9f9 (patch)
treeee7f110f9b40bbae2080756abb190f59b5bfcea5
parent6661b6047e56956bdec82bf469769e32109850e4 (diff)
...
-rw-r--r--car/elegoo/main.go48
1 files changed, 19 insertions, 29 deletions
diff --git a/car/elegoo/main.go b/car/elegoo/main.go
index e44fb6a..daf8262 100644
--- a/car/elegoo/main.go
+++ b/car/elegoo/main.go
@@ -12,22 +12,24 @@ import (
"github.com/tarm/serial"
)
-func Write(w io.Writer, buf []byte) {
- sz := proto.EncodeVarint(uint64(len(buf)))
- w.Write(append(sz, buf...))
-}
-
-func Read(r io.Reader) []byte {
- buf := make([]byte, 1)
- r.Read(buf)
- sz, _ := proto.DecodeVarint(buf)
- nbuf := make([]byte, int(sz))
- io.ReadFull(r, nbuf)
- return nbuf
+func Write(w io.Writer, pb proto.Message) error {
+ buf := new(proto.Buffer)
+ err := buf.EncodeMessage(pb)
+ if err != nil {
+ return err
+ }
+ _, err = w.Write(buf.Bytes())
+ return err
}
-func varint(b []byte) []byte {
- return append([]byte{byte(len(b))}, b...)
+func Read(r io.Reader, pb proto.Message) error {
+ buf := make([]byte, 80)
+ n, err := r.Read(buf)
+ if err != nil {
+ return err
+ }
+ log.Prinltn("got: % x", buf[:n]) // DEBUG
+ return proto.NewBuffer(buf[:n]).DecodeMessage(pb)
}
// /dev/cu.Elegoo-DevB
@@ -44,25 +46,13 @@ func main() {
}
defer s.Close()
- cmd := &Command{
- SetSpeed: &Speed{
- Left: 100,
- Right: 120,
- },
- }
- buf, err := proto.Marshal(cmd)
- if err != nil {
- log.Fatal(err)
- }
- log.Printf("Send: %x", buf)
- //Write(s, buf)
+ cmd := &Command{}
+ Write(s, cmd)
go func() {
for {
- buf := Read(s)
- log.Printf("Got: %x", buf)
evt := &Event{}
- proto.Unmarshal(buf, evt)
+ Read(s, evt)
log.Println(evt)
}
}()