-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
executable file
·88 lines (75 loc) · 2.07 KB
/
main.go
File metadata and controls
executable file
·88 lines (75 loc) · 2.07 KB
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
package main
import (
"flag"
"fmt"
"io"
"log"
"strings"
"time"
"github.com/jacobsa/go-serial/serial"
)
func main() {
portName := flag.String("port", "/dev/ttyUSB0", "serial port to test (/dev/ttyUSB0, etc)")
portName = flag.String("p", "/dev/ttyUSB0", "serial port to test (/dev/ttyUSB0, etc) (shorthand)")
baud := flag.Uint("baud", 115200, "Baud rate")
stopbits := flag.Uint("stopbits", 1, "Stop bits")
databits := flag.Uint("databits", 8, "Data bits")
command := flag.String("command", "", "AT command to be sent (e.g. at+cfun?)")
command = flag.String("c", "", "AT command to be sent (e.g. at+cfun?) (shorthand)")
expect := flag.String("expect", "OK", "AT reply to look for before exiting")
expect = flag.String("e", "OK", "AT reply to look for before exiting (shorthand)")
timeout := flag.Uint("timeout", 3, "Reply timeout")
timeout = flag.Uint("t", 3, "Reply timeout (shorthand)")
flag.Parse()
options := serial.OpenOptions{
PortName: *portName,
BaudRate: *baud,
DataBits: *databits,
StopBits: *stopbits,
MinimumReadSize: 4,
}
port, err := serial.Open(options)
if err != nil {
log.Fatalf("serial.Open: %v", err)
}
defer port.Close()
if !strings.HasPrefix(*command, "at") && !strings.HasPrefix(*command, "AT") {
*command = "AT" + *command
}
// Write 4 bytes to the port.
b := []byte(*command + "\r\n")
_, err = port.Write(b)
if err != nil {
log.Fatalf("port.Write: %v", err)
}
fmt.Println(">>> ", *command)
r := make(chan string)
go func() {
for {
buf := make([]byte, 128)
n, err := port.Read(buf)
if err != nil {
fmt.Println(err)
if err != io.EOF {
r <- fmt.Sprintf("Error reading from serial port: %s", err)
}
r <- fmt.Sprintf("end of stream")
}
fmt.Println(string(buf[:n]))
if strings.Contains(string(buf[:n]), *expect) {
r <- ""
}
if strings.Contains(string(buf[:n]), "ERROR") {
r <- ""
}
}
}()
select {
case res := <-r:
if res != "" {
fmt.Println(r)
}
case <-time.After(time.Duration(*timeout) * time.Second):
fmt.Println("Timeout expired")
}
}