-
Notifications
You must be signed in to change notification settings - Fork 0
/
chamgo.go
68 lines (60 loc) · 1.32 KB
/
chamgo.go
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
package main
import (
"bufio"
"fmt"
"github.com/tarm/serial"
"log"
"os"
"strings"
)
//ui holds the userinput
var ui = ""
func main() {
argCount := len(os.Args[1:])
if argCount != 1 {
fmt.Printf("Usage: %s <serial-port>\ne.g.:\n\t%s com5 (on windows)\n\t%s /dev/ttyUSB0 (on linux)\n\t%s /dev/cu.usbmodem1411 (on osx)\n", os.Args[0], os.Args[0], os.Args[0], os.Args[0])
os.Exit(0)
}
c := &serial.Config{Name: os.Args[1], Baud: 9600}
s, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
os.Exit(2)
}
fmt.Println("chamgo - ready to talk to the chameleon")
for {
ui = getUserInput()
if ui == "exit" || ui == "quit" || ui == "q" {
os.Exit(0)
}
rb := sendCmd(ui, s)
fmt.Print(string(rb))
}
}
/**
* sending cmds to serial
* returns {bytes} responde from device
**/
func sendCmd(cmd string, port *serial.Port) (returnmessage []byte) {
cmd += "\r"
n, err := port.Write([]byte(cmd))
if err != nil {
log.Fatal(err)
}
buf := make([]byte, 256)
n, err = port.Read(buf)
if err != nil {
log.Fatal(err)
}
return buf[0:n]
}
/**
* for receiving user input
* returns {string} with no newline (|n)
**/
func getUserInput() string {
scanner := bufio.NewScanner(os.Stdin)
scanner.Scan() // use `for scanner.Scan()` to keep reading
line := scanner.Text()
return strings.Replace(string(line), "\n", "", -1)
}