~sungo/sbs-http

sbs-http/main.go -rw-r--r-- 8.1 KiB
763ad0f8 — sungo restructure a bit 1 year, 9 months ago
                                                                                
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
// Copyright Matt Cashner (sungo). Licensed under BSD-3-Clause. See the
// included LICENSE file

package main

import (
	"bufio"
	"encoding/json"
	"flag"
	"fmt"
	"net"
	"net/http"
	"os"
	"strings"
	"sync"
	"sync/atomic"
	"time"

	"git.sr.ht/~sungo/go-sbs"
	"git.sr.ht/~sungo/sbs-http/pkg/models"

	"github.com/davecgh/go-spew/spew"
	"github.com/gorilla/handlers"
	"github.com/gorilla/mux"
	"github.com/paulmach/orb"
	"github.com/paulmach/orb/geo"
)

const Version = "0.0.1"

func ddp(v interface{}) {
	spew.Fdump(os.Stderr, v)
}

func init() {
	spew.Config = spew.ConfigState{
		Indent:   "    ",
		SortKeys: true,
	}
}

type cmdFlags struct {
	URL              string
	ClientRefresh    int
	ReceiverLat      float64
	ReceiverLon      float64
	AircraftTimeout  int
	ExpiryCheckTime  int
	UnhateCORS       bool
	ListenOn         string
	SbsReconnectTime int
}

/////////////

/////////////
var (
	TotalMessages   uint64
	QueueMutex      = &sync.Mutex{}
	CurrentAircraft = make(map[string]*models.Aircraft)
)

var Flags = &cmdFlags{}

func main() {
	flag.StringVar(&Flags.URL, "sbs-url", "localhost:30003", "URL for the SBS-1 CSV server")
	flag.IntVar(&Flags.ClientRefresh, "client-refresh", 200, "Time in milliseconds for the user to attempt data refresh")
	flag.Float64Var(&Flags.ReceiverLat, "lat", 0, "Latitude of the receiver")
	flag.Float64Var(&Flags.ReceiverLon, "lon", 0, "Latitude of the receiver")
	flag.IntVar(&Flags.AircraftTimeout, "aircraft-timeout", 60, "If an aircraft is not heard from in this many seconds, expire it")
	flag.IntVar(&Flags.ExpiryCheckTime, "expiry-check", 1, "How often, in seconds, to check for expired aircraft")
	flag.BoolVar(&Flags.UnhateCORS, "disable-insecure-cors", false, "By default, the http server allows all origins via CORS. If you dislike this behavior, use this flag")
	flag.StringVar(&Flags.ListenOn, "listen", ":8000", "Listen ip:port for the HTTP server")
	flag.IntVar(&Flags.SbsReconnectTime, "sbs-reconnect", 1, "Time to pause between attempts to connect to the SBS server")

	flag.Parse()

	go talkToDump1090(Flags.URL)
	go dataExpiry()

	/////////////
	// Make dump1090 data available via HTTP
	/////////////
	r := mux.NewRouter()

	r.HandleFunc("/data/receiver.json", handlerReceiver).Methods("GET")
	r.HandleFunc("/data/aircraft.json", handlerAircraft).Methods("GET")
	r.HandleFunc("/data/stats.json", handlerStats).Methods("GET")

	origins := handlers.AllowedOrigins([]string{"*"})
	methods := handlers.AllowedMethods([]string{"GET"})

	var loggedRouter http.Handler
	if Flags.UnhateCORS {
		loggedRouter = handlers.LoggingHandler(os.Stdout, r)
	} else {
		cors := handlers.CORS(origins, methods)(r)
		loggedRouter = handlers.LoggingHandler(os.Stdout, cors)
	}

	ddp(http.ListenAndServe(Flags.ListenOn, loggedRouter))
}

