-
Notifications
You must be signed in to change notification settings - Fork 7
/
main.go
233 lines (199 loc) · 4.79 KB
/
main.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
package main
import (
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/signal"
"strconv"
"sync/atomic"
"github.com/pion/webrtc/v3"
"gobot.io/x/gobot/platforms/dji/tello"
"golang.org/x/net/websocket"
)
type Drone interface {
VideoTrack() webrtc.TrackLocal
FlightData() <-chan FlightData
Forward(int) error
Clockwise(int) error
Right(int) error
Up(int) error
Flip(tello.FlipType) error
Hover()
TakeOff() error
Land() error
}
type FlightData struct {
Height int
BatteryPercentage int
}
func main() {
go panicOnInterrupt()
if err := run(); err != nil {
log.Fatal("error", err)
}
}
func panicOnInterrupt() {
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt)
go func() {
<-c
panic("interrupt")
}()
}
func run() error {
var drone Drone
var err error
if os.Getenv("MOCK") != "" {
drone, err = NewMock("recorded.h264")
} else {
drone, err = NewTello()
}
if err != nil {
return err
}
http.Handle("/", http.FileServer(http.Dir(".")))
http.Handle("/websocket", websocket.Handler(socketHandler(drone)))
addr := os.Getenv("ADDR")
if addr == "" {
addr = "localhost:3000"
}
fmt.Println("serving on http://" + addr)
return http.ListenAndServe(addr, nil)
}
type logger func(...interface{})
func socketHandler(drone Drone) func(*websocket.Conn) {
flightData := &broadcast{}
go flightData.ForwardFlightData(drone.FlightData())
var counter int32
return func(ws *websocket.Conn) {
prefix := strconv.Itoa(int(atomic.AddInt32(&counter, 1)))
fmt.Println()
log := func(i ...interface{}) {
fmt.Println(append([]interface{}{prefix}, i...)...)
}
log("[User-Agent]", ws.Request().UserAgent())
// Create a new RTCPeerConnection
pc, err := webrtc.NewPeerConnection(webrtc.Configuration{
ICEServers: []webrtc.ICEServer{
{
URLs: []string{"stun:stun.l.google.com:19302"},
},
},
})
if err != nil {
panic(err)
}
_, err = pc.AddTrack(trackDebugger{drone.VideoTrack()})
if err != nil {
panic(err)
}
pc.OnDataChannel(func(d *webrtc.DataChannel) {
log("DataChannel", d.Label(), d.ID())
d.OnMessage(func(msg webrtc.DataChannelMessage) {
b := msg.Data
factor := 2
if b[0] == '-' {
factor = -2
}
switch string(b[1:]) {
case "forwa":
drone.Forward(20 * factor)
case "clock":
drone.Clockwise(25 * factor)
case "right":
drone.Right(20 * factor)
case "up":
drone.Up(20 * factor)
case "hover":
drone.Hover()
case "takeoff":
drone.TakeOff()
case "land":
drone.Land()
case "flip":
ft := tello.FlipType(b[0] - '0')
err := drone.Flip(ft)
fmt.Println("ft", ft, err)
default:
log("unknown command", string(b), factor)
}
})
d.OnOpen(func() {
ch := make(chan []byte, 1)
_ = flightData.Listen(ch)
for fd := range ch {
d.Send(fd)
}
})
})
handleICE(log, pc, ws)
}
}
type trackDebugger struct {
webrtc.TrackLocal
}
func (td trackDebugger) Bind(ctx webrtc.TrackLocalContext) (webrtc.RTPCodecParameters, error) {
for _, p := range ctx.CodecParameters() {
fmt.Println(p.PayloadType, p)
}
params, err := td.TrackLocal.Bind(ctx)
fmt.Println("===>", params.PayloadType)
return params, err
}
func handleICE(log logger, pc *webrtc.PeerConnection, ws io.ReadWriter) {
// Set the handler for ICE connection state
// This will notify you when the peer has connected/disconnected
pc.OnICEConnectionStateChange(func(connectionState webrtc.ICEConnectionState) {
log("ICE", connectionState.String())
})
// When Pion gathers a new ICE Candidate send it to the client.
encoder := json.NewEncoder(ws)
pc.OnICECandidate(func(c *webrtc.ICECandidate) {
if c == nil {
return
}
if err := encoder.Encode(c.ToJSON()); err != nil {
log("ERROR", "JSON-Encoder", err)
}
})
decoder := json.NewDecoder(ws)
for {
var socketMsg struct {
webrtc.ICECandidateInit
webrtc.SessionDescription
}
if err := decoder.Decode(&socketMsg); err != nil {
log("ERROR", "JSON-Decoder", err)
return
}
// Attempt to unmarshal as a SessionDescription. If the SDP field is empty
// assume it is not one.
if socketMsg.SDP != "" {
log("SDP")
if err := pc.SetRemoteDescription(socketMsg.SessionDescription); err != nil {
log("ERROR", "SDP", err)
}
answer, err := pc.CreateAnswer(nil)
if err != nil {
log("ERROR", "SDP", err)
}
if err := pc.SetLocalDescription(answer); err != nil {
log("ERROR", "SDP", err)
}
if err := encoder.Encode(answer); err != nil {
log("ERROR", "SDP", err)
}
}
// Attempt to unmarshal as a ICECandidateInit. If the candidate field is empty
// assume it is not one.
if socketMsg.Candidate != "" {
log("ICE candidate")
if err := pc.AddICECandidate(socketMsg.ICECandidateInit); err != nil {
log("ERROR", "Candidate", err)
}
}
}
}