forked from NubeDev/bacnet
-
Notifications
You must be signed in to change notification settings - Fork 0
/
address.go
72 lines (63 loc) · 1.61 KB
/
address.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
package btypes
import (
"fmt"
"net"
)
type Address struct {
Net uint16 // BACnet network number
Len uint8
MacLen uint8 // mac len 0 is a broadcast address
Mac []uint8 //note: MAC for IP addresses uses 4 bytes for addr, 2 bytes for port
Adr []uint8 // hardware addr (MAC) address of ms-tp devices
}
const GlobalBroadcast uint16 = 0xFFFF
const broadcastNetwork uint16 = 0xFFFF
// IsBroadcast returns if the address is a broadcast address
func (a *Address) IsBroadcast() bool {
if a.Net == broadcastNetwork || a.MacLen == 0 {
return true
}
return false
}
//SetLength if device is of type ms-tp then set address len to 1
func (a *Address) SetLength() {
if len(a.Adr) > 0 {
// 兼容bacnet device simulator的adr地址长度不为1的情况
a.Len = uint8(len(a.Adr))
}
return
}
func (a *Address) SetBroadcast(b bool) {
if b {
a.MacLen = 0
} else {
a.MacLen = uint8(len(a.Mac))
}
}
// IsSubBroadcast checks to see if packet is meant to be a network
// specific broadcast
func (a *Address) IsSubBroadcast() bool {
if a.Net > 0 && a.Len == 0 {
return true
}
return false
}
// IsUnicast checks to see if packet is meant to be a unicast
func (a *Address) IsUnicast() bool {
if a.MacLen == 6 {
return true
}
return false
}
// UDPAddr parses the mac address and returns a proper net.UDPAddr
func (a *Address) UDPAddr() (net.UDPAddr, error) {
if len(a.Mac) != 6 {
return net.UDPAddr{}, fmt.Errorf("mac is too short at %d", len(a.Mac))
}
port := uint(a.Mac[4])<<8 | uint(a.Mac[5])
ip := net.IPv4(a.Mac[0], a.Mac[1], a.Mac[2], a.Mac[3])
return net.UDPAddr{
IP: ip,
Port: int(port),
}, nil
}