/////////////
// Stream data from dump1090
/////////////
func talkToDump1090(url string) {
	for {
		fmt.Printf("Connecting to %s ...\n", url)

		conn, err := net.Dial("tcp", url)
		if err != nil {
			fmt.Printf(
				"Failed to connect to %s: %s\nWill attempt reconnection in %d seconds\n",
				url,
				err,
				Flags.SbsReconnectTime,
			)
			time.Sleep(time.Duration(Flags.SbsReconnectTime) * time.Second)
			continue
		}

		fmt.Println("Connected.")

		buf := bufio.NewReader(conn)
		for {
			str, err := buf.ReadString('\n')
			if err != nil {
				ddp(err)
				break
			}

			str = strings.TrimSpace(str)

			if len(str) == 0 {
				continue
			}

			msg, err := sbs.Parse(str)
			if err != nil {
				fmt.Printf(
					"PARSE FAILURE: %s // --%s--\n",
					err,
					str,
				)
				continue
			}

			atomic.AddUint64(&TotalMessages, 1)

			if msg.MessageType != sbs.Transmission {
				continue
			}

			if msg.HexIdent == "" {
				continue
			}

			now := time.Now()

			QueueMutex.Lock()
			a, ok := CurrentAircraft[msg.HexIdent]

			if !ok {
				a = &models.Aircraft{Hex: msg.HexIdent}
				CurrentAircraft[a.Hex] = a
			}

			a.Seen = now.Sub(a.LastSeen).Seconds()
			a.LastSeen = now

			if msg.HexIdent != "" {
				a.Hex = strings.TrimSpace(msg.HexIdent)
			}
			if msg.Squawk != "" {
				a.Squawk = strings.TrimSpace(msg.Squawk)
			}
			if msg.CallSign != "" {
				a.Flight = strings.TrimSpace(msg.CallSign)
			}

			if msg.TransmissionType == sbs.ESSurfacePosition {
				// Alt, GS, Trk, Lat, Long, Gnd
				if msg.IsOnGround.IsSet && msg.IsOnGround.Value {
					a.Altitude = "ground"
				} else {
					a.Altitude = fmt.Sprintf("%d", msg.Altitude)
				}

				a.Track = msg.Track
				a.Speed = msg.GroundSpeed

				a.Lat = msg.Latitude
				a.Lon = msg.Longitude
				a.SeenPos = now.Sub(a.LastPosSeen).Seconds()
				a.LastPosSeen = now

			} else if msg.TransmissionType == sbs.ESAirbornePosition {
				// Alt, Lat, Long, Alert, Emerg, SPI, Ground
				if msg.IsOnGround.IsSet && msg.IsOnGround.Value {
					a.Altitude = "ground"
				} else {
					a.Altitude = fmt.Sprintf("%d", msg.Altitude)
				}

				a.Lat = msg.Latitude
				a.Lon = msg.Longitude
				a.SeenPos = now.Sub(a.LastPosSeen).Seconds()
				a.LastPosSeen = now

			} else if msg.TransmissionType == sbs.ESAirborneVelocity {
				// GS, Trk, VR
				a.VertRate = msg.VerticalRate
				a.Track = msg.Track
				a.Speed = msg.GroundSpeed

			} else if msg.TransmissionType == sbs.SurveillanceAlt {
				// Alt, Alrt, SPI, Ground
				if msg.IsOnGround.IsSet && msg.IsOnGround.Value {
					a.Altitude = "ground"
				} else {
					a.Altitude = fmt.Sprintf("%d", msg.Altitude)
				}

			} else if msg.TransmissionType == sbs.SurveillanceID {
				// Alt, Sq, Alrt, Emerg, SPI, Ground

				if msg.IsOnGround.IsSet && msg.IsOnGround.Value {
					a.Altitude = "ground"
				} else {
					a.Altitude = fmt.Sprintf("%d", msg.Altitude)
				}

			} else if msg.TransmissionType == sbs.AirToAir {
				// Alt, Ground
				if msg.IsOnGround.IsSet && msg.IsOnGround.Value {
					a.Altitude = "ground"
				} else {
					a.Altitude = fmt.Sprintf("%d", msg.Altitude)
				}

			} else if msg.TransmissionType == sbs.AllCallReply {
				// Ground
				if msg.IsOnGround.IsSet && msg.IsOnGround.Value {
					a.Altitude = "ground"
				}

			}

			a.Messages = a.Messages + 1

			if Flags.ReceiverLat != 0 && Flags.ReceiverLon != 0 {
				if a.Lat != 0 && a.Lon != 0 {
					us := orb.Point{Flags.ReceiverLon, Flags.ReceiverLat}
					them := orb.Point{a.Lon, a.Lat}

					a.Distance = geo.Distance(us, them)
					a.Bearing = geo.Bearing(us, them)

				}
			}

			QueueMutex.Unlock()
		}

		fmt.Printf(
			"Disconnected from %s\nWill attempt reconnection in %d seconds\n",
			url,
			Flags.SbsReconnectTime,
		)
		time.Sleep(time.Duration(Flags.SbsReconnectTime) * time.Second)
	}
}

/////////////
// Expire old aircraft
/////////////
func dataExpiry() {
	ticker := time.NewTicker(time.Duration(Flags.ExpiryCheckTime) * time.Second)
	for range ticker.C {
		QueueMutex.Lock()
		expired := 0
		now := time.Now()

		for k, a := range CurrentAircraft {
			dur := now.Sub(a.LastSeen)
			a.Seen = dur.Seconds()
			if dur >= time.Duration(Flags.AircraftTimeout)*time.Second {
				expired = expired + 1
				delete(CurrentAircraft, k)
			}
		}
		//fmt.Printf("[%s] Expired %d aircraft\n", time.Now().Local().Format("2006-01-02 15:04:05 -0700"), expired)
		fmt.Printf(
			"[%s] %d visible aircraft\n",
			time.Now().Local().Format("2006-01-02 15:04:05 -0700"),
			len(CurrentAircraft),
		)
		// ddp(CurrentAircraft)
		QueueMutex.Unlock()
	}
}

//////////////
// Web stuff
//////////////

func handlerReceiver(w http.ResponseWriter, r *http.Request) {
	receiver := &models.OutputReceiver{
		Version:   Version,
		Refresh:   Flags.ClientRefresh,
		History:   0,
		Latitude:  Flags.ReceiverLat,
		Longitude: Flags.ReceiverLon,
	}

	json.NewEncoder(w).Encode(receiver)

}

func handlerAircraft(w http.ResponseWriter, r *http.Request) {
	var o models.OutputAircraft

	QueueMutex.Lock()

	now := time.Now()
	o.Now = now.Unix()
	o.Messages = atomic.LoadUint64(&TotalMessages)

	aircraft := make([]*models.Aircraft, 0)

	for _, v := range CurrentAircraft {
		if v.Lat != 0 && v.Lon != 0 {
			v.Seen = now.Sub(v.LastSeen).Seconds()
			v.SeenPos = now.Sub(v.LastPosSeen).Seconds()
			v.AltGeom = v.Altitude
			v.GS = v.Speed
			v.VertRateGeom = v.VertRate
			aircraft = append(aircraft, v)
		}
	}
	o.Aircraft = aircraft

	json.NewEncoder(w).Encode(o)
	QueueMutex.Unlock()
}

func handlerStats(w http.ResponseWriter, r *http.Request) {

}