-
Notifications
You must be signed in to change notification settings - Fork 95
/
ptz.go
107 lines (91 loc) · 1.97 KB
/
ptz.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
package gb28181
import (
"encoding/hex"
"encoding/xml"
"fmt"
)
var (
name2code = map[string]uint8{
"stop": 0,
"right": 1,
"left": 2,
"down": 4,
"downright": 5,
"downleft": 6,
"up": 8,
"upright": 9,
"upleft": 10,
"zoomin": 16,
"zoomout": 32,
}
)
type PresetCmd byte
const (
PresetAddPoint = 0
PresetDelPoint = 1
PresetCallPoint = 2
)
const DeviceControl = "DeviceControl"
const PTZFirstByte = 0xA5
const (
PresetSet = 0x81
PresetCall = 0x82
PresetDel = 0x83
)
type MessagePtz struct {
XMLName xml.Name `xml:"Control"`
CmdType string `xml:"CmdType"`
SN int `xml:"SN"`
DeviceID string `xml:"DeviceID"`
PTZCmd string `xml:"PTZCmd"`
}
type Preset struct {
CMD byte
Point byte
}
func toPtzStrByCmdName(cmdName string, horizontalSpeed, verticalSpeed, zoomSpeed uint8) (string, error) {
c, err := toPtzCode(cmdName)
if err != nil {
return "", err
}
return toPtzStr(c, horizontalSpeed, verticalSpeed, zoomSpeed), nil
}
func toPtzStr(cmdCode, horizontalSpeed, verticalSpeed, zoomSpeed uint8) string {
checkCode := uint16(0xA5+0x0F+0x01+cmdCode+horizontalSpeed+verticalSpeed+(zoomSpeed&0xF0)) % 0x100
return fmt.Sprintf("A50F01%02X%02X%02X%01X0%02X",
cmdCode,
horizontalSpeed,
verticalSpeed,
zoomSpeed>>4, // 根据 GB28181 协议,zoom 只取 4 bit
checkCode,
)
}
func toPtzCode(cmd string) (uint8, error) {
if code, ok := name2code[cmd]; ok {
return code, nil
} else {
return 0, fmt.Errorf("invalid ptz cmd %q", cmd)
}
}
func getVerificationCode(ptz []byte) {
sum := uint8(0)
for i := 0; i < len(ptz)-1; i++ {
sum += ptz[i]
}
ptz[len(ptz)-1] = sum
}
func getAssembleCode() uint8 {
return (PTZFirstByte>>4 + PTZFirstByte&0xF + 0) % 16
}
func Pack(cmd, point byte) string {
buf := make([]byte, 8)
buf[0] = PTZFirstByte
buf[1] = getAssembleCode()
buf[2] = 0
buf[3] = cmd
buf[4] = 0
buf[5] = point
buf[6] = 0
getVerificationCode(buf)
return hex.EncodeToString(buf)
}