-
Notifications
You must be signed in to change notification settings - Fork 8
/
server.go
352 lines (309 loc) · 7.46 KB
/
server.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
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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package jt809server
import (
"fmt"
"io"
"net"
"runtime/debug"
"sync"
"time"
"github.com/lai323/jt809server/jt809"
"github.com/go-kit/log"
"github.com/go-kit/log/level"
)
type Server struct {
UserID uint32
Password string
GNSSCenterID uint32
UpLinkIP string
UpLinkPort uint16
DownLinkIP string
DownLinkPort uint16
upconn net.Conn
downconn net.Conn
logger log.Logger
receiveChan chan jt809.Packet
sngen *jt809.SerialNoGenerater
mtx sync.Mutex
exitedChan chan struct{}
OnConnect func()
}
func NewServer(logger log.Logger) *Server {
return &Server{
logger: logger,
receiveChan: make(chan jt809.Packet),
sngen: jt809.NewSerialNoGenerater(),
exitedChan: make(chan struct{}),
}
}
func (srv *Server) UpRealLocation(loc *jt809.UpExgMsg) {
srv.send(loc)
}
func (srv *Server) startLinktest(p jt809.Packet) {
for {
time.Sleep(time.Second * 50)
select {
case <-srv.exitedChan:
return
default:
}
srv.send(p)
}
}
func (srv *Server) waitdowconn(ch chan net.Conn) {
addr := fmt.Sprintf(":%d", srv.DownLinkPort)
ln, err := net.Listen("tcp", addr)
if err != nil {
level.Error(srv.logger).Log("msg", "waitdowconn Listen", "error", err)
close(ch)
return
}
var tempDelay time.Duration
for {
level.Debug(srv.logger).Log("msg", "waitdowconn wait connect", "Addr", ln.Addr())
conn, err := ln.Accept()
if err != nil {
select {
case <-srv.exitedChan:
close(ch)
return
default:
}
if ne, ok := err.(net.Error); ok && ne.Temporary() {
if tempDelay == 0 {
tempDelay = 5 * time.Millisecond
} else {
tempDelay *= 2
}
if max := 1 * time.Second; tempDelay > max {
tempDelay = max
}
level.Debug(srv.logger).Log(
"msg", "dowconnConnet listener Accept temporary error",
"error", err,
"retrying", tempDelay)
time.Sleep(tempDelay)
continue
}
level.Error(srv.logger).Log(
"msg", "dowconnConnet listener Accept error",
"error", err)
close(ch)
return
}
ch <- conn
return
}
}
func (srv *Server) login() {
req := jt809.NewUpConnectReq()
req.UserID = srv.UserID
req.Password = jt809.FixedLengthString(srv.Password, 8, false)
req.DownLinkIP = jt809.FixedLengthString(srv.DownLinkIP, 32, false)
req.DownLinkPort = srv.DownLinkPort
srv.send(req)
}
func (srv *Server) connect() bool {
// 等待建立从链路
ch := make(chan net.Conn)
safego(func() { srv.waitdowconn(ch) }, srv.logger, "waitdowconn panic")
// 建立主链路
addr := fmt.Sprintf("%s:%d", srv.UpLinkIP, srv.UpLinkPort)
conn, err := net.Dial("tcp", addr)
if err != nil {
level.Error(srv.logger).Log("msg", "connect Dial", "error", err)
return false
}
// 启动主链路消息接收
srv.upconn = conn
srv.login()
safego(func() { srv.receive(srv.upconn, "upconn") }, srv.logger, "upconn receive panic")
// 启动消息处理
safego(func() { defer srv.Shutdown(); srv.handle() }, srv.logger, "handle panic")
// 启动从链路消息接收
var ok bool
select {
case conn, ok = <-ch:
if !ok {
return false
}
case <-srv.exitedChan:
return false
}
srv.downconn = conn
safego(func() { srv.receive(srv.downconn, "downconn") }, srv.logger, "downconn receive panic")
return true
}
func (srv *Server) receive(conn net.Conn, connname string) {
level.Debug(srv.logger).Log("msg", "start receive", "conn", connname)
dec := jt809.NewDecoder(conn)
for {
p, err := dec.Decode()
if err != nil {
select {
case <-srv.exitedChan:
return
default:
}
if err != io.EOF {
level.Error(srv.logger).Log("msg", "Server receive Decode error", "error", err)
}
break
}
level.Debug(srv.logger).Log("msg", "receive", "conn", connname, "packet", p)
srv.receiveChan <- p
}
}
func (srv *Server) send(p jt809.Packet) {
srv.mtx.Lock()
defer srv.mtx.Unlock()
lt := p.LinkType()
var conn net.Conn = nil
var connname string
if lt == jt809.DownLinkOnly && srv.downconn == nil {
level.Error(srv.logger).Log(
"msg", "Server send downconn unavailable", "packet", p)
return
}
if lt == jt809.UpLinkOnly && srv.upconn == nil {
level.Error(srv.logger).Log(
"msg", "Server send upconn unavailable", "packet", p)
return
}
if lt == jt809.DownLinkOnly {
connname = "downconn"
conn = srv.downconn
}
if lt == jt809.UpLinkOnly {
connname = "upconn"
conn = srv.upconn
}
if lt == jt809.DownLink {
connname = "downconn"
conn = srv.downconn
if conn == nil {
connname = "upconn"
conn = srv.upconn
}
}
if lt == jt809.UpLink {
connname = "upconn"
conn = srv.upconn
if conn == nil {
connname = "downconn"
conn = srv.downconn
}
}
if conn == nil {
level.Error(srv.logger).Log("msg", "Server send not connect available", "packet", p)
}
h := p.Header()
h.SerialNo = srv.sngen.GetByType(h.Type)
h.GNSSCenterID = srv.GNSSCenterID
h.Version = []byte{1, 0, 0}
h.Encrypt = 0
h.EncryptKey = 0
err := jt809.NewEncoder(conn).Encode(p)
if err != nil {
level.Error(srv.logger).Log("msg", "Server send Encode", "packet", p)
}
level.Debug(srv.logger).Log("msg", "send", "conn", connname, "packet", p)
}
func (srv *Server) Serve() error {
level.Debug(srv.logger).Log("msg", "Server start")
ok := srv.connect()
if !ok {
srv.Shutdown()
return nil
}
if srv.OnConnect != nil {
func() {
defer func() {
if err := recover(); err != nil {
level.Error(srv.logger).Log(
"msg", "server OnConnect panic",
"error", err,
"stack", debug.Stack())
}
}()
srv.OnConnect()
}()
}
<-srv.exitedChan
return nil
}
func (srv *Server) Shutdown() {
select {
case <-srv.exitedChan:
// Already closed. Don't close again.
default:
close(srv.exitedChan)
if srv.upconn != nil {
srv.upconn.Close()
}
if srv.downconn != nil {
srv.downconn.Close()
}
close(srv.receiveChan)
}
}
func (srv *Server) handle() {
for tmp := range srv.receiveChan {
handle := func(p jt809.Packet) {
defer func() {
if err := recover(); err != nil {
level.Error(srv.logger).Log(
"msg", "client handle panic",
"packet", p,
"error", err,
"stack", debug.Stack())
}
}()
header := p.Header()
switch header.Type {
case jt809.UP_CONNECT_RSP:
srv.onUpConnectRsp(p.(*jt809.UpConnectRsp))
case jt809.DOWN_CONNECT_REQ:
srv.onDownConnectReq(p.(*jt809.DownConnectReq))
case jt809.DOWN_LINKTEST_REQ:
srv.onDownLinkTestReq(p.(*jt809.DownLinkTestReq))
case jt809.UP_LINKTEST_RSP:
srv.onUpLinkTestRsp(p.(*jt809.UpLinkTestRsp))
default:
level.Info(srv.logger).Log(
"msg", "Server handle unsupport packet", "packet", p)
}
}
go handle(tmp)
}
}
func (srv *Server) onUpConnectRsp(p *jt809.UpConnectRsp) {
level.Info(srv.logger).Log("msg", "login response",
"Result", p.Result, "VerifyCode", p.VerifyCode)
// 如果添加了重连逻辑,注意不要启动多个 link test
testp := jt809.NewUpLinkTestReq()
safego(func() { srv.startLinktest(testp) }, srv.logger, "upconn linktest panic")
}
func (srv *Server) onDownConnectReq(p *jt809.DownConnectReq) {
rsp := jt809.NewDownConnectRsp()
rsp.Result = 0
srv.send(rsp)
}
func (srv *Server) onDownLinkTestReq(p *jt809.DownLinkTestReq) {
rsp := jt809.NewDownLinkTestRsp()
srv.send(rsp)
}
func (srv *Server) onUpLinkTestRsp(p *jt809.UpLinkTestRsp) {
}
func safego(goroutine func(), logger log.Logger, errmsg string) {
go func() {
defer func() {
if err := recover(); err != nil {
level.Error(logger).Log(
"msg", errmsg,
"error", err,
"stack", debug.Stack())
}
}()
goroutine()
}()
}