-
-
Notifications
You must be signed in to change notification settings - Fork 1k
/
mavlink_driver.go
96 lines (82 loc) · 2.11 KB
/
mavlink_driver.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
package mavlink
import (
"time"
"gobot.io/x/gobot/v2"
common "gobot.io/x/gobot/v2/platforms/mavlink/common"
)
const (
// PacketEvent event
PacketEvent = "packet"
// MessageEvent event
MessageEvent = "message"
// ErrorIOEEvent event
ErrorIOEvent = "errorIO"
// ErrorMAVLinkEvent event
ErrorMAVLinkEvent = "errorMAVLink"
)
type Driver struct {
name string
connection gobot.Connection
interval time.Duration
gobot.Eventer
}
type MavlinkInterface interface{}
// NewDriver creates a new mavlink driver.
//
// It add the following events:
//
// "packet" - triggered when a new packet is read
// "message" - triggered when a new valid message is processed
func NewDriver(a BaseAdaptor, v ...time.Duration) *Driver {
m := &Driver{
name: "Mavlink",
connection: a,
Eventer: gobot.NewEventer(),
interval: 10 * time.Millisecond,
}
if len(v) > 0 {
m.interval = v[0]
}
m.AddEvent(PacketEvent)
m.AddEvent(MessageEvent)
m.AddEvent(ErrorIOEvent)
m.AddEvent(ErrorMAVLinkEvent)
return m
}
func (m *Driver) Connection() gobot.Connection { return m.connection }
func (m *Driver) Name() string { return m.name }
func (m *Driver) SetName(n string) { m.name = n }
// adaptor returns driver associated adaptor
func (m *Driver) adaptor() BaseAdaptor {
//nolint:forcetypeassert // ok here
return m.Connection().(BaseAdaptor)
}
// Start begins process to read mavlink packets every m.Interval
// and process them
func (m *Driver) Start() error {
go func() {
for {
packet, err := m.adaptor().ReadMAVLinkPacket()
if err != nil {
m.Publish(ErrorIOEvent, err)
continue
}
m.Publish(PacketEvent, packet)
message, err := packet.MAVLinkMessage()
if err != nil {
m.Publish(ErrorMAVLinkEvent, err)
continue
}
m.Publish(MessageEvent, message)
time.Sleep(m.interval)
}
}()
return nil
}
// Halt returns true if device is halted successfully
func (m *Driver) Halt() error { return nil }
// SendPacket sends a packet to mavlink device
func (m *Driver) SendPacket(packet *common.MAVLinkPacket) error {
_, err := m.adaptor().Write(packet.Pack())
return err
}