-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
mavlink_udp_adaptor.go
101 lines (83 loc) · 1.8 KB
/
mavlink_udp_adaptor.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
package mavlink
import (
"net"
common "gobot.io/x/gobot/v2/platforms/mavlink/common"
)
type UDPConnection interface {
Close() error
ReadFromUDP(b []byte) (int, *net.UDPAddr, error)
WriteTo(b []byte, a net.Addr) (int, error)
}
type UDPAdaptor struct {
name string
port string
sock UDPConnection
}
var _ BaseAdaptor = (*UDPAdaptor)(nil)
// NewAdaptor creates a new Mavlink-over-UDP adaptor with specified
// port.
func NewUDPAdaptor(port string) *UDPAdaptor {
return &UDPAdaptor{
name: "Mavlink",
port: port,
}
}
func (m *UDPAdaptor) Name() string { return m.name }
func (m *UDPAdaptor) SetName(n string) { m.name = n }
func (m *UDPAdaptor) Port() string { return m.port }
// Connect returns true if connection to device is successful
func (m *UDPAdaptor) Connect() error {
m.close()
addr, err := net.ResolveUDPAddr("udp", m.Port())
if err != nil {
return err
}
m.sock, err = net.ListenUDP("udp", addr)
if err != nil {
return err
}
return nil
}
func (m *UDPAdaptor) close() error {
sock := m.sock
m.sock = nil
if sock != nil {
return sock.Close()
} else {
return nil
}
}
// Finalize returns true if connection to devices is closed successfully
func (m *UDPAdaptor) Finalize() error {
return m.close()
}
func (m *UDPAdaptor) ReadMAVLinkPacket() (*common.MAVLinkPacket, error) {
buf := make([]byte, 4096)
for {
got, _, err := m.sock.ReadFromUDP(buf)
if err != nil {
return nil, err
}
if got < 2 {
continue
}
sof := buf[0]
length := buf[1]
if sof != common.MAVLINK_10_STX {
continue
}
if length > 250 {
continue
}
m := &common.MAVLinkPacket{}
m.Decode(buf)
return m, nil
}
}
func (m *UDPAdaptor) Write(b []byte) (int, error) {
addr, err := net.ResolveUDPAddr("udp", m.Port())
if err != nil {
return 0, err
}
return m.sock.WriteTo(b, addr)
}