forked from mmp/vice
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathaviation.go
775 lines (664 loc) · 18.1 KB
/
aviation.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
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
// aviation.go
// Copyright(c) 2022 Matt Pharr, licensed under the GNU Public License, Version 3.
// SPDX: GPL-3.0-only
package main
import (
"bytes"
_ "embed"
"encoding/csv"
"encoding/json"
"fmt"
"io"
"strconv"
"strings"
"sync"
"time"
"github.com/davecgh/go-spew/spew"
)
type FAAAirport struct {
Id string
Name string
Elevation int
Location Point2LL
}
type METAR struct {
AirportICAO string
Time string
Auto bool
Wind string
Weather string
Altimeter string
Rmk string
}
func (m METAR) String() string {
auto := ""
if m.Auto {
auto = "AUTO"
}
return strings.Join([]string{m.AirportICAO, m.Time, auto, m.Wind, m.Weather, m.Altimeter, m.Rmk}, " ")
}
func ParseMETAR(str string) (*METAR, error) {
fields := strings.Fields(str)
if len(fields) < 3 {
return nil, fmt.Errorf("Expected >= 3 fields in METAR text")
}
i := 0
next := func() string {
if i == len(fields) {
return ""
}
s := fields[i]
i++
return s
}
m := &METAR{AirportICAO: next(), Time: next(), Wind: next()}
if m.Wind == "AUTO" {
m.Auto = true
m.Wind = next()
}
for {
s := next()
if s == "" {
break
}
if s[0] == 'A' || s[0] == 'Q' {
m.Altimeter = s
break
}
m.Weather += s + " "
}
m.Weather = strings.TrimRight(m.Weather, " ")
if s := next(); s != "RMK" {
// TODO: improve the METAR parser...
lg.Printf("Expecting RMK where %s is in METAR \"%s\"", s, str)
} else {
for s != "" {
s = next()
m.Rmk += s + " "
}
m.Rmk = strings.TrimRight(m.Rmk, " ")
}
return m, nil
}
type ATIS struct {
Airport string
AppDep string
Code string
Contents string
}
// Frequencies are scaled by 1000 and then stored in integers.
type Frequency int
func NewFrequency(f float32) Frequency {
// 0.5 is key for handling rounding!
return Frequency(f*1000 + 0.5)
}
func (f Frequency) String() string {
s := fmt.Sprintf("%03d.%03d", f/1000, f%1000)
for len(s) < 7 {
s += "0"
}
return s
}
type Controller struct {
Callsign string `json:"-"`
Frequency Frequency `json:"frequency"`
SectorId string `json:"sector_id"` // e.g. N56, 2J, ...
Scope string `json:"scope_char"` // For tracked a/c on the scope--e.g., T
}
type FlightRules int
const (
UNKNOWN = iota
IFR
VFR
DVFR
SVFR
)
func (f FlightRules) String() string {
return [...]string{"Unknown", "IFR", "VFR", "DVFR", "SVFR"}[f]
}
type FlightPlan struct {
Rules FlightRules
AircraftType string
CruiseSpeed int
DepartureAirport string
DepartTimeEst int
DepartTimeActual int
Altitude int
ArrivalAirport string
Hours, Minutes int
FuelHours, FuelMinutes int
AlternateAirport string
Route string
Remarks string
}
type FlightStrip struct {
callsign string
annotations [9]string
}
type Squawk int
func (s Squawk) String() string { return fmt.Sprintf("%04o", s) }
func ParseSquawk(s string) (Squawk, error) {
if s == "" {
return Squawk(0), nil
}
sq, err := strconv.ParseInt(s, 8, 32) // base 8!!!
if err != nil {
return Squawk(0), fmt.Errorf("%s: invalid squawk code", s)
} else if sq < 0 || sq > 0o7777 {
return Squawk(0), fmt.Errorf("%s: out of range squawk code", s)
}
return Squawk(sq), nil
}
type RadarTrack struct {
Position Point2LL
Altitude int
Groundspeed int
Heading float32
Time time.Time
}
type TransponderMode int
const (
Standby = iota
Charlie
Ident
)
func (t TransponderMode) String() string {
return [...]string{"Standby", "C", "Ident"}[t]
}
type Runway struct {
Number string
Heading float32
Threshold, End Point2LL
}
type Navaid struct {
Id string
Type string
Name string
Location Point2LL
}
type Fix struct {
Id string
Location Point2LL
}
type Callsign struct {
Company string
Country string
Telephony string
ThreeLetter string
}
func ParseAltitude(s string) (int, error) {
s = strings.ToUpper(s)
if strings.HasPrefix(s, "FL") {
if alt, err := strconv.Atoi(s[2:]); err != nil {
return 0, err
} else {
return alt * 100, nil
}
} else if alt, err := strconv.Atoi(s); err != nil {
return 0, err
} else {
return alt, nil
}
}
func (fp FlightPlan) BaseType() string {
s := strings.TrimPrefix(fp.TypeWithoutSuffix(), "H/")
s = strings.TrimPrefix(s, "S/")
s = strings.TrimPrefix(s, "J/")
return s
}
func (fp FlightPlan) TypeWithoutSuffix() string {
// try to chop off equipment suffix
actypeFields := strings.Split(fp.AircraftType, "/")
switch len(actypeFields) {
case 3:
// Heavy (presumably), with suffix
return actypeFields[0] + "/" + actypeFields[1]
case 2:
if actypeFields[0] == "H" || actypeFields[0] == "S" || actypeFields[0] == "J" {
// Heavy or super, no suffix
return actypeFields[0] + "/" + actypeFields[1]
} else {
// No heavy, with suffix
return actypeFields[0]
}
default:
// Who knows, so leave it alone
return fp.AircraftType
}
}
///////////////////////////////////////////////////////////////////////////
// Waypoint
type WaypointCommand int
const (
WaypointCommandHandoff = iota
WaypointCommandDelete
)
func (wc WaypointCommand) MarshalJSON() ([]byte, error) {
switch wc {
case WaypointCommandHandoff:
return []byte("\"handoff\""), nil
case WaypointCommandDelete:
return []byte("\"delete\""), nil
default:
return nil, fmt.Errorf("unhandled WaypointCommand in MarshalJSON")
}
}
func (wc *WaypointCommand) UnmarshalJSON(b []byte) error {
switch string(b) {
case "\"handoff\"":
*wc = WaypointCommandHandoff
return nil
case "\"delete\"":
*wc = WaypointCommandDelete
return nil
default:
return fmt.Errorf("%s: unknown waypoint command", string(b))
}
}
type Waypoint struct {
Fix string `json:"fix"`
Location Point2LL `json:"-"` // never serialized, derived from fix
Altitude int `json:"altitude,omitempty"`
Speed int `json:"speed,omitempty"`
Heading int `json:"heading,omitempty"` // outbound heading after waypoint
Commands []WaypointCommand `json:"commands,omitempty"`
}
func (wp *Waypoint) ETA(p Point2LL, gs float32) time.Duration {
dist := nmdistance2ll(p, wp.Location)
eta := dist / gs
return time.Duration(eta * float32(time.Hour))
}
type WaypointArray []Waypoint
func (wslice WaypointArray) MarshalJSON() ([]byte, error) {
var entries []string
for _, w := range wslice {
s := w.Fix
if w.Altitude != 0 {
s += fmt.Sprintf("@a%d", w.Altitude)
}
if w.Speed != 0 {
s += fmt.Sprintf("@s%d", w.Speed)
}
entries = append(entries, s)
if w.Heading != 0 {
entries = append(entries, fmt.Sprintf("#%d", w.Heading))
}
for _, c := range w.Commands {
switch c {
case WaypointCommandHandoff:
entries = append(entries, "@")
case WaypointCommandDelete:
entries = append(entries, "*")
}
}
}
return []byte("\"" + strings.Join(entries, " ") + "\""), nil
}
func (w *WaypointArray) UnmarshalJSON(b []byte) error {
if len(b) < 2 {
*w = nil
return nil
}
wp, err := parseWaypoints(string(b[1 : len(b)-1]))
if err == nil {
*w = wp
}
return err
}
func parseWaypoints(str string) ([]Waypoint, error) {
var waypoints []Waypoint
for _, field := range strings.Fields(str) {
if len(field) == 0 {
return nil, fmt.Errorf("Empty waypoint in string: \"%s\"", str)
}
if field == "@" {
if len(waypoints) == 0 {
return nil, fmt.Errorf("No previous waypoint before handoff specifier")
}
waypoints[len(waypoints)-1].Commands =
append(waypoints[len(waypoints)-1].Commands, WaypointCommandHandoff)
} else if field[0] == '#' {
if len(waypoints) == 0 {
return nil, fmt.Errorf("No previous waypoint before heading specifier")
}
if hdg, err := strconv.Atoi(field[1:]); err != nil {
return nil, fmt.Errorf("%s: invalid waypoint outbound heading: %v", field[1:], err)
} else {
waypoints[len(waypoints)-1].Heading = hdg
}
} else {
wp := Waypoint{}
for i, f := range strings.Split(field, "@") {
if i == 0 {
wp.Fix = f
} else if len(f) == 0 {
return nil, fmt.Errorf("no command found after @ in \"%s\"", field)
} else {
switch f[0] {
case 'a':
alt, err := strconv.Atoi(f[1:])
if err != nil {
return nil, err
}
wp.Altitude = alt
case 's':
kts, err := strconv.Atoi(f[1:])
if err != nil {
return nil, err
}
wp.Speed = kts
default:
return nil, fmt.Errorf("%s: unknown @ command '%c", field, f[0])
}
}
}
waypoints = append(waypoints, wp)
}
}
return waypoints, nil
}
type RadarSite struct {
Char string `json:"char"`
Position string `json:"position"`
Elevation int32 `json:"elevation"`
PrimaryRange int32 `json:"primary_range"`
SecondaryRange int32 `json:"secondary_range"`
SlopeAngle float32 `json:"slope_angle"`
SilenceAngle float32 `json:"silence_angle"`
}
func (rs *RadarSite) CheckVisibility(p Point2LL, altitude int) (primary, secondary bool, distance float32) {
// Check altitude first; this is a quick first cull that
// e.g. takes care of everyone on the ground.
if altitude < int(rs.Elevation) {
return
}
pRadar, ok := scenarioGroup.Locate(rs.Position)
if !ok {
// Really, this method shouldn't be called if the site is invalid,
// but if it is, there's not much else we can do.
return
}
// Time to check the angles; we'll do all of this in nm coordinates,
// since that's how we check the range anyway.
p = ll2nm(p)
palt := float32(altitude) * FeetToNauticalMiles
pRadar = ll2nm(pRadar)
ralt := float32(rs.Elevation) * FeetToNauticalMiles
dxy := sub2f(p, pRadar)
dalt := palt - ralt
distance = sqrt(sqr(dxy[0]) + sqr(dxy[1]) + sqr(dalt))
// If we normalize the vector from the radar site to the aircraft, then
// the z (altitude) component gives the cosine of the angle with the
// "up" direction; in turn, we can check that against the two angles.
cosAngle := dalt / distance
// if angle < silence angle, we can't see it, but the test flips since
// we're testing cosines.
// FIXME: it's annoying to be repeatedly computing these cosines here...
if cosAngle > cos(radians(rs.SilenceAngle)) {
// inside the cone of silence
return
}
// similarly, if angle > 90-slope angle, we can't see it, but again the
// test flips.
if cosAngle < cos(radians(90-rs.SlopeAngle)) {
// below the slope angle
return
}
primary = distance <= float32(rs.PrimaryRange)
secondary = !primary && distance <= float32(rs.SecondaryRange)
return
}
// StaticDatabase is a catch-all for data about the world that doesn't
// change after it's loaded.
type StaticDatabase struct {
Navaids map[string]Navaid
Airports map[string]FAAAirport
Fixes map[string]Fix
Callsigns map[string]Callsign
AircraftTypeAliases map[string]string
AircraftPerformance map[string]AircraftPerformance
Airlines map[string]Airline
}
type AircraftPerformance struct {
Name string `json:"name"`
ICAO string `json:"icao"`
// engines, weight class, category
WeightClass string `json:"weightClass"`
Ceiling int `json:"ceiling"`
Rate struct {
Climb int `json:"climb"` // ft / minute; reduce by 500 after alt 5000 if this is >=2500
Descent int `json:"descent"`
Accelerate float32 `json:"accelerate"` // kts / 2 seconds
Decelerate float32 `json:"decelerate"`
} `json:"rate"`
Runway struct {
Takeoff float32 `json:"takeoff"` // nm
Landing float32 `json:"landing"` // nm
} `json:"runway"`
Speed struct {
Min int `json:"min"`
Landing int `json:"landing"`
Cruise int `json:"cruise"`
Max int `json:"max"`
} `json:"speed"`
}
type Airline struct {
ICAO string `json:"icao"`
Name string `json:"name"`
Callsign struct {
CallsignFormats []string `json:"callsignFormats"`
} `json:"callsign"`
JSONFleets map[string][][2]interface{} `json:"fleets"`
Fleets map[string][]FleetAircraft
}
type FleetAircraft struct {
ICAO string
Count int
}
func InitializeStaticDatabase() *StaticDatabase {
start := time.Now()
db := &StaticDatabase{}
var wg sync.WaitGroup
wg.Add(1)
go func() { db.Navaids = parseNavaids(); wg.Done() }()
wg.Add(1)
go func() { db.Airports = parseAirports(); wg.Done() }()
wg.Add(1)
go func() { db.Fixes = parseFixes(); wg.Done() }()
wg.Add(1)
go func() { db.Callsigns = parseCallsigns(); wg.Done() }()
wg.Add(1)
go func() { db.AircraftPerformance = parseAircraftPerformance(); wg.Done() }()
wg.Add(1)
go func() { db.Airlines = parseAirlines(); wg.Done() }()
wg.Wait()
lg.Printf("Parsed built-in databases in %v", time.Since(start))
return db
}
///////////////////////////////////////////////////////////////////////////
// FAA databases
var (
// https://www.faa.gov/air_traffic/flight_info/aeronav/aero_data/NASR_Subscription_2022-07-14/
//go:embed resources/NAV_BASE.csv.zst
navBaseRaw string
//go:embed resources/APT_BASE.csv.zst
airportsRaw string
//go:embed resources/FIX_BASE.csv.zst
fixesRaw string
//go:embed resources/callsigns.csv.zst
callsignsRaw string
)
// Utility function for parsing CSV files as strings; it breaks each line
// of the file into fields and calls the provided callback function for
// each one.
func mungeCSV(filename string, raw string, callback func([]string)) {
r := bytes.NewReader([]byte(raw))
cr := csv.NewReader(r)
cr.ReuseRecord = true
// Skip the first line with the legend
if _, err := cr.Read(); err != nil {
lg.Errorf("%s: error parsing CSV file: %s", filename, err)
return
}
for {
if record, err := cr.Read(); err == io.EOF {
return
} else if err != nil {
lg.Errorf("%s: error parsing CSV file: %s", filename, err)
return
} else {
callback(record)
}
}
}
func parseNavaids() map[string]Navaid {
navaids := make(map[string]Navaid)
mungeCSV("navaids", decompressZstd(navBaseRaw), func(s []string) {
n := Navaid{
Id: s[1],
Type: s[2],
Name: s[7],
Location: Point2LL{float32(atof(s[31])), float32(atof(s[26]))},
}
if n.Id != "" {
navaids[n.Id] = n
}
})
return navaids
}
func point2LLFromComponents(lat []string, long []string) Point2LL {
latitude := atof(lat[0]) + atof(lat[1])/60. + atof(lat[2])/3600.
if lat[3] == "S" {
latitude = -latitude
}
longitude := atof(long[0]) + atof(long[1])/60. + atof(long[2])/3600.
if long[3] == "W" {
longitude = -longitude
}
return Point2LL{float32(longitude), float32(latitude)}
}
func parseAirports() map[string]FAAAirport {
airports := make(map[string]FAAAirport)
// FAA database
mungeCSV("airports", decompressZstd(airportsRaw), func(s []string) {
if elevation, err := strconv.ParseFloat(s[24], 64); err != nil {
lg.Errorf("%s: error parsing elevation: %s", s[24], err)
} else {
loc := point2LLFromComponents(s[15:19], s[19:23])
ap := FAAAirport{Id: s[98], Name: s[12], Location: loc, Elevation: int(elevation)}
if ap.Id == "" {
ap.Id = s[4] // No ICAO code so grab the FAA airport id
}
if ap.Id != "" {
airports[ap.Id] = ap
}
}
})
return airports
}
func parseFixes() map[string]Fix {
fixes := make(map[string]Fix)
mungeCSV("fixes", decompressZstd(fixesRaw), func(s []string) {
f := Fix{
Id: s[1],
Location: Point2LL{float32(atof(s[14])), float32(atof(s[9]))},
}
if f.Id != "" {
fixes[f.Id] = f
}
})
return fixes
}
func parseCallsigns() map[string]Callsign {
callsigns := make(map[string]Callsign)
addCallsign := func(s []string) {
fix := func(s string) string { return stopShouting(strings.TrimSpace(s)) }
cs := Callsign{
Company: fix(s[0]),
Country: fix(s[1]),
Telephony: fix(s[2]),
ThreeLetter: strings.TrimSpace(s[3])}
if cs.ThreeLetter != "" && cs.ThreeLetter != "..." {
callsigns[cs.ThreeLetter] = cs
}
}
mungeCSV("callsigns", decompressZstd(callsignsRaw), addCallsign)
return callsigns
}
//go:embed resources/openscope-aircraft.json
var openscopeAircraft string
func parseAircraftPerformance() map[string]AircraftPerformance {
var acStruct struct {
Aircraft []AircraftPerformance `json:"aircraft"`
}
if err := json.Unmarshal([]byte(openscopeAircraft), &acStruct); err != nil {
lg.Errorf("%v", err)
}
ap := make(map[string]AircraftPerformance)
for i, ac := range acStruct.Aircraft {
ap[ac.ICAO] = acStruct.Aircraft[i]
}
return ap
}
//go:embed resources/openscope-airlines.json
var openscopeAirlines string
func parseAirlines() map[string]Airline {
var alStruct struct {
Airlines []Airline `json:"airlines"`
}
if err := json.Unmarshal([]byte(openscopeAirlines), &alStruct); err != nil {
lg.Errorf("%v", err)
}
airlines := make(map[string]Airline)
for _, al := range alStruct.Airlines {
fixedAirline := al
fixedAirline.Fleets = make(map[string][]FleetAircraft)
for name, aircraft := range fixedAirline.JSONFleets {
for _, ac := range aircraft {
fleetAC := FleetAircraft{
ICAO: strings.ToUpper(ac[0].(string)),
Count: int(ac[1].(float64)),
}
fixedAirline.Fleets[name] = append(fixedAirline.Fleets[name], fleetAC)
}
}
fixedAirline.JSONFleets = nil
airlines[strings.ToUpper(al.ICAO)] = fixedAirline
}
return airlines
}
///////////////////////////////////////////////////////////////////////////
// Utility methods
func (db *StaticDatabase) CheckAirline(icao, fleet string, e *ErrorLogger) {
e.Push("Airline " + icao + ", fleet " + fleet)
defer e.Pop()
al, ok := database.Airlines[icao]
if !ok {
e.ErrorString("airline not known")
return
}
if fleet == "" {
fleet = "default"
}
fl, ok := al.Fleets[fleet]
if !ok {
e.ErrorString("fleet unknown")
return
}
for _, aircraft := range fl {
e.Push("Aircraft " + aircraft.ICAO)
if perf, ok := database.AircraftPerformance[aircraft.ICAO]; !ok {
e.ErrorString("aircraft not present in performance database")
} else {
if perf.Speed.Min < 35 || perf.Speed.Landing < 35 || perf.Speed.Cruise < 35 ||
perf.Speed.Max < 35 || perf.Speed.Min > perf.Speed.Max {
e.ErrorString("aircraft's speed specification is questionable: %s", spew.Sdump(perf.Speed))
}
if perf.Rate.Climb == 0 || perf.Rate.Descent == 0 || perf.Rate.Accelerate == 0 ||
perf.Rate.Decelerate == 0 {
e.ErrorString("aircraft's rate specification is questionable: %s", spew.Sdump(perf.Rate))
}
}
e.Pop()
}
}