Location location location. Geolocation, in point of fact. I’ve written a quick snippet of code to query http://ipinfo.io for my current latitude and longitude, for the purposes of calculating the times of sunrise and sunset (my Sleepy Pi has now arrived), and it gives some “interesting” results. Whilst running from home is almost creepily accurate, running from work gives me the address of the Canberra office (!), and at the other end of the spectrum running it while tethered via a mobile deposits me here :

https://www.google.com.au/maps/@-27,133,104020m/data=!3m1!1e3
#!/usr/bin/python3
# Attempt to determine your position (including latitude and longitude) using your current IP address.
# Unless specified your latitude and longitude will be written to ~/.sunrise/location.ini
# Requires a recent version of Python (preferably 3+).
import urllib.request
import json
from html.parser import HTMLParser, HTMLParseError
import configparser
import os
import argparse
import sys
class CLocationConfig:
def __init__(self):
self.config = configparser.ConfigParser ()
def write(self, section, latitude, longitude):
home_directory = os.path.expanduser("~")
write_directory = home_directory+'/.sunrise'
if not os.path.exists (write_directory):
os.mkdir (write_directory)
ini_filename = write_directory+'/location.ini'
try:
self.config.read (ini_filename)
except:
print ("Error")
self.config [section] = {}
self.config [section]['Latitude'] = latitude
self.config [section]['Longitude'] = longitude
with open(ini_filename, 'w') as configfile:
self.config.write(configfile)
class CLocationWeb (HTMLParser) :
def __init__(self):
HTMLParser.__init__(self)
self.JSONData = ""
def handle_data(self, data):
self.JSONData = data
def read(self):
try:
response = urllib.request.urlopen('http://ipinfo.io/json')
except urllib.error.URLError:
print("URL error connecting to http://ipinfo.io : ",urllib.error.URLError.reason)
except urllib.error.HTTPError:
print("HTTP error connecting to http://ipinfo.io (code ",urllib.error.HTTPError.code,")")
except urllib.error.ContentTooShortError:
print("Error : Response was too short")
try:
self.feed(response.read().decode("utf-8"))
except HTMLParseError:
print("Error parsing output \"",HTMLParseError.msg,"\"")
except:
print ("Unknown error occurred whilst parsing.")
if self.JSONData != "":
location = json.loads(self.JSONData)
else:
print("JSON data not set.")
exit()
my_latitude, my_longitude = (location['loc'].split(','))
return my_latitude, my_longitude
def main ():
LocationWeb = CLocationWeb ()
LocationConfig = CLocationConfig ()
parser = argparse.ArgumentParser (prog='geolocate.py')
parser.add_argument('-s','--section', help='Specify a section name to write in .ini file.',default='Default')
parser.add_argument('-f', '--filename', help='Write location to this file.',default='~/.sunrise/location.ini')
args = parser.parse_args()
location = args.section
my_latitude, my_longitude = LocationWeb.read ()
print("Location ", location)
print("Latitude ", my_latitude)
print("Longitude ", my_longitude)
LocationConfig.write(location, my_latitude, my_longitude)
main ()
EDIT : Fixed code tag.
