-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathatcom.go
More file actions
300 lines (247 loc) · 6.44 KB
/
Copy pathatcom.go
File metadata and controls
300 lines (247 loc) · 6.44 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
/*
Created by: Yasin Kaya (selengalp), yasinkaya.121@gmail.com, 2023
Copyright (c) 2023 Sixfab Inc.
*/
package atcom
import (
"context"
"errors"
"os/exec"
"strings"
"time"
"github.com/tarm/serial"
)
type Atcom struct {
serial SerialModel
shell ShellModel
}
// Serial Implementation for normal usage
type Serial struct{}
// Serial interface
type SerialModel interface {
OpenPort(c *serial.Config) (*serial.Port, error)
Write(port *serial.Port, command []byte) (n int, err error)
Close(port *serial.Port) (err error)
Read(port *serial.Port, buffer []byte) (n int, err error)
Flush(port *serial.Port) error
}
// Serial implements Serial interface
func (s *Serial) OpenPort(c *serial.Config) (*serial.Port, error) {
return serial.OpenPort(c)
}
func (s *Serial) Write(port *serial.Port, command []byte) (n int, err error) {
return port.Write([]byte(command))
}
func (s *Serial) Close(port *serial.Port) (err error) {
return port.Close()
}
func (s *Serial) Read(port *serial.Port, buffer []byte) (n int, err error) {
return port.Read(buffer)
}
func (s *Serial) Flush(port *serial.Port) error {
return port.Flush()
}
// Shell Implementation for normal usage
type Shell struct{}
// Shell interface
type ShellModel interface {
Command(name string, arg ...string) (string, error)
}
// RealShell implements Shell interface
func (s *Shell) Command(name string, arg ...string) (string, error) {
cmd := exec.Command(name, arg...)
output, err := cmd.Output()
return string(output), err
}
// NewAtcom creates a new Atcom instance with default serial and shell implementations
func NewAtcom(s SerialModel, sh ShellModel) *Atcom {
if s == nil {
s = &Serial{}
}
if sh == nil {
sh = &Shell{}
}
return &Atcom{
serial: s,
shell: sh,
}
}
// Function to open serial port
func (t *Atcom) open(portname string, baudrate int) (port *serial.Port, err error) {
if baudrate == 0 {
baudrate = 115200
}
if portname == "" {
return nil, errors.New("serialport is required")
}
config := &serial.Config{
Name: portname,
Baud: baudrate,
ReadTimeout: time.Millisecond * 100,
}
return t.serial.OpenPort(config)
}
// SendAT sends AT command to modem and returns response
func (t *Atcom) SendAT(c *ATCommand) *ATCommand {
command := c.Command
lineEnd := c.LineEnd
timeout := c.Timeout
desired := c.Desired
fault := c.Fault
portname := c.SerialAttr.Port
baudrate := c.SerialAttr.Baud
responseChan := c.ResponseChan
urc := c.Urc
serialPort, err := t.open(portname, baudrate)
if err != nil {
c.Error = err
return c
}
defer t.serial.Close(serialPort)
if lineEnd {
command += "\r\n"
}
// If urc is true, do not send command to serial port.
if !urc {
// drain serial buffer before sending command
t.serial.Flush(serialPort)
// send command to serial port
_, err = t.serial.Write(serialPort, []byte(command))
}
if err != nil {
c.Error = err
return c
}
data := make([]string, 0)
responseBuffer := ""
timeoutDuration := time.Duration(timeout) * time.Second
found := make(chan error)
ctxScan, cancelScan := context.WithCancel(context.Background())
defer cancelScan()
go func(ctx context.Context) {
response := ""
buf := make([]byte, 1024)
leftFromLastRead := make([]byte, 1024)
nLeftBytes := 0
for {
select {
case <-ctx.Done():
close(found)
return
default:
n, err := t.serial.Read(serialPort, buf)
if err != nil {
if err.Error() == "EOF" {
continue
}
found <- err
return
}
// if no data, continue
if n == 0 {
continue
}
response = string(leftFromLastRead[:nLeftBytes]) + string(buf[:n]) // prepend left bytes from last read
nLeftBytes = 0 // reset left bytes count
// replace \r with \n for uniformity
response = strings.ReplaceAll(response, "\r", "\n")
lines := strings.Split(response, "\n")
responseBuffer += response
if len(lines) == 1 && n > 0 {
// save all bytes to leftFromLastRead
copy(leftFromLastRead, []byte(response))
nLeftBytes = n
continue
}
// split response to lines and trim spaces
for index, line := range lines {
line = strings.TrimSpace(line)
// skip empty lines
if line == "" {
continue
}
// if last line and not ended with \n, save it for next read
if index == len(lines)-1 {
// save left bytes for next read
copy(leftFromLastRead, []byte(line))
nLeftBytes = len(line)
break
}
data = append(data, line)
// send line to response channel if exists
if responseChan != nil {
c.ResponseChan <- line
}
}
if responseChan == nil { // if responseChan is not existed
for _, line := range data {
if line == "OK" {
// check desired and fault existed in response
if desired != nil || fault != nil {
ok := false
for _, desiredStr := range desired {
if strings.Contains(responseBuffer, desiredStr) {
ok = true
found <- nil
return
}
}
for _, faultStr := range fault {
if strings.Contains(responseBuffer, faultStr) {
ok = true
found <- errors.New("faulty response detected")
return
}
}
if !ok {
found <- errors.New("desired or fault response not found")
return
}
} else {
found <- nil
return
}
}
}
} else { // if responseChan is existed
// check desired and fault existed in response
if desired != nil || fault != nil {
for _, desiredStr := range desired {
if strings.Contains(responseBuffer, desiredStr) {
found <- nil
return
}
}
for _, faultStr := range fault {
if strings.Contains(responseBuffer, faultStr) {
found <- errors.New("faulty response detected")
return
}
}
}
}
// check "ERROR" existed in response
if strings.Contains(responseBuffer, "ERROR") {
// remove \n from responseBuffer for cleaner error message
responseBuffer = strings.ReplaceAll(responseBuffer, "\n", "")
found <- errors.New("modem error - " + responseBuffer)
return
}
}
}
}(ctxScan)
timeoutCh := time.After(timeoutDuration)
for {
select {
case err := <-found:
c.Response = data
c.Error = err
return c
case <-timeoutCh:
cancelScan()
c.Response = data
c.Error = errors.New("timeout")
return c
}
}
}