-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathsailaway.py
175 lines (152 loc) · 6.21 KB
/
sailaway.py
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
'''
sailaway.py
Queries the Sailaway servers, caches responses, and maintains
local sailing logbook.
TODO: compress/decompress log
'''
import requests
import json
import csv
import sys
import glob
import os
from datetime import datetime
from utils import db, units, geo
KEY_PATH = "key.txt"
LOG_PATH = "logs/"
LOG_FILE = LOG_PATH + "logs.csv"
CSV_TEMPLATE = ['boatid','zulu','lat','lon','cog','sog','windspd']
# Sailaway API specifies a minimum of 10 minutes between requests
UPDATE_INTERVAL = 600
TIME_FORMAT = "%Y-%m-%d %H-%M-%S"
REQCACHE_FORMAT = "%Y_%m_%d_%H_%M_%S"
class sailaway:
def __init__(self):
if not os.path.exists(KEY_PATH):
sys.exit("Missing Sailaway API key. Run \"install\" first.")
f = open(KEY_PATH, "r")
self.key = f.readline().rstrip()
if self.key == "":
sys.exit("Missing Sailaway API key. Run \"install\" first.")
self.lastUpdate = None
# clears cache and writes latest update to it
def writeReqCache(self, req):
for file in glob.glob(LOG_PATH + "*.json"):
os.remove(file)
curTime = datetime.utcnow()
reqFile = open(LOG_PATH + curTime.strftime(REQCACHE_FORMAT) + ".json", "w")
reqFile.write(req)
reqFile.close()
self.lastUpdate = curTime
# return (last update in seconds, path to latest cache file)
def lastCacheFile(self):
newestLogTime = 99999
newestLog = ""
curTime = datetime.utcnow()
prevReqList = glob.glob(LOG_PATH + "*.json")
if len(prevReqList) > 0:
for f in prevReqList:
reqTimeStr = f[f.find(LOG_PATH)+len(LOG_PATH):f.find(".json")]
try:
reqTime = datetime.strptime(reqTimeStr, REQCACHE_FORMAT)
except ValueError:
continue
timeDiff = (curTime - reqTime).total_seconds()
if timeDiff < newestLogTime:
newestLogTime = timeDiff
newestLog = f
self.lastUpdate = reqTime
return (newestLogTime, newestLog)
# returns true if query can be run usefully
def canUpdate(self):
if self.lastUpdate != None:
return (datetime.utcnow() - self.lastUpdate).total_seconds() >= UPDATE_INTERVAL
return True
def query(self):
reqText = ""
# first, check cache to see how old the previous request is
lastTime, lastReqFile = self.lastCacheFile()
if lastTime < UPDATE_INTERVAL:
reqFile = open(lastReqFile, "r")
reqText = reqFile.read()
reqFile.close()
# If we didn't have any recent data cached, request it
if reqText == "":
try:
r = requests.get(self.key)
except requests.exceptions.Timeout:
sys.exit("Error: Connection to Sailaway server timed out. Please try again later.")
except requests.exceptions.TooManyRedirects:
sys.exit("Error: Cannot connect to Sailaway server. Please try again later.")
except requests.exceptions.RequestException as e:
sys.exit("Error: Cannot connect to Sailaway server. Check your internet connection.")
reqText = r.text
self.writeReqCache(reqText)
boats = json.loads(reqText)
# sort boats by ID and return them
def sortById(b):
return b['ubtnr']
if len(boats) > 0:
boats.sort(key=sortById)
return boats
def updateInterval():
return UPDATE_INTERVAL
class saillog:
def __init__(self):
if not os.path.exists(LOG_FILE):
# create our logfile if it doesn't exist
os.mkdir(LOG_PATH)
self.wipe()
self.rebuildEntries()
def rebuildEntries(self):
self.entries={}
def addEntry(e):
self.processEntry(e)
db.execute(LOG_FILE, addEntry)
def processEntry(self, e):
e['zulu']=datetime.strptime(e['zulu'], TIME_FORMAT)
if e['boatid'] in self.entries:
boatlog = self.entries[e['boatid']]
else:
boatlog = []
self.entries[e['boatid']] = boatlog
boatlog.append(e)
def logTimeToString(entry):
time = entry['zulu']
return str(time.year) + "-" + str(time.month) + "-" + str(time.day) + " " + units.enforceTwoDigits(str(time.hour)) + ":" + units.enforceTwoDigits(str(time.minute)) + " UTC"
def write(self, zulu, boat):
boatid = str(boat['ubtnr'])
if boatid in self.entries:
prevEntries = self.entries[boatid]
lastEntry = prevEntries[len(prevEntries)-1]
delta = zulu - lastEntry['zulu']
if delta.total_seconds() < sailaway.updateInterval():
return
zuluStr = zulu.strftime(TIME_FORMAT)
entry = [boat['ubtnr'], zuluStr, boat['latitude'], boat['longitude'], geo.wrap_angle(boat['cog']), units.mps_to_kts(boat['sog']), units.mps_to_kts(boat['tws'])]
with open(LOG_FILE,"a") as csvfile:
logwriter = csv.writer(csvfile, delimiter=',')
logwriter.writerow(entry)
self.processEntry({'boatid':entry[0],'zulu':entry[1],'lat':entry[2],'lon':entry[3],'cog':entry[4],'sog':entry[5],'windspd':entry[6]})
def rewrite(self, includeId):
def isValidId(e):
return (e['boatid'] in includeId,)
validBoats = db.query(LOG_FILE, isValidId)
with open(LOG_PATH + "logstmp.csv","w") as csvfile:
logwriter = csv.writer(csvfile, delimiter=',')
logwriter.writerow(CSV_TEMPLATE)
for boat in validBoats:
logwriter.writerow([boat['boatid'],boat['zulu'],boat['lat'],boat['lon'],boat['cog'],boat['sog'],boat['windspd']])
os.remove(LOG_FILE)
os.rename(LOG_PATH+"logstmp.csv", LOG_FILE)
self.rebuildEntries()
def wipe(self):
with open(LOG_FILE,"w") as csvfile:
logwriter = csv.writer(csvfile, delimiter=',')
logwriter.writerow(CSV_TEMPLATE)
self.entries = {}
def getLog(self, boatid):
boatidStr = str(boatid)
if boatidStr in self.entries:
return self.entries[boatidStr]
return None