-
Notifications
You must be signed in to change notification settings - Fork 95
/
device.go
540 lines (503 loc) · 14.9 KB
/
device.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
package gb28181
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"time"
"go.uber.org/zap"
"m7s.live/engine/v4"
"m7s.live/engine/v4/log"
"m7s.live/plugin/gb28181/v4/utils"
"github.com/ghettovoice/gosip/sip"
myip "github.com/husanpao/ip"
)
const TIME_LAYOUT = "2006-01-02T15:04:05"
// Record 录像
type Record struct {
DeviceID string
Name string
FilePath string
Address string
StartTime string
EndTime string
Secrecy int
Type string
}
func (r *Record) GetPublishStreamPath() string {
return fmt.Sprintf("%s/%s", r.DeviceID, r.StartTime)
}
var (
Devices sync.Map
DeviceNonce sync.Map //保存nonce防止设备伪造
DeviceRegisterCount sync.Map //设备注册次数
)
type DeviceStatus string
const (
DeviceRegisterStatus = "REGISTER"
DeviceRecoverStatus = "RECOVER"
DeviceOnlineStatus = "ONLINE"
DeviceOfflineStatus = "OFFLINE"
DeviceAlarmedStatus = "ALARMED"
)
type Device struct {
ID string
Name string
Manufacturer string
Model string
Owner string
RegisterTime time.Time
UpdateTime time.Time
LastKeepaliveAt time.Time
Status DeviceStatus
SN int
Addr sip.Address `json:"-" yaml:"-"`
SipIP string //设备对应网卡的服务器ip
MediaIP string //设备对应网卡的服务器ip
NetAddr string
channelMap sync.Map
subscriber struct {
CallID string
Timeout time.Time
}
lastSyncTime time.Time
GpsTime time.Time //gps时间
Longitude string //经度
Latitude string //纬度
*log.Logger `json:"-" yaml:"-"`
}
func (d *Device) MarshalJSON() ([]byte, error) {
type Alias Device
data := &struct {
Channels []*Channel
*Alias
}{
Alias: (*Alias)(d),
}
d.channelMap.Range(func(key, value interface{}) bool {
data.Channels = append(data.Channels, value.(*Channel))
return true
})
return json.Marshal(data)
}
func (c *GB28181Config) RecoverDevice(d *Device, req sip.Request) {
from, _ := req.From()
d.Addr = sip.Address{
DisplayName: from.DisplayName,
Uri: from.Address,
}
deviceIp := req.Source()
servIp := req.Recipient().Host()
//根据网卡ip获取对应的公网ip
sipIP := c.routes[servIp]
//如果相等,则服务器是内网通道.海康摄像头不支持...自动获取
if strings.LastIndex(deviceIp, ".") != -1 && strings.LastIndex(servIp, ".") != -1 {
if servIp[0:strings.LastIndex(servIp, ".")] == deviceIp[0:strings.LastIndex(deviceIp, ".")] || sipIP == "" {
sipIP = servIp
}
}
//如果用户配置过则使用配置的
if c.SipIP != "" {
sipIP = c.SipIP
} else if sipIP == "" {
sipIP = myip.InternalIPv4()
}
mediaIp := sipIP
if c.MediaIP != "" {
mediaIp = c.MediaIP
}
d.Info("RecoverDevice", zap.String("deviceIp", deviceIp), zap.String("servIp", servIp), zap.String("sipIP", sipIP), zap.String("mediaIp", mediaIp))
d.Status = DeviceRegisterStatus
d.SipIP = sipIP
d.MediaIP = mediaIp
d.NetAddr = deviceIp
d.UpdateTime = time.Now()
}
func (c *GB28181Config) StoreDevice(id string, req sip.Request) (d *Device) {
from, _ := req.From()
deviceAddr := sip.Address{
DisplayName: from.DisplayName,
Uri: from.Address,
}
deviceIp := req.Source()
if _d, loaded := Devices.Load(id); loaded {
d = _d.(*Device)
d.UpdateTime = time.Now()
d.NetAddr = deviceIp
d.Addr = deviceAddr
d.Debug("UpdateDevice", zap.String("netaddr", d.NetAddr))
} else {
servIp := req.Recipient().Host()
//根据网卡ip获取对应的公网ip
sipIP := c.routes[servIp]
//如果相等,则服务器是内网通道.海康摄像头不支持...自动获取
if strings.LastIndex(deviceIp, ".") != -1 && strings.LastIndex(servIp, ".") != -1 {
if servIp[0:strings.LastIndex(servIp, ".")] == deviceIp[0:strings.LastIndex(deviceIp, ".")] || sipIP == "" {
sipIP = servIp
}
}
//如果用户配置过则使用配置的
if c.SipIP != "" {
sipIP = c.SipIP
} else if sipIP == "" {
sipIP = myip.InternalIPv4()
}
mediaIp := sipIP
if c.MediaIP != "" {
mediaIp = c.MediaIP
}
d = &Device{
ID: id,
RegisterTime: time.Now(),
UpdateTime: time.Now(),
Status: DeviceRegisterStatus,
Addr: deviceAddr,
SipIP: sipIP,
MediaIP: mediaIp,
NetAddr: deviceIp,
Logger: GB28181Plugin.With(zap.String("id", id)),
}
d.Info("StoreDevice", zap.String("deviceIp", deviceIp), zap.String("servIp", servIp), zap.String("sipIP", sipIP), zap.String("mediaIp", mediaIp))
Devices.Store(id, d)
c.SaveDevices()
}
return
}
func (c *GB28181Config) ReadDevices() {
if f, err := os.OpenFile("devices.json", os.O_RDONLY, 0644); err == nil {
defer f.Close()
var items []*Device
if err = json.NewDecoder(f).Decode(&items); err == nil {
for _, item := range items {
if time.Since(item.UpdateTime) < conf.RegisterValidity {
item.Status = "RECOVER"
item.Logger = GB28181Plugin.With(zap.String("id", item.ID))
Devices.Store(item.ID, item)
}
}
}
}
}
func (c *GB28181Config) SaveDevices() {
var item []any
Devices.Range(func(key, value any) bool {
item = append(item, value)
return true
})
if f, err := os.OpenFile("devices.json", os.O_WRONLY|os.O_CREATE, 0644); err == nil {
defer f.Close()
encoder := json.NewEncoder(f)
encoder.SetIndent("", " ")
encoder.Encode(item)
}
}
func (d *Device) addOrUpdateChannel(info ChannelInfo) (c *Channel) {
if old, ok := d.channelMap.Load(info.DeviceID); ok {
c = old.(*Channel)
c.ChannelInfo = info
} else {
c = &Channel{
Device: d,
ChannelInfo: info,
Logger: d.Logger.With(zap.String("channel", info.DeviceID)),
}
if s := engine.Streams.Get(fmt.Sprintf("%s/%s/rtsp", c.Device.ID, c.DeviceID)); s != nil {
c.LiveSubSP = s.Path
} else {
c.LiveSubSP = ""
}
d.channelMap.Store(info.DeviceID, c)
}
return
}
func (d *Device) deleteChannel(DeviceID string) {
d.channelMap.Delete(DeviceID)
}
func (d *Device) UpdateChannels(list ...ChannelInfo) {
for _, c := range list {
if _, ok := conf.ignores[c.DeviceID]; ok {
continue
}
//当父设备非空且存在时、父设备节点增加通道
if c.ParentID != "" {
path := strings.Split(c.ParentID, "/")
parentId := path[len(path)-1]
//如果父ID并非本身所属设备,一般情况下这是因为下级设备上传了目录信息,该信息通常不需要处理。
// 暂时不考虑级联目录的实现
if d.ID != parentId {
if v, ok := Devices.Load(parentId); ok {
parent := v.(*Device)
parent.addOrUpdateChannel(c)
continue
} else {
c.Model = "Directory " + c.Model
c.Status = "NoParent"
}
}
}
//本设备增加通道
channel := d.addOrUpdateChannel(c)
if conf.InviteMode == INVIDE_MODE_AUTO {
channel.TryAutoInvite(&InviteOptions{})
}
if s := engine.Streams.Get("sub/" + c.DeviceID); s != nil {
channel.LiveSubSP = s.Path
} else {
channel.LiveSubSP = ""
}
}
}
func (d *Device) CreateRequest(Method sip.RequestMethod) (req sip.Request) {
d.SN++
callId := sip.CallID(utils.RandNumString(10))
userAgent := sip.UserAgentHeader("Monibuca")
maxForwards := sip.MaxForwards(70) //增加max-forwards为默认值 70
cseq := sip.CSeq{
SeqNo: uint32(d.SN),
MethodName: Method,
}
port := sip.Port(conf.SipPort)
serverAddr := sip.Address{
//DisplayName: sip.String{Str: d.config.Serial},
Uri: &sip.SipUri{
FUser: sip.String{Str: conf.Serial},
FHost: d.SipIP,
FPort: &port,
},
Params: sip.NewParams().Add("tag", sip.String{Str: utils.RandNumString(9)}),
}
req = sip.NewRequest(
"",
Method,
d.Addr.Uri,
"SIP/2.0",
[]sip.Header{
serverAddr.AsFromHeader(),
d.Addr.AsToHeader(),
&callId,
&userAgent,
&cseq,
&maxForwards,
serverAddr.AsContactHeader(),
},
"",
nil,
)
req.SetTransport(conf.SipNetwork)
req.SetDestination(d.NetAddr)
//fmt.Printf("构建请求参数:%s", *&req)
// requestMsg.DestAdd, err2 = d.ResolveAddress(requestMsg)
// if err2 != nil {
// return nil
// }
//intranet ip , let's resolve it with public ip
// var deviceIp, deviceSourceIP net.IP
// switch addr := requestMsg.DestAdd.(type) {
// case *net.UDPAddr:
// deviceIp = addr.IP
// case *net.TCPAddr:
// deviceIp = addr.IP
// }
// switch addr2 := d.SourceAddr.(type) {
// case *net.UDPAddr:
// deviceSourceIP = addr2.IP
// case *net.TCPAddr:
// deviceSourceIP = addr2.IP
// }
// if deviceIp.IsPrivate() && !deviceSourceIP.IsPrivate() {
// requestMsg.DestAdd = d.SourceAddr
// }
return
}
func (d *Device) Subscribe() int {
request := d.CreateRequest(sip.SUBSCRIBE)
if d.subscriber.CallID != "" {
callId := sip.CallID(utils.RandNumString(10))
request.AppendHeader(&callId)
}
expires := sip.Expires(3600)
d.subscriber.Timeout = time.Now().Add(time.Second * time.Duration(expires))
contentType := sip.ContentType("Application/MANSCDP+xml")
request.AppendHeader(&contentType)
request.AppendHeader(&expires)
request.SetBody(BuildCatalogXML(d.SN, d.ID), true)
response, err := d.SipRequestForResponse(request)
if err == nil && response != nil {
if response.StatusCode() == http.StatusOK {
callId, _ := request.CallID()
d.subscriber.CallID = string(*callId)
} else {
d.subscriber.CallID = ""
}
return int(response.StatusCode())
}
return http.StatusRequestTimeout
}
func (d *Device) Catalog() int {
//os.Stdout.Write(debug.Stack())
request := d.CreateRequest(sip.MESSAGE)
expires := sip.Expires(3600)
d.subscriber.Timeout = time.Now().Add(time.Second * time.Duration(expires))
contentType := sip.ContentType("Application/MANSCDP+xml")
request.AppendHeader(&contentType)
request.AppendHeader(&expires)
request.SetBody(BuildCatalogXML(d.SN, d.ID), true)
// 输出Sip请求设备通道信息信令
GB28181Plugin.Sugar().Debugf("SIP->Catalog:%s", request)
resp, err := d.SipRequestForResponse(request)
if err == nil && resp != nil {
GB28181Plugin.Sugar().Debugf("SIP<-Catalog Response: %s", resp.String())
return int(resp.StatusCode())
} else if err != nil {
GB28181Plugin.Error("SIP<-Catalog error:", zap.Error(err))
}
return http.StatusRequestTimeout
}
func (d *Device) QueryDeviceInfo() {
for i := time.Duration(5); i < 100; i++ {
time.Sleep(time.Second * i)
request := d.CreateRequest(sip.MESSAGE)
contentType := sip.ContentType("Application/MANSCDP+xml")
request.AppendHeader(&contentType)
request.SetBody(BuildDeviceInfoXML(d.SN, d.ID), true)
response, _ := d.SipRequestForResponse(request)
if response != nil {
// via, _ := response.ViaHop()
// if via != nil && via.Params.Has("received") {
// received, _ := via.Params.Get("received")
// d.SipIP = received.String()
// }
d.Info("QueryDeviceInfo", zap.Uint16("status code", uint16(response.StatusCode())))
if response.StatusCode() == http.StatusOK {
break
}
}
}
}
func (d *Device) SipRequestForResponse(request sip.Request) (sip.Response, error) {
return srv.RequestWithContext(context.Background(), request)
}
// MobilePositionSubscribe 移动位置订阅
func (d *Device) MobilePositionSubscribe(id string, expires time.Duration, interval time.Duration) (code int) {
mobilePosition := d.CreateRequest(sip.SUBSCRIBE)
if d.subscriber.CallID != "" {
callId := sip.CallID(utils.RandNumString(10))
mobilePosition.ReplaceHeaders(callId.Name(), []sip.Header{&callId})
}
expiresHeader := sip.Expires(expires / time.Second)
d.subscriber.Timeout = time.Now().Add(expires)
contentType := sip.ContentType("Application/MANSCDP+xml")
mobilePosition.AppendHeader(&contentType)
mobilePosition.AppendHeader(&expiresHeader)
mobilePosition.SetBody(BuildDevicePositionXML(d.SN, id, int(interval/time.Second)), true)
response, err := d.SipRequestForResponse(mobilePosition)
if err == nil && response != nil {
if response.StatusCode() == http.StatusOK {
callId, _ := mobilePosition.CallID()
d.subscriber.CallID = callId.String()
} else {
d.subscriber.CallID = ""
}
return int(response.StatusCode())
}
return http.StatusRequestTimeout
}
// UpdateChannelPosition 更新通道GPS坐标
func (d *Device) UpdateChannelPosition(channelId string, gpsTime string, lng string, lat string) {
if v, ok := d.channelMap.Load(channelId); ok {
c := v.(*Channel)
c.GpsTime = time.Now() //时间取系统收到的时间,避免设备时间和格式问题
c.Longitude = lng
c.Latitude = lat
c.Debug("update channel position success")
} else {
//如果未找到通道,则更新到设备上
d.GpsTime = time.Now() //时间取系统收到的时间,避免设备时间和格式问题
d.Longitude = lng
d.Latitude = lat
d.Debug("update device position success", zap.String("channelId", channelId))
}
}
// UpdateChannelStatus 目录订阅消息处理:新增/移除/更新通道或者更改通道状态
func (d *Device) UpdateChannelStatus(deviceList []*notifyMessage) {
for _, v := range deviceList {
switch v.Event {
case "ON":
d.Debug("receive channel online notify")
d.channelOnline(v.DeviceID)
case "OFF":
d.Debug("receive channel offline notify")
d.channelOffline(v.DeviceID)
case "VLOST":
d.Debug("receive channel video lost notify")
d.channelOffline(v.DeviceID)
case "DEFECT":
d.Debug("receive channel video defect notify")
d.channelOffline(v.DeviceID)
case "ADD":
d.Debug("receive channel add notify")
channel := ChannelInfo{
DeviceID: v.DeviceID,
ParentID: v.ParentID,
Name: v.Name,
Manufacturer: v.Manufacturer,
Model: v.Model,
Owner: v.Owner,
CivilCode: v.CivilCode,
Address: v.Address,
Port: v.Port,
Parental: v.Parental,
SafetyWay: v.SafetyWay,
RegisterWay: v.RegisterWay,
Secrecy: v.Secrecy,
Status: ChannelStatus(v.Status),
}
d.addOrUpdateChannel(channel)
case "DEL":
//删除
d.Debug("receive channel delete notify")
d.deleteChannel(v.DeviceID)
case "UPDATE":
d.Debug("receive channel update notify")
// 更新通道
channel := ChannelInfo{
DeviceID: v.DeviceID,
ParentID: v.ParentID,
Name: v.Name,
Manufacturer: v.Manufacturer,
Model: v.Model,
Owner: v.Owner,
CivilCode: v.CivilCode,
Address: v.Address,
Port: v.Port,
Parental: v.Parental,
SafetyWay: v.SafetyWay,
RegisterWay: v.RegisterWay,
Secrecy: v.Secrecy,
Status: ChannelStatus(v.Status),
}
d.UpdateChannels(channel)
}
}
}
func (d *Device) channelOnline(DeviceID string) {
if v, ok := d.channelMap.Load(DeviceID); ok {
c := v.(*Channel)
c.Status = ChannelOnStatus
c.Debug("channel online", zap.String("channelId", DeviceID))
} else {
d.Debug("update channel status failed, not found", zap.String("channelId", DeviceID))
}
}
func (d *Device) channelOffline(DeviceID string) {
if v, ok := d.channelMap.Load(DeviceID); ok {
c := v.(*Channel)
c.Status = ChannelOffStatus
c.Debug("channel offline", zap.String("channelId", DeviceID))
} else {
d.Debug("update channel status failed, not found", zap.String("channelId", DeviceID))
}
}