-
Notifications
You must be signed in to change notification settings - Fork 0
/
kahoo.go
105 lines (83 loc) · 1.89 KB
/
kahoo.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
package main
import (
"bufio"
"flag"
"fmt"
"io"
"os"
"github.com/spf13/cobra"
"github.com/tarm/serial"
)
const defaultPort = "/dev/ttyUSB0"
const defaultBaud = 115200
var rootCmd = &cobra.Command{
Use: "",
}
var readCmd = &cobra.Command{
Use: "read -p [port] -b [baud]",
Short: "Read data from serial",
Long: "Read data form serial on specific port and baud",
Run: func(cmd *cobra.Command, args []string) {
port, _ := cmd.Flags().GetString("port")
baud, _ := cmd.Flags().GetInt("baud")
config := &serial.Config{
Name: port,
Baud: baud,
}
serialConnection, err := serial.OpenPort(config)
if err != nil {
panic(err)
}
buffer := make([]byte, 1024)
for {
size, err := serialConnection.Read(buffer)
if err != nil {
panic(err)
}
fmt.Printf("%q", buffer[:size])
}
},
}
var writeCmd = &cobra.Command{
Use: "write -p [port] -b [baud]",
Short: "Write bytes on serial",
Long: "",
Run: func(cmd *cobra.Command, args []string) {
port, _ := cmd.Flags().GetString("port")
baud, _ := cmd.Flags().GetInt("baud")
reader := bufio.NewReader(os.Stdin)
var message []byte
for {
line, err := reader.ReadBytes('\n')
if err == io.EOF {
break
}
message = append(message, line[:]...)
}
config := &serial.Config{
Name: port,
Baud: baud,
}
serialConnection, err := serial.OpenPort(config)
if err != nil {
panic(err)
}
size, err := serialConnection.Write(message)
if err != nil {
panic(err)
}
fmt.Printf("%d bytes were written", size)
},
}
func main() {
flag.Parse()
rootCmd.AddCommand(readCmd, writeCmd)
readCmd.Flags().StringP("port", "p", defaultPort, "Port path")
readCmd.Flags().IntP("baud", "b", defaultBaud, "Baud rate")
writeCmd.Flags().StringP("port", "p", defaultPort, "Port path")
writeCmd.Flags().IntP("baud", "b", defaultBaud, "Baud rate")
err := rootCmd.Execute()
if err != nil {
panic(err)
}
}