-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmodem.go
255 lines (205 loc) · 5.71 KB
/
modem.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
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
package minigo
import (
"fmt"
"strings"
"sync"
"time"
"github.com/prometheus/client_golang/prometheus"
"go.bug.st/serial"
)
const ModemInitTimeout = 5 * time.Second
const ModemConnectTimeout = 60 * time.Second
const ModemServeTimeout = 10 * time.Millisecond
type Modem struct {
port serial.Port
init []ATCommand
ringHandler func(modem *Modem)
connected bool
mutex sync.RWMutex
tag string
connAttempt *prometheus.CounterVec
}
type ATCommand struct {
Command string `json:"command"`
Reply string `json:"reply"`
}
func NewModem(portName string, baud int, init []ATCommand, tag string, connAttempt *prometheus.CounterVec) (*Modem, error) {
port, err := serial.Open(portName, &serial.Mode{BaudRate: baud})
if err != nil {
errorLog.Printf("unable to start modem port=%s baud=%d: %s\n", port, baud, err.Error())
return nil, &ConnectorError{code: InvalidDefinition, raw: err}
}
return &Modem{
port: port,
init: init,
connected: false,
tag: tag,
connAttempt: connAttempt,
}, nil
}
func (m *Modem) Init() error {
infoLog.Printf("[modem] %s: init sequence", m.tag)
m.resetBuffers()
m.switchDTR()
// We expect a fast reply from the modem
m.port.SetReadTimeout(ModemInitTimeout)
rep := strings.NewReplacer("\n", " ", "\r", " ")
for _, atCommand := range m.init {
infoLog.Printf("[modem] %s: send command='%s'\n", m.tag, atCommand)
isAck, result, err := m.sendCommandAndAck(atCommand)
if err != nil {
return err
}
if !isAck {
return &ConnectorError{
code: InvalidInit,
raw: fmt.Errorf("[modem] %s: cannot ack command='%s' got reply='%s'", m.tag, atCommand.Command, rep.Replace(result)),
}
} else {
infoLog.Printf("[modem] %s: acknowledged command='%s' with reply='%s'", m.tag, atCommand.Command, rep.Replace(result))
}
time.Sleep(time.Second)
}
return nil
}
func (m *Modem) sendCommandAndAck(atCmd ATCommand) (bool, string, error) {
// Send initial message
if len(atCmd.Command) > 0 {
if _, err := m.port.Write([]byte(atCmd.Command + "\r\n")); err != nil {
errorLog.Printf("[modem] %s: unable to write to port=%s\n", m.tag, err.Error())
return false, "", &ConnectorError{code: Unreachable, raw: err}
}
}
var ack bool
var result string
// Wait for message
if len(atCmd.Reply) > 0 {
for {
buffer, err := m.Read()
if err != nil {
errorLog.Printf("[modem] %s: unable to read from port=%s\n", m.tag, err.Error())
return false, "", &ConnectorError{code: Unreachable, raw: err}
}
if len(buffer) == 0 {
warnLog.Printf("[modem] %s: no data replied\n", m.tag)
break
}
result += string(buffer)
if strings.Contains(result, atCmd.Reply) {
ack = true
break
} else if strings.Contains(result, "ERROR") {
errorLog.Printf("[modem] %s: modem replied ERROR\n", m.tag)
break
}
}
} else {
ack = true
}
return ack, result, nil
}
func (m *Modem) Write(b []byte) error {
_, err := m.port.Write(b)
if err != nil {
return &ConnectorError{code: Unreachable, raw: err}
}
return nil
}
func (m *Modem) Read() ([]byte, error) {
buffer := make([]byte, 256)
n, err := m.port.Read(buffer)
if err != nil {
return nil, &ConnectorError{code: Unreachable, raw: err}
}
return buffer[:n], nil
}
func (m *Modem) Connected() bool {
m.mutex.RLock()
defer m.mutex.RUnlock()
return m.connected
}
func (m *Modem) SetConnected(status bool) {
m.mutex.Lock()
defer m.mutex.Unlock()
m.connected = status
}
func (m *Modem) RingHandler(f func(modem *Modem)) {
m.ringHandler = f
}
func (m *Modem) Serve(forceRing bool) {
var err error
var status *serial.ModemStatusBits
for {
status, err = m.port.GetModemStatusBits()
if err != nil {
warnLog.Printf("[modem] %s: unable to get modem status: %s\n", m.tag, err.Error())
}
// Connection lost
if !status.DCD && m.Connected() {
warnLog.Printf("[modem] %s: lost connection\n", m.tag)
m.switchDTR()
m.SetConnected(false)
m.Init()
}
// Call recieved
if status.RI || forceRing {
infoLog.Printf("[modem] %s: we got a call\n", m.tag)
forceRing = false
m.connAttempt.With(prometheus.Labels{"source": m.tag}).Inc()
m.Connect()
// Fail to establish connection, reset the bouzin
if !m.Connected() {
m.Init()
}
}
time.Sleep(time.Second)
}
}
func (m *Modem) Connect() {
infoLog.Printf("[modem] %s: start up connection procedure\n", m.tag)
m.port.SetReadTimeout(ModemServeTimeout)
var status *serial.ModemStatusBits
var result string
start := time.Now()
for time.Since(start) < ModemConnectTimeout {
status, _ = m.port.GetModemStatusBits()
time.Sleep(1 * time.Second)
if status.DCD {
m.SetConnected(true)
infoLog.Printf("[modem] %s: connection established\n", m.tag)
break
}
}
if !m.Connected() {
m.switchDTR()
rep := strings.NewReplacer("\n", " ", "\r", " ")
errorLog.Printf("[modem] %s: unable to connect after RING got reply=%s\n", m.tag, rep.Replace(result))
return
}
m.resetBuffers()
// Start to serve the teletel content
go m.ringHandler(m)
}
func (m *Modem) Disconnect() {
if !m.Connected() {
infoLog.Printf("[modem] %s: request modem disconnect, but already disconnected\n", m.tag)
return
}
m.switchDTR()
m.SetConnected(false)
infoLog.Printf("[modem] %s: modem disconnected\n", m.tag)
}
func (m *Modem) switchDTR() {
m.port.SetDTR(false)
time.Sleep(2 * time.Second)
m.port.SetDTR(true)
}
func (m *Modem) resetBuffers() {
// Cleanup all the In/Out buffers between the DCE and the DTE
if err := m.port.ResetInputBuffer(); err != nil {
errorLog.Printf("[modem] %s:unable to reset input buffer: %s\n", m.tag, err.Error())
}
if err := m.port.ResetOutputBuffer(); err != nil {
errorLog.Printf("[modem] %s:unable to reset output buffer: %s\n", m.tag, err.Error())
}
}