This repository has been archived by the owner on Jan 11, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
pipboy_gps.py
185 lines (153 loc) · 7.45 KB
/
pipboy_gps.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
176
177
178
179
180
181
182
183
184
185
# RasPipBoy: A Pip-Boy 3000 implementation for Raspberry Pi
# Neal D Corbett, 2013
# GPS/position functions
import os, time, math
import urllib.request, urllib.parse, urllib.error, urllib.request, urllib.error, urllib.parse, io, json
import config
if config.USE_GPS:
# Load libraries used by GPS, if present:
def loadGPS():
try:
global gps
import gps
except:
# Deactivate GPS-related systems if load failed:
print("GPS LIBRARY NOT FOUND!")
config.USE_GPS = False
loadGPS()
class GpsModuleClass:
saveVersion = 1
cacheFilename = ("%s/map_coords.txt" %(config.CACHEPATH))
lat, lon = 0, 0
locality = ""
localityLat, localityLon = 0, 0
# Do rendered-commandline print if cmdLine object is available, otherwise do a plain print:
def cmdLinePrint(self, cmdLine, msg):
if (cmdLine == 0):
print(msg)
else:
cmdLine.printText(msg)
# Return Lat/Lon value for a given address:
def addressToLatLong(self,address):
urlParams = {
'address': address,
'sensor': 'false',
}
url = 'http://maps.google.com/maps/api/geocode/json?' + urllib.parse.urlencode( urlParams )
print(url)
response = urllib.request.urlopen( url )
responseBody = response.read().decode("utf-8")
body = io.StringIO( responseBody )
result = json.load( body )
if 'status' not in result or result['status'] != 'OK':
return None, None
else:
return result['results'][0]['geometry']['location']['lat'], result['results'][0]['geometry']['location']['lng']
# Return Locality for a given lat/lon value:
def latLongToLocality(self, lat, lon):
urlParams = {
'latlng': (str(lat) +"," + str(lon)),
'sensor': 'false',
}
url = 'http://maps.google.com/maps/api/geocode/json?' + urllib.parse.urlencode( urlParams )
print("latLongToLocality:")
print(url)
response = urllib.request.urlopen( url )
responseBody = response.read()
body = io.StringIO( responseBody )
result = json.load( body )
if 'status' not in result or result['status'] != 'OK':
return None
else:
addressComps = result['results'][0]['address_components']
notLocality = True
compNum = 0
retVal = ""
while (notLocality and compNum < len(addressComps)):
addressComp = addressComps[compNum]
retVal = addressComp['long_name']
for compType in addressComp['types']:
if (compType == 'locality'):
notLocality = False
compNum += 1
return retVal
def hasCoords(self):
badCoords = (((self.lat == 0) or math.isnan(self.lat)))
return(not badCoords)
def getCoords(self, *args):
cmdLine = 0
if (len(args) != 0):
cmdLine = args[0]
# Do initial GPS-fix:
self.cmdLinePrint(cmdLine, ">GPSD.LOCATE")
self.cmdLinePrint(cmdLine, "Acquiring GPS Fix...")
if config.USE_GPS:
# Play sound until we have a GPS location locked:
if (config.USE_SOUND) and (cmdLine != 0):
#downloadSound = config.SOUNDS["static"]
downloadSound = config.SOUNDS["beacon"]
#config.SOUNDS["static"].play(loops=-1)
downloadSound.play(loops=-1)
# Initialise GPS module:
session = gps.gps(host="localhost", port="2947")
session.stream(gps.WATCH_ENABLE | gps.WATCH_NEWSTYLE)
time.sleep(1)
# Don't use GPS if no devices were found:
if (len(session.devices) == 0):
config.USE_GPS = False
print("GPS MODULE NOT FOUND!")
if config.USE_GPS:
try:
while (self.lat == 0) and (self.lat == 0):
next(session)
self.lat = session.fix.latitude
self.lon = session.fix.longitude
self.cmdLinePrint(cmdLine, "\t(%s,%s)" %(str(self.lat),str(self.lon)))
except StopIteration:
self.cmdLinePrint(cmdLine, "GPSD has terminated")
config.USE_GPS = False
del session
if (config.USE_SOUND) and (cmdLine != 0):
downloadSound.stop()
newCoords = True
if (not self.hasCoords()):
# If GPS-fix wasn't available, load it from cached coords:
if (os.path.exists(self.cacheFilename)):
self.cmdLinePrint(cmdLine, ">GPSD.LOADCACHE %s" %(config.defaultPlace))
self.cmdLinePrint(cmdLine, "Getting cached coords from %s..." %(self.cacheFilename))
with open(self.cacheFilename, 'r') as f:
savedVersion = eval(f.readline())
# Only use coordinates-cache file if its version matches current version:
if (savedVersion == self.saveVersion):
self.lat = eval(f.readline())
self.lon = eval(f.readline())
self.locality = (f.readline()).rstrip()
self.localityLat = eval(f.readline())
self.localityLon = eval(f.readline())
self.cmdLinePrint(cmdLine, "\t(%s,%s)" %(str(self.lat),str(self.lon)))
newCoords = False
else:
self.cmdLinePrint("\tInvalid cache-version, ignoring file")
# If cache wasn't available, generate coords from defaultPlace:
if (newCoords):
self.cmdLinePrint(cmdLine, ">GPSD.DEFAULTLOC %s" %(config.defaultPlace))
self.cmdLinePrint(cmdLine, "Getting coords via geocode for Default Location %s..." %(config.defaultPlace))
self.lat, self.lon = self.addressToLatLong(config.defaultPlace)
self.cmdLinePrint(cmdLine, "\t(%s,%s)" %(str(self.lat),str(self.lon)))
if not self.lat and not self.lon:
return None, None
self.locality = self.latLongToLocality(self.lat, self.lon)
# Get map-centre coordinates for Locality:
self.localityLat, self.localityLon = self.addressToLatLong(self.locality)
# Get locality (i.e. city) for current coordinates via reverse-geocoding, if connection is available:
self.cmdLinePrint(cmdLine, ">GPSD.LOCALITY")
if (self.locality == ""):
self.locality = self.latLongToLocality(self.lat, self.lon)
newCoords = True
self.cmdLinePrint(cmdLine, "\tLocality: \"%s\"" % (self.locality))
# Output new coordinates/locality to cache-file:
if (newCoords):
self.cmdLinePrint(cmdLine, ">GPSD.SAVECACHE %s" %(self.cacheFilename))
with open(self.cacheFilename, 'w') as f:
f.write("%s\n%s\n%s\n%s\n%s\n%s\n" %(self.saveVersion,repr(self.lat),repr(self.lon),self.locality,repr(self.localityLat),repr(self.localityLon)))
return self.lat, self.lon