-
Notifications
You must be signed in to change notification settings - Fork 10
/
main.go
266 lines (249 loc) · 6.95 KB
/
main.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
package main
import (
"context"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"github.com/cloudwego/hertz/pkg/app"
"github.com/cloudwego/hertz/pkg/app/server"
"github.com/cuteLittleDevil/go-jt808/protocol/jt808"
"github.com/cuteLittleDevil/go-jt808/protocol/model"
"github.com/cuteLittleDevil/go-jt808/protocol/utils"
"github.com/cuteLittleDevil/go-jt808/service"
"github.com/cuteLittleDevil/go-jt808/shared/consts"
"github.com/hertz-contrib/cors"
"jt1078/help"
"log/slog"
"net/http"
"os"
"strings"
"sync"
"time"
)
var goJt808 *service.GoJT808
func init() {
logger := slog.New(slog.NewJSONHandler(os.Stdout, &slog.HandlerOptions{
AddSource: true,
Level: slog.LevelDebug,
ReplaceAttr: nil,
}))
slog.SetDefault(logger)
goJt808 = service.New(
service.WithHostPorts("0.0.0.0:8082"),
service.WithNetwork("tcp"),
service.WithCustomTerminalEventer(func() service.TerminalEventer {
return &help.LogTerminal{}
}),
)
go goJt808.Run()
}
func main() {
h := server.Default(
server.WithHostPorts("0.0.0.0:17001"),
)
h.Use(cors.New(cors.Config{
AllowOrigins: []string{"*"},
AllowMethods: []string{"GET", "POST", "PUT", "PATCH", "DELETE", "HEAD"},
AllowHeaders: []string{"Origin", "Content-Length", "Content-Type", "Authorization", "Token", "Accept"},
AllowCredentials: true,
MaxAge: 12 * time.Hour,
}))
customRoute(h)
h.NoRoute(func(ctx context.Context, c *app.RequestContext) {
fmt.Println("未知路由", string(c.Request.Method()),
string(c.Request.Path()), string(c.Request.QueryString()))
c.String(http.StatusOK, "-1")
})
h.GET("/", func(ctx context.Context, c *app.RequestContext) {
c.Redirect(http.StatusMovedPermanently, []byte("index.html"))
})
h.StaticFile("/index.html", "tstrtvs.html")
h.Spin()
}
func customRoute(h *server.Hertz) {
apiRtvsV1 := h.Group("/api/")
apiRtvsV1.GET("/VideoControl", videoControl)
apiRtvsV1.POST("/WCF0x9105", wcf0x9105)
}
func wcf0x9105(_ context.Context, c *app.RequestContext) {
content := c.DefaultPostForm("Content", "")
type RtvsResponse []struct {
Sim string `json:"Sim"`
NotifyList []struct {
Channel byte `json:"Channel"`
PacketLossRate byte `json:"PacketLossRate"`
} `json:"NotifyList"`
}
var rtvsResponse RtvsResponse
_ = json.Unmarshal([]byte(content), &rtvsResponse)
var (
wg sync.WaitGroup
once sync.Once
complete = make(chan error, 1)
)
defer close(complete)
for _, v := range rtvsResponse {
sim := v.Sim
for _, notify := range v.NotifyList {
wg.Add(1)
go func(sim string, channel, packetLossRate byte) {
defer wg.Done()
tmp := &model.P0x9105{
ChannelNo: channel,
PackageLossRate: packetLossRate,
}
replyMsg := goJt808.SendActiveMessage(&service.ActiveMessage{
Key: strings.TrimLeft(sim, "0"), //注意去掉前面的0
Command: consts.P9105AudioVideoControlStatusNotice,
Body: tmp.Encode(),
OverTimeDuration: 3 * time.Second,
})
if replyMsg.ExtensionFields.Err != nil {
once.Do(func() {
complete <- replyMsg.ExtensionFields.Err
})
return
}
}(sim, notify.Channel, notify.PacketLossRate)
}
}
wg.Wait()
select {
case err := <-complete:
slog.Warn("9105",
slog.Any("err", err))
c.String(http.StatusInternalServerError, "-1")
return
default:
}
c.String(http.StatusOK, "1")
}
func videoControl(_ context.Context, c *app.RequestContext) {
content := c.DefaultQuery("Content", "")
activeMsg, err := rtvs2jt1078Pack(content)
if err != nil {
slog.Warn("rtvs to jt1078 fail",
slog.String("content", content),
slog.Any("err", err))
c.String(http.StatusBadRequest, "-1")
return
}
replyMsg := goJt808.SendActiveMessage(activeMsg)
if replyMsg.ExtensionFields.Err != nil {
slog.Warn("send active message fail",
slog.String("content", content),
slog.Any("err", replyMsg.ExtensionFields.Err))
c.String(http.StatusBadRequest, "-1")
return
}
type Handler struct {
Parse func(jtMsg *jt808.JTMessage) error
CustomSignFunc func() string
}
var handler Handler
switch activeMsg.Command {
case consts.P9205QueryResourceList:
tmp := &model.T0x1205{}
handler.Parse = tmp.Parse
handler.CustomSignFunc = func() string {
return "9205-" + replyMsg.JTMessage.Header.TerminalPhoneNo
}
case consts.P9201SendVideoRecordRequest:
tmp := &model.P0x9201{}
handler.Parse = tmp.Parse
handler.CustomSignFunc = func() string {
return "9201-" + replyMsg.JTMessage.Header.TerminalPhoneNo + fmt.Sprintf("-%d", tmp.ChannelNo)
}
case consts.P9206FileUploadInstructions:
tmp := &model.P0x9206{}
handler.Parse = tmp.Parse
handler.CustomSignFunc = func() string {
return fmt.Sprintf("%d", activeMsg.ExtensionFields.PlatformSeq)
}
}
if replyMsg.JTMessage.Header.ID == uint16(consts.T0001GeneralRespond) {
tmp := &model.T0x0001{}
handler.Parse = tmp.Parse
handler.CustomSignFunc = func() string {
if tmp.Result == 0 {
return "1"
}
return "-1"
}
}
if handler.Parse == nil || handler.CustomSignFunc == nil {
c.String(http.StatusBadRequest, "-1")
return
}
if err := handler.Parse(replyMsg.JTMessage); err != nil {
slog.Warn("send active message fail",
slog.String("content", content),
slog.String("reply", fmt.Sprintf("%x", replyMsg.ExtensionFields.TerminalData)),
slog.Any("err", replyMsg.ExtensionFields.Err))
c.String(http.StatusBadRequest, "-1")
}
sign := handler.CustomSignFunc()
c.String(http.StatusOK, sign)
return
}
func rtvs2jt1078Pack(content string) (*service.ActiveMessage, error) {
if len(content) < 24 {
return nil, errors.New("content too short")
}
data := rtvsContent2Data(content)
jtMsg := jt808.NewJTMessage()
if err := jtMsg.Decode(data); err != nil {
return nil, err
}
type Handler interface {
Protocol() consts.JT808CommandType
Parse(jtMsg *jt808.JTMessage) error
Encode() []byte
}
var (
handler Handler
overTime time.Duration
)
overTime = 3 * time.Second
switch content[:4] {
case "9101":
handler = &model.P0x9101{}
case "9102":
handler = &model.P0x9102{}
case "9201":
handler = &model.P0x9201{}
overTime = 5 * time.Second
case "9202":
handler = &model.P0x9202{}
case "9205":
handler = &model.P0x9205{}
overTime = 10 * time.Second
case "9206":
handler = &model.P0x9206{}
}
if handler == nil {
return nil, fmt.Errorf("unknown command: %s", content[:4])
}
if err := handler.Parse(jtMsg); err != nil {
return nil, err
}
return &service.ActiveMessage{
Key: jtMsg.Header.TerminalPhoneNo,
Command: handler.Protocol(),
Body: handler.Encode(),
OverTimeDuration: overTime,
}, nil
}
func rtvsContent2Data(content string) []byte {
content = strings.ReplaceAll(content, "7d", "7d01")
content = strings.ReplaceAll(content, "7e", "7d02")
body, _ := hex.DecodeString(content)
code := utils.CreateVerifyCode(body)
data := make([]byte, 0, 20)
data = append(data, 0x7e)
data = append(data, body...)
data = append(data, code)
data = append(data, 0x7e)
return data
}