/
archive.go
191 lines (176 loc) · 5.9 KB
/
archive.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
package main
import (
"errors"
"math"
"sync"
"time"
ais "github.com/andmarios/aislib"
"github.com/tormol/AIS/geo"
"github.com/tormol/AIS/nmeais"
"github.com/tormol/AIS/storage"
)
//The Archive stores the information about the ships (and works as a temp. solution for the RTree concurrency)
type Archive struct {
rt *storage.RTree //Stores the points
rw *sync.RWMutex //works as a lock for the RTree (#TODO: RTree should be improved to handle concurrency on its own)
db *storage.ShipDB //Contains tracklog and other info for each ship
}
// NewArchive returns a pointer to a new Archive
func NewArchive(historyMax uint, goneThreshold, leftAreaThreshold time.Duration) *Archive {
return &Archive{
rt: storage.NewRTree(),
rw: &sync.RWMutex{},
db: storage.NewShipDB(historyMax, goneThreshold, leftAreaThreshold),
}
}
func decodeHeading(heading uint16) float32 {
if heading != 511 {
return float32(heading)
}
return float32(math.NaN())
}
func decodeCourseOverGround(cog float32) float32 {
if cog < 360 { // I assume 360 means unknown
return cog
}
return float32(math.NaN())
}
func decodeRateOfTurn(rot float32) float32 {
if rot >= -127 && rot <= 127 {
// doesn't handle the edge cases of ±127 meaning " or more"
return (rot / 4.733) * float32(math.Abs(float64(rot)/4.733))
}
return float32(math.NaN())
}
// Save stores the information in the relevant Ais message
// types recieved form the channel
func (a *Archive) Save(msg chan *nmeais.Message) {
for m := range msg {
var err error
ps := (*ais.PositionReport)(nil)
switch m.Type() {
case 1, 2, 3: // class A position report (longest)
cApr, e := ais.DecodeClassAPositionReport(m.ArmoredPayload())
ps = &cApr.PositionReport
if e != nil {
continue
}
err = a.updatePos(ps)
pos := storage.ShipPos{
time.Now(),
geo.Point{ps.Lat, ps.Lon},
storage.Accuracy(ps.Accuracy),
storage.ShipNavStatus(cApr.Status),
decodeHeading(ps.Heading),
decodeCourseOverGround(ps.Course),
ps.Speed,
decodeRateOfTurn(cApr.Turn)}
a.db.UpdateDynamic(ps.MMSI, pos)
case 5: // static voyage data
svd, e := ais.DecodeStaticVoyageData(m.ArmoredPayload())
if e != nil && svd.MMSI <= 0 {
continue
}
length := uint16(svd.ToBow + svd.ToStern)
lOffset := int16(length/2 - svd.ToBow)
width := uint16(svd.ToPort + svd.ToStarboard)
wOffset := int16(width/2 - uint16(svd.ToStarboard))
a.db.UpdateStatic(svd.MMSI, storage.ShipInfo{storage.ShipType(svd.ShipType), svd.Draught, length, width, lOffset, wOffset, svd.Callsign, svd.VesselName, svd.Destination, svd.ETA})
case 18: // basic class B position report (shorter)
cBpr, e := ais.DecodeClassBPositionReport(m.ArmoredPayload())
ps = &cBpr.PositionReport
if e != nil {
continue
}
err = a.updatePos(ps)
pos := storage.ShipPos{
time.Now(),
geo.Point{ps.Lat, ps.Lon},
storage.Accuracy(ps.Accuracy),
storage.ShipNavStatus(15),
decodeHeading(ps.Heading),
decodeCourseOverGround(ps.Course),
ps.Speed,
float32(math.NaN()) /*rate of turn*/}
a.db.UpdateDynamic(ps.MMSI, pos)
case 24: // static data report
sdr, e := ais.DecodeStaticDataReport(m.ArmoredPayload())
if e != nil && sdr.MMSI <= 0 {
continue
}
length := uint16(sdr.ToBow + sdr.ToStern)
lOffset := int16(length/2 - sdr.ToBow)
width := uint16(sdr.ToPort + sdr.ToStarboard)
wOffset := int16(width/2 - uint16(sdr.ToStarboard))
a.db.UpdateStatic(sdr.MMSI, storage.ShipInfo{storage.ShipType(sdr.ShipType), 0, length, width, lOffset, wOffset, sdr.CallSign, sdr.VesselName, "", time.Date(0001, 1, 1, 0, 0, 0, 0, time.UTC)})
}
if err != nil {
continue //TODO do something...
}
}
}
// NumberOfShips returns the number of known ships
func (a *Archive) NumberOfShips() int {
a.rw.RLock()
defer a.rw.RUnlock()
return a.rt.NumOfBoats()
}
//Updates the ships position in the structures (message type 1,2,3,18)
func (a *Archive) updatePos(ps *ais.PositionReport) error {
mmsi := ps.MMSI
if !okCoords(ps.Lat, ps.Lon) || mmsi <= 0 { //This happends quite frequently (coordinates are set to 91,181)
return errors.New("Cannot update position")
}
//Check if it is a known ship
if a.db.Known(mmsi) {
oldLat, oldLong := a.db.Coords(mmsi) //get the previous coordinates
if oldLat == 0 && oldLong == 0 {
return errors.New("The ship has no known coordinates")
}
a.rw.Lock()
err := a.rt.Update(mmsi, oldLat, oldLong, ps.Lat, ps.Lon) //update the position in the R*Tree
a.rw.Unlock()
if err != nil {
return errors.New("The archive failed to update the position of the ship")
}
} else {
a.rw.Lock()
a.rt.InsertData(ps.Lat, ps.Lon, mmsi) //insert a new ship into the R*Tree
a.rw.Unlock()
}
return nil
}
// FindAll returns a GeoJSON FeatureCollection containing all the known ships
func (a *Archive) FindAll() string {
geoJSONFC, _ := a.FindWithin(-89.999999, -179.999999, 89.999999, 179.999999)
return geoJSONFC
}
// FindWithin uses the index to find all ships within a bounding box.
// The bounding box can cross the date line or be offset 360°.
// The ships are returned as a GeoJSON FeatureCollection. output:
func (a *Archive) FindWithin(minLat, minLong, maxLat, maxLong float64) (string, error) {
rects := geo.SplitViewRect(minLat, minLong, maxLat, maxLong)
if rects == nil {
return "{}", errors.New("ERROR, invalid rectangle coordinates")
}
matches := []storage.Match{}
a.rw.RLock()
for _, r := range rects {
m := a.rt.FindWithin(&r)
matches = append(matches, *m...)
}
a.rw.RUnlock()
// TODO return rectangles?
return storage.Matches(&matches, a.db, Log), nil
}
// Check if the coordinates are ok. (<91, 181> seems to be a fallback value for the coordinates)
func okCoords(lat, long float64) bool {
if lat <= 90 && long <= 180 && lat >= -90 && long >= -180 {
return true
}
return false
}
// Select returns the information about the ship and its tracklog as GeoJSON
func (a *Archive) Select(mmsi uint32) string {
return a.db.Select(mmsi, Log)
}