aboutsummaryrefslogtreecommitdiff
path: root/car/elegoo/main.go
blob: 91711026e90d22fbf2dbe50e8ac2d7e764fdf2c8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package main

import (
	"io"
	"log"
	"time"

	"github.com/golang/protobuf/proto"
	"github.com/tarm/serial"
)

func Write(w io.Writer, buf []byte) {
	w.Write([]byte{byte(len(buf))})
	w.Write(buf)
}

func Read(r io.Reader) []byte {
	buf := [32]byte{}
	n, _ := r.Read(buf[:])
	return buf[:n]
	/*
		sz := [1]byte{}
		r.Read(sz[:])
		log.Println(sz)
		if l := int(sz[0]); l > 0 {
			buf := make([]byte, l)
			r.Read(buf)
			return buf
		}
		return nil
	*/
}

func varint(b []byte) []byte {
	return append([]byte{byte(len(b))}, b...)
}

// /dev/cu.Elegoo-DevB
// /dev/cu.usbmodem1421

func Wait(d time.Duration) {
	log.Println("Wait", d)
	time.Sleep(d)
}

func main() {
	c := &serial.Config{
		Name: "/dev/cu.usbmodem1421",
		Baud: 57600,
	}
	s, err := serial.OpenPort(c)
	if err != nil {
		log.Fatal(err)
	}
	defer s.Close()

	Wait(3 * time.Second)
	cmd := &Command{
		SetSpeed: &Speed{
			Left:  100,
			Right: 120,
		},
	}
	buf, err := proto.Marshal(cmd)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("Send: %v", buf)
	Write(s, buf)

	go func() {
		for {
			log.Printf("Got: %v", Read(s))
		}
	}()

	time.Sleep(30 * time.Second)
}