-
Notifications
You must be signed in to change notification settings - Fork 0
/
stamp.go
356 lines (286 loc) · 9.71 KB
/
stamp.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
// Copyright 2017 Inca Roads LLC. All rights reserved.
// Use of this source code is governed by licenses granted by the
// copyright holder including that found in the LICENSE file.
// Support for "stamping" of messages - a method wherein the
// GPS satellite-detected date/time and location are uploaded
// very infrequently and associated with a "stamp ID". By
// including this stamp on each uploaded message (along with
// an offset), we save significant network bandwidth.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"sync"
ttproto "github.com/Safecast/ttproto/golang"
)
// Debugging
const debugStamp = false
// StampVersion1 is the first stamp version we introduced. Unlike the client, the support
// for downlevel stamp version must be kept here forever.
const StampVersion1 = 1
// Cache file format
type stampFile struct {
Version uint32 `json:"Version,omitempty"`
Stamp uint32 `json:"Stamp,omitempty"`
Latitude float64 `json:"Latitude,omitempty"`
Longitude float64 `json:"Longitude,omitempty"`
Altitude int32 `json:"Altitude,omitempty"`
CapturedAtDate uint32 `json:"CapturedAtDate,omitempty"`
CapturedAtTime uint32 `json:"CapturedAtTime,omitempty"`
HasTestMode bool `json:"HasTestMode,omitempty"`
HasMotionOffset bool `json:"HasMotionOffset,omitempty"`
TestMode bool `json:"TestMode,omitempty"`
MotionOffset uint32 `json:"MotionOffset,omitempty"`
}
// Describes every device that has sent us a message
type cachedDevice struct {
deviceid uint32
valid bool
cache stampFile
}
var cacheLock sync.RWMutex
var cachedDevices []cachedDevice
// Construct the path of a command file
func stpFilename(DeviceID uint32) string {
directory := SafecastDirectory()
file := directory + TTDeviceStampPath + "/" + fmt.Sprintf("%d", DeviceID) + ".json"
return file
}
// Set or apply the stamp
func stampSetOrApply(message *ttproto.Telecast) (isValidMessage bool) {
var CacheEntry int
// Device ID is required here, but that doesn't mean it's not a valid message
if message.DeviceId == nil {
return true
}
DeviceID := message.GetDeviceId()
// Protect the cache data structure
cacheLock.Lock()
// Find or create the cache entry for this device
found := false
for CacheEntry = 0; CacheEntry < len(cachedDevices); CacheEntry++ {
if DeviceID == cachedDevices[CacheEntry].deviceid {
found = true
break
}
}
if !found {
var entry cachedDevice
entry.deviceid = DeviceID
entry.valid = false
cachedDevices = append(cachedDevices, entry)
CacheEntry = len(cachedDevices) - 1
if debugStamp {
fmt.Printf("Added new device cache entry for never-before seen %d: %d\n", DeviceID, CacheEntry)
}
}
// If this is a "set stamp" operation, do it
if message.StampVersion != nil {
isValidMessage = stpSet(message, DeviceID, CacheEntry)
cacheLock.Unlock()
return
}
// If this isn't a "stamp this message" operation, exit
if message.Stamp != nil {
isValidMessage = stpApply(message, DeviceID, CacheEntry)
cacheLock.Unlock()
return
}
// Neither a stamper or a stampee
cacheLock.Unlock()
return true
}
// Set or apply the stamp
func stpSet(message *ttproto.Telecast, DeviceID uint32, CacheEntry int) (isValidMessage bool) {
// Regardless of whatever else happens, we need to invalidate the cache
cachedDevices[CacheEntry].valid = false
// Generate the contents for the cache file
sf := &stampFile{}
sf.Version = message.GetStampVersion()
// Pack the new structure based on version #
switch sf.Version {
default:
{
fmt.Printf("*** Unrecognized stamp version: %d ***\n", sf.Version)
}
case StampVersion1:
{
if message.Stamp == nil || message.CapturedAtDate == nil || message.CapturedAtTime == nil {
fmt.Printf("*** Warning - badly formatted v%d stamp ***\n", sf.Version)
} else {
sf.Stamp = message.GetStamp()
sf.CapturedAtDate = message.GetCapturedAtDate()
sf.CapturedAtTime = message.GetCapturedAtTime()
if message.Latitude != nil || message.Longitude != nil {
sf.Latitude = float64(message.GetLatitude())
sf.Longitude = float64(message.GetLongitude())
if message.Altitude != nil {
sf.Altitude = message.GetAltitude()
} else {
sf.Altitude = 0.0
}
}
if message.MotionBeganOffset != nil {
sf.HasMotionOffset = true
sf.MotionOffset = message.GetMotionBeganOffset()
}
if message.Test != nil {
sf.HasTestMode = true
sf.TestMode = message.GetTest()
}
sfJSON, _ := json.Marshal(sf)
file := stpFilename(DeviceID)
fd, err := os.OpenFile(file, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0666)
if err != nil {
fmt.Printf("error creating file %s: %s\n", file, err)
} else {
// Write and close the file
fd.WriteString(string(sfJSON))
fd.Close()
// Write the cache entry
cachedDevices[CacheEntry].cache = *sf
cachedDevices[CacheEntry].valid = true
// Done
if debugStamp {
fmt.Printf("Saved and cached new stamp for %d\n%s\n", DeviceID, string(sfJSON))
}
}
}
}
}
// Remove the stamp fields so they're no longer part of the message
message.Stamp = nil
message.StampVersion = nil
// Done
return true
}
// Appply the stamp
func stpApply(message *ttproto.Telecast, DeviceID uint32, CacheEntry int) (isValidMessage bool) {
// If there's no valid cache entry, or if the cache entry is wrong, refresh the cache
if !cachedDevices[CacheEntry].valid || (cachedDevices[CacheEntry].valid && cachedDevices[CacheEntry].cache.Stamp != message.GetStamp()) {
// Read the file and delete it
file, err := ioutil.ReadFile(stpFilename(DeviceID))
if err != nil {
cachedDevices[CacheEntry].valid = false
} else {
sf := stampFile{}
// Read it as JSON
err = json.Unmarshal(file, &sf)
if err != nil {
cachedDevices[CacheEntry].valid = false
} else {
// Cache it
cachedDevices[CacheEntry].cache = sf
cachedDevices[CacheEntry].valid = true
// Done
if debugStamp {
fmt.Printf("Read stamp for %d from file\n", DeviceID)
}
}
}
}
// If there's still no valid cache entry, we need to discard this reading
if !cachedDevices[CacheEntry].valid {
fmt.Printf("*** No cached stamp for %d when one is needed ***\n", DeviceID)
return false
}
// If there's a valid cache but it is incorrect, do the best we can by using cache as Last Known Good
if cachedDevices[CacheEntry].cache.Stamp != message.GetStamp() {
switch cachedDevices[CacheEntry].cache.Version {
default:
{
fmt.Printf("*** Unrecognized stamp version in cache: %d ***\n", cachedDevices[CacheEntry].cache.Version)
return false
}
case StampVersion1:
{
// Location is best set to last known good rather than nothing at all
if message.Latitude == nil || message.Longitude == nil {
if cachedDevices[CacheEntry].cache.Latitude != 0.0 || cachedDevices[CacheEntry].cache.Longitude != 0.0 {
lat := float32(cachedDevices[CacheEntry].cache.Latitude)
message.Latitude = &lat
lon := float32(cachedDevices[CacheEntry].cache.Longitude)
message.Longitude = &lon
if cachedDevices[CacheEntry].cache.Altitude != 0.0 {
message.Altitude = &cachedDevices[CacheEntry].cache.Altitude
}
}
}
// Modes are best set to last known good rather than making a mistake
if message.Test == nil {
if cachedDevices[CacheEntry].cache.HasTestMode {
message.Test = &cachedDevices[CacheEntry].cache.TestMode
}
}
// Motion is best set to last known good rather than faking it
if message.MotionBeganOffset == nil {
if cachedDevices[CacheEntry].cache.HasMotionOffset {
message.MotionBeganOffset = &cachedDevices[CacheEntry].cache.MotionOffset
}
}
// Time is best set to current time rather than nothing at all
substituteCapturedAt := NowInUTC()
message.CapturedAt = &substituteCapturedAt
message.CapturedAtDate = nil
message.CapturedAtTime = nil
message.CapturedAtOffset = nil
// Remove the stamp field so that it's no longer part of the message
message.Stamp = nil
// Done
if debugStamp {
fmt.Printf("Stamp message required by this message must've been lost, so faking it:\n%v\n", message)
}
return true
}
}
}
// We have a valid cache entry for the correct stamp, so use it
switch cachedDevices[CacheEntry].cache.Version {
default:
{
fmt.Printf("*** Unrecognized stamp version in cache: %d ***\n", cachedDevices[CacheEntry].cache.Version)
return false
}
case StampVersion1:
{
// Set Location
if message.Latitude == nil || message.Longitude == nil {
if cachedDevices[CacheEntry].cache.Latitude != 0.0 || cachedDevices[CacheEntry].cache.Longitude != 0.0 {
lat := float32(cachedDevices[CacheEntry].cache.Latitude)
message.Latitude = &lat
lon := float32(cachedDevices[CacheEntry].cache.Longitude)
message.Longitude = &lon
if cachedDevices[CacheEntry].cache.Altitude != 0.0 {
message.Altitude = &cachedDevices[CacheEntry].cache.Altitude
}
}
}
// Set Modes
if message.Test == nil {
if cachedDevices[CacheEntry].cache.TestMode {
message.Test = &cachedDevices[CacheEntry].cache.TestMode
}
}
// Set Motion
if message.MotionBeganOffset == nil {
if cachedDevices[CacheEntry].cache.HasMotionOffset {
message.MotionBeganOffset = &cachedDevices[CacheEntry].cache.MotionOffset
}
}
// Set Time
if message.CapturedAtOffset != nil {
message.CapturedAtDate = &cachedDevices[CacheEntry].cache.CapturedAtDate
message.CapturedAtTime = &cachedDevices[CacheEntry].cache.CapturedAtTime
}
// Done
if debugStamp {
fmt.Printf("Stamped: %v\n", message)
}
}
}
// Remove the stamp field so that it's no longer part of the message
message.Stamp = nil
return true
}