-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgsmmodem.go
85 lines (75 loc) · 1.55 KB
/
gsmmodem.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
package main
import (
"bufio"
"flag"
"github.com/tarm/goserial"
"io"
"log"
"strings"
"fmt"
)
var (
port = flag.String("port", "/dev/cu.HUAWEIMobile-Pcui", "port modem is connected on e.g. /dev/cu.HUAWEIMobile-Pcui on Mac OSX")
)
type GsmModem struct {
port string
readWriter io.ReadWriteCloser
}
func NewGsmModem(port string) *GsmModem {
return &GsmModem{port: port}
}
func (g *GsmModem) Connect() (io.ReadWriteCloser, error) {
c := &serial.Config{Name: g.port, Baud: 115200}
s, err := serial.OpenPort(c)
if err != nil {
log.Fatal(err)
}
//defer s.Close()
g.readWriter = s
return g.readWriter, nil
}
func (g *GsmModem) SendCommand(command string) (lines []string, response string, isOK bool) {
_, err := g.readWriter.Write([]byte(command + "\n"))
if err != nil {
log.Fatal(err)
}
r := bufio.NewReader(g.readWriter)
for {
read, _, err := r.ReadLine()
if err != nil {
isOK = false
return
}
strread := string(read)
fmt.Println(strread)
if strings.Contains(strread, "OK") {
response = strread
isOK = true
return
}
if strings.Contains(strread, "ERROR") {
response = strread
isOK = false
return
}
lines = append(lines, strread)
}
return
}
func main() {
flag.Parse()
if len(*port) == 0 {
log.Fatal("--port flag not provided")
}
modem := NewGsmModem(*port)
modem.Connect()
_, _, isOK := modem.SendCommand("AT+CMGF=1")
if isOK != true {
log.Fatal("failed to set modem on text mode")
}
for{
resp, lines, _ := modem.SendCommand("AT+CMGL=ALL")
fmt.Println(resp)
fmt.Println(lines)
}
}